7df3e9d37d9e663de9fae283bb03ac73a84b48f3
[dragonfly.git] / sys / vfs / hammer2 / hammer2_flush.c
1 /*
2  * Copyright (c) 2011-2018 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 /*
36  *                      TRANSACTION AND FLUSH HANDLING
37  *
38  * Deceptively simple but actually fairly difficult to implement properly is
39  * how I would describe it.
40  *
41  * Flushing generally occurs bottom-up but requires a top-down scan to
42  * locate chains with MODIFIED and/or UPDATE bits set.  The ONFLUSH flag
43  * tells how to recurse downward to find these chains.
44  */
45
46 #include <sys/cdefs.h>
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/types.h>
50 #include <sys/lock.h>
51 #include <sys/uuid.h>
52
53 #include "hammer2.h"
54
55 #define FLUSH_DEBUG 0
56
57 #define HAMMER2_FLUSH_DEPTH_LIMIT       60      /* stack recursion limit */
58
59
60 /*
61  * Recursively flush the specified chain.  The chain is locked and
62  * referenced by the caller and will remain so on return.  The chain
63  * will remain referenced throughout but can temporarily lose its
64  * lock during the recursion to avoid unnecessarily stalling user
65  * processes.
66  */
67 struct hammer2_flush_info {
68         hammer2_chain_t *parent;
69         int             depth;
70         int             error;                  /* cumulative error */
71         int             flags;
72 #ifdef HAMMER2_SCAN_DEBUG
73         long            scan_count;
74         long            scan_mod_count;
75         long            scan_upd_count;
76         long            scan_onf_count;
77         long            scan_del_count;
78         long            scan_btype[7];
79 #endif
80         hammer2_chain_t *debug;
81 };
82
83 typedef struct hammer2_flush_info hammer2_flush_info_t;
84
85 static int hammer2_flush_core(hammer2_flush_info_t *info,
86                                 hammer2_chain_t *chain, int flags);
87 static int hammer2_flush_recurse(hammer2_chain_t *child, void *data);
88
89 /*
90  * Any per-pfs transaction initialization goes here.
91  */
92 void
93 hammer2_trans_manage_init(hammer2_pfs_t *pmp)
94 {
95 }
96
97 /*
98  * Transaction support for any modifying operation.  Transactions are used
99  * in the pmp layer by the frontend and in the spmp layer by the backend.
100  *
101  * 0                    - Normal transaction.  Interlocks against just the
102  *                        COPYQ portion of an ISFLUSH transaction.
103  *
104  * TRANS_ISFLUSH        - Flush transaction.  Interlocks against other flush
105  *                        transactions.
106  *
107  *                        When COPYQ is also specified, waits for the count
108  *                        to drop to 1.
109  *
110  * TRANS_BUFCACHE       - Buffer cache transaction.  No interlock.
111  *
112  * TRANS_SIDEQ          - Run the sideq (only tested in trans_done())
113  *
114  * Initializing a new transaction allocates a transaction ID.  Typically
115  * passed a pmp (hmp passed as NULL), indicating a cluster transaction.  Can
116  * be passed a NULL pmp and non-NULL hmp to indicate a transaction on a single
117  * media target.  The latter mode is used by the recovery code.
118  */
119 void
120 hammer2_trans_init(hammer2_pfs_t *pmp, uint32_t flags)
121 {
122         uint32_t oflags;
123         uint32_t nflags;
124         int dowait;
125
126         for (;;) {
127                 oflags = pmp->trans.flags;
128                 cpu_ccfence();
129                 dowait = 0;
130
131                 if (flags & HAMMER2_TRANS_ISFLUSH) {
132                         /*
133                          * Interlock against other flush transactions.
134                          */
135                         if (oflags & HAMMER2_TRANS_ISFLUSH) {
136                                 nflags = oflags | HAMMER2_TRANS_WAITING;
137                                 dowait = 1;
138                         } else {
139                                 nflags = (oflags | flags) + 1;
140                         }
141                 } else if (flags & HAMMER2_TRANS_BUFCACHE) {
142                         /*
143                          * Requesting strategy transaction from buffer-cache,
144                          * or a VM getpages/putpages through the buffer cache.
145                          * We must allow such transactions in all situations
146                          * to avoid deadlocks.
147                          */
148                         nflags = (oflags | flags) + 1;
149                 } else {
150                         /*
151                          * Normal transaction.  We currently only interlock
152                          * against COPYQ.  We do not interlock against
153                          * BUFCACHE or ISFLUSH.  COPYQ is used to interlock
154                          * the transfer of SIDEQ into SYNCQ.
155                          *
156                          * Note that vnode locks may be held going into
157                          * this call.
158                          *
159                          * NOTE: Remember that non-modifying operations
160                          *       such as read, stat, readdir, etc, do
161                          *       not use transactions.
162                          */
163                         if (oflags & HAMMER2_TRANS_COPYQ) {
164                                 nflags = oflags | HAMMER2_TRANS_WAITING;
165                                 dowait = 1;
166                         } else {
167                                 nflags = (oflags | flags) + 1;
168                         }
169                 }
170                 if (dowait)
171                         tsleep_interlock(&pmp->trans.sync_wait, 0);
172                 if (atomic_cmpset_int(&pmp->trans.flags, oflags, nflags)) {
173                         if (dowait == 0)
174                                 break;
175                         tsleep(&pmp->trans.sync_wait, PINTERLOCKED,
176                                "h2trans", hz);
177                         /* retry */
178                 } else {
179                         cpu_pause();
180                         /* retry */
181                 }
182                 /* retry */
183         }
184
185         /*
186          * When entering a FLUSH transaction with COPYQ set, wait for the
187          * transaction count to drop to 1 (our flush transaction only)
188          * before proceeding.
189          *
190          * This waits for all non-flush transactions to complete and blocks
191          * new non-flush transactions from starting until COPYQ is cleared.
192          * (the flush will then proceed after clearing COPYQ).  This should
193          * be a very short stall on modifying operations.
194          */
195         while ((flags & HAMMER2_TRANS_ISFLUSH) &&
196                (flags & HAMMER2_TRANS_COPYQ)) {
197                 oflags = pmp->trans.flags;
198                 cpu_ccfence();
199                 if ((oflags & HAMMER2_TRANS_MASK) == 1)
200                         break;
201                 nflags = oflags | HAMMER2_TRANS_WAITING;
202                 tsleep_interlock(&pmp->trans.sync_wait, 0);
203                 if (atomic_cmpset_int(&pmp->trans.flags, oflags, nflags)) {
204                         tsleep(&pmp->trans.sync_wait, PINTERLOCKED,
205                                "h2trans2", hz);
206                 }
207         }
208 }
209
210 /*
211  * Start a sub-transaction, there is no 'subdone' function.  This will
212  * issue a new modify_tid (mtid) for the current transaction, which is a
213  * CLC (cluster level change) id and not a per-node id.
214  *
215  * This function must be called for each XOP when multiple XOPs are run in
216  * sequence within a transaction.
217  *
218  * Callers typically update the inode with the transaction mtid manually
219  * to enforce sequencing.
220  */
221 hammer2_tid_t
222 hammer2_trans_sub(hammer2_pfs_t *pmp)
223 {
224         hammer2_tid_t mtid;
225
226         mtid = atomic_fetchadd_64(&pmp->modify_tid, 1);
227
228         return (mtid);
229 }
230
231 void
232 hammer2_trans_setflags(hammer2_pfs_t *pmp, uint32_t flags)
233 {
234         atomic_set_int(&pmp->trans.flags, flags);
235 }
236
237 /*
238  * Typically used to clear trans flags asynchronously.  If TRANS_WAITING
239  * is in the mask, and was previously set, this function will wake up
240  * any waiters.
241  */
242 void
243 hammer2_trans_clearflags(hammer2_pfs_t *pmp, uint32_t flags)
244 {
245         uint32_t oflags;
246         uint32_t nflags;
247
248         for (;;) {
249                 oflags = pmp->trans.flags;
250                 cpu_ccfence();
251                 nflags = oflags & ~flags;
252                 if (atomic_cmpset_int(&pmp->trans.flags, oflags, nflags)) {
253                         if ((oflags ^ nflags) & HAMMER2_TRANS_WAITING)
254                                 wakeup(&pmp->trans.sync_wait);
255                         break;
256                 }
257                 cpu_pause();
258                 /* retry */
259         }
260 }
261
262 void
263 hammer2_trans_done(hammer2_pfs_t *pmp, uint32_t flags)
264 {
265         uint32_t oflags;
266         uint32_t nflags;
267
268         /*
269          * Modifying ops on the front-end can cause dirty inodes to
270          * build up in the sideq.  We don't flush these on inactive/reclaim
271          * due to potential deadlocks, so we have to deal with them from
272          * inside other nominal modifying front-end transactions.
273          */
274         if ((flags & HAMMER2_TRANS_SIDEQ) &&
275             pmp->sideq_count > (pmp->inum_count >> 3) &&
276             pmp->mp) {
277                 speedup_syncer(pmp->mp);
278         }
279
280         /*
281          * Clean-up the transaction.  Wakeup any waiters when finishing
282          * a flush transaction or transitioning the non-flush transaction
283          * count from 2->1 while a flush transaction is pending.
284          */
285         for (;;) {
286                 oflags = pmp->trans.flags;
287                 cpu_ccfence();
288                 KKASSERT(oflags & HAMMER2_TRANS_MASK);
289
290                 nflags = (oflags - 1) & ~flags;
291                 if (flags & HAMMER2_TRANS_ISFLUSH) {
292                         nflags &= ~HAMMER2_TRANS_WAITING;
293                 }
294                 if ((oflags & (HAMMER2_TRANS_ISFLUSH|HAMMER2_TRANS_MASK)) ==
295                     (HAMMER2_TRANS_ISFLUSH|2)) {
296                         nflags &= ~HAMMER2_TRANS_WAITING;
297                 }
298                 if (atomic_cmpset_int(&pmp->trans.flags, oflags, nflags)) {
299                         if ((oflags ^ nflags) & HAMMER2_TRANS_WAITING)
300                                 wakeup(&pmp->trans.sync_wait);
301                         break;
302                 }
303                 cpu_pause();
304                 /* retry */
305         }
306 }
307
308 /*
309  * Obtain new, unique inode number (not serialized by caller).
310  */
311 hammer2_tid_t
312 hammer2_trans_newinum(hammer2_pfs_t *pmp)
313 {
314         hammer2_tid_t tid;
315
316         tid = atomic_fetchadd_64(&pmp->inode_tid, 1);
317
318         return tid;
319 }
320
321 /*
322  * Assert that a strategy call is ok here.  Currently we allow strategy
323  * calls in all situations, including during flushes.  Previously:
324  *      (old) (1) In a normal transaction.
325  *      (old) (2) In a flush transaction only if PREFLUSH is also set.
326  */
327 void
328 hammer2_trans_assert_strategy(hammer2_pfs_t *pmp)
329 {
330 #if 0
331         KKASSERT((pmp->trans.flags & HAMMER2_TRANS_ISFLUSH) == 0 ||
332                  (pmp->trans.flags & HAMMER2_TRANS_PREFLUSH));
333 #endif
334 }
335
336 /*
337  * Flush the chain and all modified sub-chains through the specified
338  * synchronization point, propagating blockref updates back up.  As
339  * part of this propagation, mirror_tid and inode/data usage statistics
340  * propagates back upward.
341  *
342  * Returns a HAMMER2 error code, 0 if no error.  Note that I/O errors from
343  * buffers dirtied during the flush operation can occur later.
344  *
345  * modify_tid (clc - cluster level change) is not propagated.
346  *
347  * update_tid (clc) is used for validation and is not propagated by this
348  * function.
349  *
350  * This routine can be called from several places but the most important
351  * is from VFS_SYNC (frontend) via hammer2_xop_inode_flush (backend).
352  *
353  * chain is locked on call and will remain locked on return.  The chain's
354  * UPDATE flag indicates that its parent's block table (which is not yet
355  * part of the flush) should be updated.
356  *
357  * flags:
358  *      HAMMER2_FLUSH_TOP       Indicates that this is the top of the flush.
359  *                              Is cleared for the recursion.
360  *
361  *      HAMMER2_FLUSH_ALL       Recurse everything
362  *
363  *      HAMMER2_FLUSH_INODE_STOP
364  *                              Stop at PFS inode or normal inode boundary
365  */
366 int
367 hammer2_flush(hammer2_chain_t *chain, int flags)
368 {
369         hammer2_flush_info_t info;
370         hammer2_dev_t *hmp;
371         int loops;
372
373         /*
374          * Execute the recursive flush and handle deferrals.
375          *
376          * Chains can be ridiculously long (thousands deep), so to
377          * avoid blowing out the kernel stack the recursive flush has a
378          * depth limit.  Elements at the limit are placed on a list
379          * for re-execution after the stack has been popped.
380          */
381         bzero(&info, sizeof(info));
382         info.flags = flags & ~HAMMER2_FLUSH_TOP;
383
384         /*
385          * Calculate parent (can be NULL), if not NULL the flush core
386          * expects the parent to be referenced so it can easily lock/unlock
387          * it without it getting ripped up.
388          */
389         if ((info.parent = chain->parent) != NULL)
390                 hammer2_chain_ref(info.parent);
391
392         /*
393          * Extra ref needed because flush_core expects it when replacing
394          * chain.
395          */
396         hammer2_chain_ref(chain);
397         hmp = chain->hmp;
398         loops = 0;
399
400         for (;;) {
401                 /*
402                  * [re]flush chain as the deep recursion may have generated
403                  * additional modifications.
404                  */
405                 if (info.parent != chain->parent) {
406                         if (hammer2_debug & 0x0040) {
407                                 kprintf("LOST CHILD4 %p->%p "
408                                         "(actual parent %p)\n",
409                                         info.parent, chain, chain->parent);
410                         }
411                         hammer2_chain_drop(info.parent);
412                         info.parent = chain->parent;
413                         hammer2_chain_ref(info.parent);
414                 }
415                 if (hammer2_flush_core(&info, chain, flags) == 0)
416                         break;
417
418                 if (++loops % 1000 == 0) {
419                         kprintf("hammer2_flush: excessive loops on %p\n",
420                                 chain);
421                         if (hammer2_debug & 0x100000)
422                                 Debugger("hell4");
423                 }
424         }
425 #ifdef HAMMER2_SCAN_DEBUG
426         if (info.scan_count >= 10)
427         kprintf("hammer2_flush: scan_count %ld (%ld,%ld,%ld,%ld) "
428                 "bt(%ld,%ld,%ld,%ld,%ld,%ld)\n",
429                 info.scan_count,
430                 info.scan_mod_count,
431                 info.scan_upd_count,
432                 info.scan_onf_count,
433                 info.scan_del_count,
434                 info.scan_btype[1],
435                 info.scan_btype[2],
436                 info.scan_btype[3],
437                 info.scan_btype[4],
438                 info.scan_btype[5],
439                 info.scan_btype[6]);
440 #endif
441         hammer2_chain_drop(chain);
442         if (info.parent)
443                 hammer2_chain_drop(info.parent);
444         return (info.error);
445 }
446
447 /*
448  * This is the core of the chain flushing code.  The chain is locked by the
449  * caller and must also have an extra ref on it by the caller, and remains
450  * locked and will have an extra ref on return.  info.parent is referenced
451  * but not locked.
452  *
453  * Upon return, the caller can test the UPDATE bit on the chain to determine
454  * if the parent needs updating.
455  *
456  * If non-zero is returned, the chain's parent changed during the flush and
457  * the caller must retry the operation.
458  *
459  * (1) Determine if this node is a candidate for the flush, return if it is
460  *     not.  fchain and vchain are always candidates for the flush.
461  *
462  * (2) If we recurse too deep the chain is entered onto the deferral list and
463  *     the current flush stack is aborted until after the deferral list is
464  *     run.
465  *
466  * (3) Recursively flush live children (rbtree).  This can create deferrals.
467  *     A successful flush clears the MODIFIED and UPDATE bits on the children
468  *     and typically causes the parent to be marked MODIFIED as the children
469  *     update the parent's block table.  A parent might already be marked
470  *     MODIFIED due to a deletion (whos blocktable update in the parent is
471  *     handled by the frontend), or if the parent itself is modified by the
472  *     frontend for other reasons.
473  *
474  * (4) Permanently disconnected sub-trees are cleaned up by the front-end.
475  *     Deleted-but-open inodes can still be individually flushed via the
476  *     filesystem syncer.
477  *
478  * (5) Delete parents on the way back up if they are normal indirect blocks
479  *     and have no children.
480  *
481  * (6) Note that an unmodified child may still need the block table in its
482  *     parent updated (e.g. rename/move).  The child will have UPDATE set
483  *     in this case.
484  *
485  *                      WARNING ON BREF MODIFY_TID/MIRROR_TID
486  *
487  * blockref.modify_tid is consistent only within a PFS, and will not be
488  * consistent during synchronization.  mirror_tid is consistent across the
489  * block device regardless of the PFS.
490  */
491 static int
492 hammer2_flush_core(hammer2_flush_info_t *info, hammer2_chain_t *chain,
493                    int flags)
494 {
495         hammer2_chain_t *parent;
496         hammer2_dev_t *hmp;
497         int save_error;
498         int retry;
499
500         retry = 0;
501
502         /*
503          * (1) Optimize downward recursion to locate nodes needing action.
504          *     Nothing to do if none of these flags are set.
505          */
506         if ((chain->flags & HAMMER2_CHAIN_FLUSH_MASK) == 0) {
507                 if (hammer2_debug & 0x200) {
508                         if (info->debug == NULL)
509                                 info->debug = chain;
510                 } else {
511                         return 0;
512                 }
513         }
514
515         hmp = chain->hmp;
516
517         /*
518          * NOTE: parent can be NULL, usually due to destroy races.
519          */
520         parent = info->parent;
521         KKASSERT(chain->parent == parent);
522
523         /*
524          * Downward search recursion
525          *
526          * We must be careful on cold stops.  If CHAIN_UPDATE is set and
527          * we stop cold, the update can wind up never being applied.  This
528          * situation most typically occurs on inode boundaries due to the way
529          * hammer2_vfs_sync() breaks-up the flush.  As a safety, we
530          * flush-through such situations. XXX removed
531          */
532         if ((chain->flags & HAMMER2_CHAIN_PFSBOUNDARY) &&
533                    /* (chain->flags & HAMMER2_CHAIN_UPDATE) == 0 && */
534                    (flags & HAMMER2_FLUSH_ALL) == 0 &&
535                    (flags & HAMMER2_FLUSH_TOP) == 0 &&
536                    chain->pmp && chain->pmp->mp) {
537                 /*
538                  * If FLUSH_ALL is not specified the caller does not want
539                  * to recurse through PFS roots that have been mounted.
540                  *
541                  * (If the PFS has not been mounted there may not be
542                  *  anything monitoring its chains and its up to us
543                  *  to flush it).
544                  *
545                  * The typical sequence is to flush dirty PFS's starting at
546                  * their root downward, then flush the device root (vchain).
547                  * It is this second flush that typically leaves out the
548                  * ALL flag.
549                  *
550                  * However we must still process the PFSROOT chains for block
551                  * table updates in their parent (which IS part of our flush).
552                  *
553                  * NOTE: The volume root, vchain, does not set PFSBOUNDARY.
554                  *
555                  * NOTE: We must re-set ONFLUSH in the parent to retain if
556                  *       this chain (that we are skipping) requires work.
557                  */
558                 if (chain->flags & (HAMMER2_CHAIN_ONFLUSH |
559                                     HAMMER2_CHAIN_DESTROY |
560                                     HAMMER2_CHAIN_MODIFIED)) {
561                         hammer2_chain_setflush(parent);
562                 }
563                 goto done;
564         } else if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
565                    /* (chain->flags & HAMMER2_CHAIN_UPDATE) == 0 && */
566                    (flags & HAMMER2_FLUSH_INODE_STOP) &&
567                    (flags & HAMMER2_FLUSH_ALL) == 0 &&
568                    (flags & HAMMER2_FLUSH_TOP) == 0 &&
569                    chain->pmp && chain->pmp->mp) {
570                 /*
571                  * When FLUSH_INODE_STOP is specified we are being asked not
572                  * to include any inode changes for inodes we encounter,
573                  * with the exception of the inode that the flush began with.
574                  * So: INODE, INODE_STOP, and TOP==0 basically.
575                  */
576                 goto done;
577 #if 0
578                 /*
579                  * If FLUSH_INODE_STOP is specified and both ALL and TOP
580                  * are clear, we must not flush the chain.  The chain should
581                  * have already been flushed and any further ONFLUSH/UPDATE
582                  * setting will be related to the next flush.
583                  *
584                  * This features allows us to flush inodes independently of
585                  * each other and meta-data above the inodes separately.
586                  */
587                 if (chain->flags & (HAMMER2_CHAIN_ONFLUSH |
588                                     HAMMER2_CHAIN_DESTROY |
589                                     HAMMER2_CHAIN_MODIFIED)) {
590                         if (parent)
591                                 hammer2_chain_setflush(parent);
592                 }
593 #endif
594         } else if (info->depth == HAMMER2_FLUSH_DEPTH_LIMIT) {
595                 /*
596                  * Recursion depth reached.
597                  */
598                 panic("hammer2: flush depth limit");
599         } else if (chain->flags & (HAMMER2_CHAIN_ONFLUSH |
600                                    HAMMER2_CHAIN_DESTROY)) {
601                 /*
602                  * Downward recursion search (actual flush occurs bottom-up).
603                  * pre-clear ONFLUSH.  It can get set again due to races or
604                  * flush errors, which we want so the scan finds us again in
605                  * the next flush.
606                  *
607                  * We must also recurse if DESTROY is set so we can finally
608                  * get rid of the related children, otherwise the node will
609                  * just get re-flushed on lastdrop.
610                  *
611                  * WARNING!  The recursion will unlock/relock info->parent
612                  *           (which is 'chain'), potentially allowing it
613                  *           to be ripped up.
614                  */
615                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
616                 save_error = info->error;
617                 info->error = 0;
618                 info->parent = chain;
619
620                 /*
621                  * We may have to do this twice to catch any indirect
622                  * block maintenance that occurs.
623                  */
624                 hammer2_spin_ex(&chain->core.spin);
625                 RB_SCAN(hammer2_chain_tree, &chain->core.rbtree,
626                         NULL, hammer2_flush_recurse, info);
627                 if (chain->flags & HAMMER2_CHAIN_ONFLUSH) {
628                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
629                         RB_SCAN(hammer2_chain_tree, &chain->core.rbtree,
630                                 NULL, hammer2_flush_recurse, info);
631                 }
632                 hammer2_spin_unex(&chain->core.spin);
633                 info->parent = parent;
634
635                 /*
636                  * Re-set the flush bits if the flush was incomplete or
637                  * an error occurred.  If an error occurs it is typically
638                  * an allocation error.  Errors do not cause deferrals.
639                  */
640                 if (info->error)
641                         hammer2_chain_setflush(chain);
642                 info->error |= save_error;
643
644                 /*
645                  * If we lost the parent->chain association we have to
646                  * stop processing this chain because it is no longer
647                  * in this recursion.  If it moved, it will be handled
648                  * by the ONFLUSH flag elsewhere.
649                  */
650                 if (chain->parent != parent) {
651                         kprintf("LOST CHILD2 %p->%p (actual parent %p)\n",
652                                 parent, chain, chain->parent);
653                         goto done;
654                 }
655         }
656
657         /*
658          * Now we are in the bottom-up part of the recursion.
659          *
660          * We continue to try to update the chain on lower-level errors, but
661          * the flush code may decide not to flush the volume root.
662          *
663          * XXX should we continue to try to update the chain if an error
664          *     occurred?
665          */
666
667         /*
668          * Both parent and chain must be locked in order to flush chain,
669          * in order to properly update the parent under certain conditions.
670          *
671          * In addition, we can't safely unlock/relock the chain once we
672          * start flushing the chain itself, which we would have to do later
673          * on in order to lock the parent if we didn't do that now.
674          */
675         hammer2_chain_ref_hold(chain);
676         hammer2_chain_unlock(chain);
677         if (parent)
678                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
679         hammer2_chain_lock(chain, HAMMER2_RESOLVE_MAYBE);
680         hammer2_chain_drop_unhold(chain);
681
682         /*
683          * Can't process if we can't access their content.
684          */
685         if ((parent && parent->error) || chain->error) {
686                 kprintf("hammer2: chain error during flush\n");
687                 info->error |= chain->error;
688                 if (parent) {
689                         info->error |= parent->error;
690                         hammer2_chain_unlock(parent);
691                 }
692                 goto done;
693         }
694
695         if (chain->parent != parent) {
696                 if (hammer2_debug & 0x0040) {
697                         kprintf("LOST CHILD3 %p->%p (actual parent %p)\n",
698                                 parent, chain, chain->parent);
699                 }
700                 KKASSERT(parent != NULL);
701                 hammer2_chain_unlock(parent);
702                 retry = 1;
703                 goto done;
704         }
705
706         /*
707          * Propagate the DESTROY flag downwards.  This dummies up the flush
708          * code and tries to invalidate related buffer cache buffers to
709          * avoid the disk write.
710          */
711         if (parent && (parent->flags & HAMMER2_CHAIN_DESTROY))
712                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
713
714         /*
715          * Dispose of the modified bit.
716          *
717          * If parent is present, the UPDATE bit should already be set.
718          * UPDATE should already be set.
719          * bref.mirror_tid should already be set.
720          */
721         if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
722                 KKASSERT((chain->flags & HAMMER2_CHAIN_UPDATE) ||
723                          chain->parent == NULL);
724                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
725                 atomic_add_long(&hammer2_count_modified_chains, -1);
726
727                 /*
728                  * Manage threads waiting for excessive dirty memory to
729                  * be retired.
730                  */
731                 if (chain->pmp)
732                         hammer2_pfs_memory_wakeup(chain->pmp);
733
734 #if 0
735                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0 &&
736                     chain != &hmp->vchain &&
737                     chain != &hmp->fchain) {
738                         /*
739                          * Set UPDATE bit indicating that the parent block
740                          * table requires updating.
741                          */
742                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
743                 }
744 #endif
745
746                 /*
747                  * Issue the flush.  This is indirect via the DIO.
748                  *
749                  * NOTE: A DELETED node that reaches this point must be
750                  *       flushed for synchronization point consistency.
751                  *
752                  * NOTE: Even though MODIFIED was already set, the related DIO
753                  *       might not be dirty due to a system buffer cache
754                  *       flush and must be set dirty if we are going to make
755                  *       further modifications to the buffer.  Chains with
756                  *       embedded data don't need this.
757                  */
758                 if (hammer2_debug & 0x1000) {
759                         kprintf("Flush %p.%d %016jx/%d data=%016jx\n",
760                                 chain, chain->bref.type,
761                                 (uintmax_t)chain->bref.key,
762                                 chain->bref.keybits,
763                                 (uintmax_t)chain->bref.data_off);
764                 }
765                 if (hammer2_debug & 0x2000) {
766                         Debugger("Flush hell");
767                 }
768
769                 /*
770                  * Update chain CRCs for flush.
771                  *
772                  * NOTE: Volume headers are NOT flushed here as they require
773                  *       special processing.
774                  */
775                 switch(chain->bref.type) {
776                 case HAMMER2_BREF_TYPE_FREEMAP:
777                         /*
778                          * Update the volume header's freemap_tid to the
779                          * freemap's flushing mirror_tid.
780                          *
781                          * (note: embedded data, do not call setdirty)
782                          */
783                         KKASSERT(hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED);
784                         KKASSERT(chain == &hmp->fchain);
785                         hmp->voldata.freemap_tid = chain->bref.mirror_tid;
786                         if (hammer2_debug & 0x8000) {
787                                 /* debug only, avoid syslogd loop */
788                                 kprintf("sync freemap mirror_tid %08jx\n",
789                                         (intmax_t)chain->bref.mirror_tid);
790                         }
791
792                         /*
793                          * The freemap can be flushed independently of the
794                          * main topology, but for the case where it is
795                          * flushed in the same transaction, and flushed
796                          * before vchain (a case we want to allow for
797                          * performance reasons), make sure modifications
798                          * made during the flush under vchain use a new
799                          * transaction id.
800                          *
801                          * Otherwise the mount recovery code will get confused.
802                          */
803                         ++hmp->voldata.mirror_tid;
804                         break;
805                 case HAMMER2_BREF_TYPE_VOLUME:
806                         /*
807                          * The free block table is flushed by
808                          * hammer2_vfs_sync() before it flushes vchain.
809                          * We must still hold fchain locked while copying
810                          * voldata to volsync, however.
811                          *
812                          * These do not error per-say since their data does
813                          * not need to be re-read from media on lock.
814                          *
815                          * (note: embedded data, do not call setdirty)
816                          */
817                         hammer2_chain_lock(&hmp->fchain,
818                                            HAMMER2_RESOLVE_ALWAYS);
819                         hammer2_voldata_lock(hmp);
820                         if (hammer2_debug & 0x8000) {
821                                 /* debug only, avoid syslogd loop */
822                                 kprintf("sync volume  mirror_tid %08jx\n",
823                                         (intmax_t)chain->bref.mirror_tid);
824                         }
825
826                         /*
827                          * Update the volume header's mirror_tid to the
828                          * main topology's flushing mirror_tid.  It is
829                          * possible that voldata.mirror_tid is already
830                          * beyond bref.mirror_tid due to the bump we made
831                          * above in BREF_TYPE_FREEMAP.
832                          */
833                         if (hmp->voldata.mirror_tid < chain->bref.mirror_tid) {
834                                 hmp->voldata.mirror_tid =
835                                         chain->bref.mirror_tid;
836                         }
837
838                         /*
839                          * The volume header is flushed manually by the
840                          * syncer, not here.  All we do here is adjust the
841                          * crc's.
842                          */
843                         KKASSERT(chain->data != NULL);
844                         KKASSERT(chain->dio == NULL);
845
846                         hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT1]=
847                                 hammer2_icrc32(
848                                         (char *)&hmp->voldata +
849                                          HAMMER2_VOLUME_ICRC1_OFF,
850                                         HAMMER2_VOLUME_ICRC1_SIZE);
851                         hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT0]=
852                                 hammer2_icrc32(
853                                         (char *)&hmp->voldata +
854                                          HAMMER2_VOLUME_ICRC0_OFF,
855                                         HAMMER2_VOLUME_ICRC0_SIZE);
856                         hmp->voldata.icrc_volheader =
857                                 hammer2_icrc32(
858                                         (char *)&hmp->voldata +
859                                          HAMMER2_VOLUME_ICRCVH_OFF,
860                                         HAMMER2_VOLUME_ICRCVH_SIZE);
861
862                         if (hammer2_debug & 0x8000) {
863                                 /* debug only, avoid syslogd loop */
864                                 kprintf("syncvolhdr %016jx %016jx\n",
865                                         hmp->voldata.mirror_tid,
866                                         hmp->vchain.bref.mirror_tid);
867                         }
868                         hmp->volsync = hmp->voldata;
869                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_VOLUMESYNC);
870                         hammer2_voldata_unlock(hmp);
871                         hammer2_chain_unlock(&hmp->fchain);
872                         break;
873                 case HAMMER2_BREF_TYPE_DATA:
874                         /*
875                          * Data elements have already been flushed via the
876                          * logical file buffer cache.  Their hash was set in
877                          * the bref by the vop_write code.  Do not re-dirty.
878                          *
879                          * Make sure any device buffer(s) have been flushed
880                          * out here (there aren't usually any to flush) XXX.
881                          */
882                         break;
883                 case HAMMER2_BREF_TYPE_INDIRECT:
884                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
885                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
886                         /*
887                          * Buffer I/O will be cleaned up when the volume is
888                          * flushed (but the kernel is free to flush it before
889                          * then, as well).
890                          */
891                         KKASSERT((chain->flags & HAMMER2_CHAIN_EMBEDDED) == 0);
892                         hammer2_chain_setcheck(chain, chain->data);
893                         break;
894                 case HAMMER2_BREF_TYPE_DIRENT:
895                         /*
896                          * A directory entry can use the check area to store
897                          * the filename for filenames <= 64 bytes, don't blow
898                          * it up!
899                          */
900                         KKASSERT((chain->flags & HAMMER2_CHAIN_EMBEDDED) == 0);
901                         if (chain->bytes)
902                                 hammer2_chain_setcheck(chain, chain->data);
903                         break;
904                 case HAMMER2_BREF_TYPE_INODE:
905                         /*
906                          * NOTE: We must call io_setdirty() to make any late
907                          *       changes to the inode data, the system might
908                          *       have already flushed the buffer.
909                          */
910                         if (chain->data->ipdata.meta.op_flags &
911                             HAMMER2_OPFLAG_PFSROOT) {
912                                 /*
913                                  * non-NULL pmp if mounted as a PFS.  We must
914                                  * sync fields cached in the pmp? XXX
915                                  */
916                                 hammer2_inode_data_t *ipdata;
917
918                                 hammer2_io_setdirty(chain->dio);
919                                 ipdata = &chain->data->ipdata;
920                                 if (chain->pmp) {
921                                         ipdata->meta.pfs_inum =
922                                                 chain->pmp->inode_tid;
923                                 }
924                         } else {
925                                 /* can't be mounted as a PFS */
926                         }
927
928                         KKASSERT((chain->flags & HAMMER2_CHAIN_EMBEDDED) == 0);
929                         hammer2_chain_setcheck(chain, chain->data);
930
931                                 hammer2_inode_data_t *ipdata;
932                         ipdata = &chain->data->ipdata;
933                         break;
934                 default:
935                         KKASSERT(chain->flags & HAMMER2_CHAIN_EMBEDDED);
936                         panic("hammer2_flush_core: unsupported "
937                               "embedded bref %d",
938                               chain->bref.type);
939                         /* NOT REACHED */
940                 }
941
942                 /*
943                  * If the chain was destroyed try to avoid unnecessary I/O
944                  * that might not have yet occurred.  Remove the data range
945                  * from dedup candidacy and attempt to invalidation that
946                  * potentially dirty portion of the I/O buffer.
947                  */
948                 if (chain->flags & HAMMER2_CHAIN_DESTROY) {
949                         hammer2_io_dedup_delete(hmp,
950                                                 chain->bref.type,
951                                                 chain->bref.data_off,
952                                                 chain->bytes);
953 #if 0
954                         hammer2_io_t *dio;
955                         if (chain->dio) {
956                                 hammer2_io_inval(chain->dio,
957                                                  chain->bref.data_off,
958                                                  chain->bytes);
959                         } else if ((dio = hammer2_io_getquick(hmp,
960                                                   chain->bref.data_off,
961                                                   chain->bytes,
962                                                   1)) != NULL) {
963                                 hammer2_io_inval(dio,
964                                                  chain->bref.data_off,
965                                                  chain->bytes);
966                                 hammer2_io_putblk(&dio);
967                         }
968 #endif
969                 }
970         }
971
972         /*
973          * If UPDATE is set the parent block table may need to be updated.
974          * This can fail if the hammer2_chain_modify() fails.
975          *
976          * NOTE: UPDATE may be set on vchain or fchain in which case
977          *       parent could be NULL, or on an inode that has not yet
978          *       been inserted into the radix tree.  It's easiest to allow
979          *       the case and test for NULL.  parent can also wind up being
980          *       NULL due to a deletion so we need to handle the case anyway.
981          *
982          * NOTE: UPDATE can be set when chains are renamed into or out of
983          *       an indirect block, without the chain itself being flagged
984          *       MODIFIED.
985          *
986          * If no parent exists we can just clear the UPDATE bit.  If the
987          * chain gets reattached later on the bit will simply get set
988          * again.
989          */
990         if ((chain->flags & HAMMER2_CHAIN_UPDATE) && parent == NULL)
991                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
992
993         /*
994          * When flushing an inode outside of a FLUSH_FSSYNC we must NOT
995          * update the parent block table to point at the flushed inode.
996          * The block table should only ever be updated by the filesystem
997          * sync code.  If we do, inode<->inode dependencies (such as
998          * directory entries vs inode nlink count) can wind up not being
999          * flushed together and result in a broken topology if a crash/reboot
1000          * occurs at the wrong time.
1001          */
1002         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
1003             (flags & HAMMER2_FLUSH_FSSYNC) == 0 &&
1004             (flags & HAMMER2_FLUSH_ALL) == 0 &&
1005             chain->pmp && chain->pmp->mp) {
1006                 goto skipupdate;
1007         }
1008
1009         /*
1010          * The chain may need its blockrefs updated in the parent, normal
1011          * path.
1012          */
1013         if (chain->flags & HAMMER2_CHAIN_UPDATE) {
1014                 hammer2_blockref_t *base;
1015                 int count;
1016
1017                 /*
1018                  * Clear UPDATE flag, mark parent modified, update its
1019                  * modify_tid if necessary, and adjust the parent blockmap.
1020                  */
1021                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1022
1023                 /*
1024                  * (optional code)
1025                  *
1026                  * Avoid actually modifying and updating the parent if it
1027                  * was flagged for destruction.  This can greatly reduce
1028                  * disk I/O in large tree removals because the
1029                  * hammer2_io_setinval() call in the upward recursion
1030                  * (see MODIFIED code above) can only handle a few cases.
1031                  */
1032                 if (parent->flags & HAMMER2_CHAIN_DESTROY) {
1033                         if (parent->bref.modify_tid < chain->bref.modify_tid) {
1034                                 parent->bref.modify_tid =
1035                                         chain->bref.modify_tid;
1036                         }
1037                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
1038                                                         HAMMER2_CHAIN_BMAPUPD);
1039                         goto skipupdate;
1040                 }
1041
1042                 /*
1043                  * The flusher is responsible for deleting empty indirect
1044                  * blocks at this point.  If we don't do this, no major harm
1045                  * will be done but the empty indirect blocks will stay in
1046                  * the topology and make it a messy and inefficient.
1047                  *
1048                  * The flusher is also responsible for collapsing the
1049                  * content of an indirect block into its parent whenever
1050                  * possible (with some hysteresis).  Not doing this will also
1051                  * not harm the topology, but would make it messy and
1052                  * inefficient.
1053                  */
1054                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT) {
1055                         if (hammer2_chain_indirect_maintenance(parent, chain))
1056                                 goto skipupdate;
1057                 }
1058
1059                 /*
1060                  * We are updating the parent's blockmap, the parent must
1061                  * be set modified.  If this fails we re-set the UPDATE flag
1062                  * in the child.
1063                  *
1064                  * NOTE! A modification error can be ENOSPC.  We still want
1065                  *       to flush modified chains recursively, not break out,
1066                  *       so we just skip the update in this situation and
1067                  *       continue.  That is, we still need to try to clean
1068                  *       out dirty chains and buffers.
1069                  *
1070                  *       This may not help bulkfree though. XXX
1071                  */
1072                 save_error = hammer2_chain_modify(parent, 0, 0, 0);
1073                 if (save_error) {
1074                         info->error |= save_error;
1075                         kprintf("hammer2_flush: %016jx.%02x error=%08x\n",
1076                                 parent->bref.data_off, parent->bref.type,
1077                                 save_error);
1078                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1079                         goto skipupdate;
1080                 }
1081                 if (parent->bref.modify_tid < chain->bref.modify_tid)
1082                         parent->bref.modify_tid = chain->bref.modify_tid;
1083
1084                 /*
1085                  * Calculate blockmap pointer
1086                  */
1087                 switch(parent->bref.type) {
1088                 case HAMMER2_BREF_TYPE_INODE:
1089                         /*
1090                          * Access the inode's block array.  However, there is
1091                          * no block array if the inode is flagged DIRECTDATA.
1092                          */
1093                         if (parent->data &&
1094                             (parent->data->ipdata.meta.op_flags &
1095                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
1096                                 base = &parent->data->
1097                                         ipdata.u.blockset.blockref[0];
1098                         } else {
1099                                 base = NULL;
1100                         }
1101                         count = HAMMER2_SET_COUNT;
1102                         break;
1103                 case HAMMER2_BREF_TYPE_INDIRECT:
1104                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1105                         if (parent->data)
1106                                 base = &parent->data->npdata[0];
1107                         else
1108                                 base = NULL;
1109                         count = parent->bytes / sizeof(hammer2_blockref_t);
1110                         break;
1111                 case HAMMER2_BREF_TYPE_VOLUME:
1112                         base = &chain->hmp->voldata.sroot_blockset.blockref[0];
1113                         count = HAMMER2_SET_COUNT;
1114                         break;
1115                 case HAMMER2_BREF_TYPE_FREEMAP:
1116                         base = &parent->data->npdata[0];
1117                         count = HAMMER2_SET_COUNT;
1118                         break;
1119                 default:
1120                         base = NULL;
1121                         count = 0;
1122                         panic("hammer2_flush_core: "
1123                               "unrecognized blockref type: %d",
1124                               parent->bref.type);
1125                 }
1126
1127                 /*
1128                  * Blocktable updates
1129                  *
1130                  * We synchronize pending statistics at this time.  Delta
1131                  * adjustments designated for the current and upper level
1132                  * are synchronized.
1133                  */
1134                 if (base && (chain->flags & HAMMER2_CHAIN_BMAPUPD)) {
1135                         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
1136                                 hammer2_spin_ex(&parent->core.spin);
1137                                 hammer2_base_delete(parent, base, count, chain,
1138                                                     NULL);
1139                                 hammer2_spin_unex(&parent->core.spin);
1140                                 /* base_delete clears both bits */
1141                         } else {
1142                                 atomic_clear_int(&chain->flags,
1143                                                  HAMMER2_CHAIN_BMAPUPD);
1144                         }
1145                 }
1146                 if (base && (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
1147                         hammer2_spin_ex(&parent->core.spin);
1148                         hammer2_base_insert(parent, base, count,
1149                                             chain, &chain->bref);
1150                         hammer2_spin_unex(&parent->core.spin);
1151                         /* base_insert sets BMAPPED */
1152                 }
1153         }
1154 skipupdate:
1155         if (parent)
1156                 hammer2_chain_unlock(parent);
1157
1158         /*
1159          * Final cleanup after flush
1160          */
1161 done:
1162         KKASSERT(chain->refs > 0);
1163         if (hammer2_debug & 0x200) {
1164                 if (info->debug == chain)
1165                         info->debug = NULL;
1166         }
1167         return retry;
1168 }
1169
1170 /*
1171  * Flush recursion helper, called from flush_core, calls flush_core.
1172  *
1173  * Flushes the children of the caller's chain (info->parent), restricted
1174  * by sync_tid.  Set info->domodify if the child's blockref must propagate
1175  * back up to the parent.
1176  *
1177  * This function may set info->error as a side effect.
1178  *
1179  * Ripouts can move child from rbtree to dbtree or dbq but the caller's
1180  * flush scan order prevents any chains from being lost.  A child can be
1181  * executes more than once.
1182  *
1183  * WARNING! If we do not call hammer2_flush_core() we must update
1184  *          bref.mirror_tid ourselves to indicate that the flush has
1185  *          processed the child.
1186  *
1187  * WARNING! parent->core spinlock is held on entry and return.
1188  */
1189 static int
1190 hammer2_flush_recurse(hammer2_chain_t *child, void *data)
1191 {
1192         hammer2_flush_info_t *info = data;
1193         hammer2_chain_t *parent = info->parent;
1194
1195 #ifdef HAMMER2_SCAN_DEBUG
1196         ++info->scan_count;
1197         if (child->flags & HAMMER2_CHAIN_MODIFIED)
1198                 ++info->scan_mod_count;
1199         if (child->flags & HAMMER2_CHAIN_UPDATE)
1200                 ++info->scan_upd_count;
1201         if (child->flags & HAMMER2_CHAIN_ONFLUSH)
1202                 ++info->scan_onf_count;
1203 #endif
1204
1205         /*
1206          * (child can never be fchain or vchain so a special check isn't
1207          *  needed).
1208          *
1209          * We must ref the child before unlocking the spinlock.
1210          *
1211          * The caller has added a ref to the parent so we can temporarily
1212          * unlock it in order to lock the child.  However, if it no longer
1213          * winds up being the child of the parent we must skip this child.
1214          *
1215          * NOTE! chain locking errors are fatal.  They are never out-of-space
1216          *       errors.
1217          */
1218         hammer2_chain_ref(child);
1219         hammer2_spin_unex(&parent->core.spin);
1220
1221         hammer2_chain_ref_hold(parent);
1222         hammer2_chain_unlock(parent);
1223         hammer2_chain_lock(child, HAMMER2_RESOLVE_MAYBE);
1224         if (child->parent != parent) {
1225                 kprintf("LOST CHILD1 %p->%p (actual parent %p)\n",
1226                         parent, child, child->parent);
1227                 goto done;
1228         }
1229         if (child->error) {
1230                 kprintf("CHILD ERROR DURING FLUSH LOCK %p->%p\n",
1231                         parent, child);
1232                 info->error |= child->error;
1233                 goto done;
1234         }
1235
1236         /*
1237          * Must propagate the DESTROY flag downwards, otherwise the
1238          * parent could end up never being removed because it will
1239          * be requeued to the flusher if it survives this run due to
1240          * the flag.
1241          */
1242         if (parent && (parent->flags & HAMMER2_CHAIN_DESTROY))
1243                 atomic_set_int(&child->flags, HAMMER2_CHAIN_DESTROY);
1244 #ifdef HAMMER2_SCAN_DEBUG
1245         if (child->flags & HAMMER2_CHAIN_DESTROY)
1246                 ++info->scan_del_count;
1247 #endif
1248         /*
1249          * Special handling of the root inode.  Because the root inode
1250          * contains an index of all the inodes in the PFS in addition to
1251          * its normal directory entries, any flush that is not part of a
1252          * filesystem sync must only flush the directory entries, and not
1253          * anything else.
1254          *
1255          * The child might be an indirect block, but H2 guarantees that
1256          * the key-range will fully partition the inode index from the
1257          * directory entries so the case just works naturally.
1258          */
1259         if ((parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT) &&
1260             (child->flags & HAMMER2_CHAIN_DESTROY) == 0 &&
1261             parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
1262             (info->flags & HAMMER2_FLUSH_FSSYNC) == 0) {
1263                 if ((child->bref.key & HAMMER2_DIRHASH_VISIBLE) == 0) {
1264                         if (child->flags & HAMMER2_CHAIN_FLUSH_MASK) {
1265                                 hammer2_chain_setflush(parent);
1266                         }
1267                         goto done;
1268                 }
1269         }
1270
1271         /*
1272          * Recurse and collect deferral data.  We're in the media flush,
1273          * this can cross PFS boundaries.
1274          */
1275         if (child->flags & HAMMER2_CHAIN_FLUSH_MASK) {
1276 #ifdef HAMMER2_SCAN_DEBUG
1277                 if (child->bref.type < 7)
1278                         ++info->scan_btype[child->bref.type];
1279 #endif
1280                 ++info->depth;
1281                 hammer2_flush_core(info, child, info->flags);
1282                 --info->depth;
1283         } else if (hammer2_debug & 0x200) {
1284                 if (info->debug == NULL)
1285                         info->debug = child;
1286                 ++info->depth;
1287                 hammer2_flush_core(info, child, info->flags);
1288                 --info->depth;
1289                 if (info->debug == child)
1290                         info->debug = NULL;
1291         }
1292
1293 done:
1294         /*
1295          * Relock to continue the loop.
1296          */
1297         hammer2_chain_unlock(child);
1298         hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
1299         hammer2_chain_drop_unhold(parent);
1300         if (parent->error) {
1301                 kprintf("PARENT ERROR DURING FLUSH LOCK %p->%p\n",
1302                         parent, child);
1303                 info->error |= parent->error;
1304         }
1305         hammer2_chain_drop(child);
1306         KKASSERT(info->parent == parent);
1307         hammer2_spin_ex(&parent->core.spin);
1308
1309         return (0);
1310 }
1311
1312 /*
1313  * flush helper (backend threaded)
1314  *
1315  * Flushes chain topology for the specified inode.
1316  *
1317  * HAMMER2_XOP_INODE_STOP       The flush recursion stops at inode boundaries.
1318  *                              Inodes belonging to the same flush are flushed
1319  *                              separately.
1320  *
1321  * HAMMER2_XOP_PARENTONFLUSH    After flushing if the starting chain indicates
1322  *                              a parent update is needed, we setflush the
1323  *                              parent to propogate the flush request across
1324  *                              the inode.
1325  *
1326  * chain->parent can be NULL, usually due to destroy races or detached inodes.
1327  *
1328  * Primarily called from vfs_sync().
1329  */
1330 void
1331 hammer2_xop_inode_flush(hammer2_xop_t *arg, void *scratch __unused, int clindex)
1332 {
1333         hammer2_xop_flush_t *xop = &arg->xop_flush;
1334         hammer2_chain_t *chain;
1335         hammer2_dev_t *hmp;
1336         int flush_error = 0;
1337         int fsync_error = 0;
1338         int total_error = 0;
1339         int j;
1340         int xflags;
1341         int ispfsroot = 0;
1342
1343         xflags = HAMMER2_FLUSH_TOP;
1344         if (xop->head.flags & HAMMER2_XOP_INODE_STOP)
1345                 xflags |= HAMMER2_FLUSH_INODE_STOP;
1346         if (xop->head.flags & HAMMER2_XOP_FSSYNC)
1347                 xflags |= HAMMER2_FLUSH_FSSYNC;
1348
1349         /*
1350          * Flush core chains
1351          */
1352         chain = hammer2_inode_chain(xop->head.ip1, clindex,
1353                                     HAMMER2_RESOLVE_ALWAYS);
1354         if (chain) {
1355                 hmp = chain->hmp;
1356                 if (chain->flags & HAMMER2_CHAIN_FLUSH_MASK) {
1357                         /*
1358                          * Due to flush partitioning the chain topology
1359                          * above the inode's chain may no longer be flagged.
1360                          * When asked to flush an inode, remark the topology
1361                          * leading to that inode.
1362                          */
1363                         if (chain->parent)
1364                                 hammer2_chain_setflush(chain->parent);
1365                         hammer2_flush(chain, xflags);
1366
1367 #if 0
1368                         /*
1369                          * Propogate upwards but only cross an inode boundary
1370                          * for inodes associated with the current filesystem
1371                          * sync.
1372                          */
1373                         if ((xop->head.flags & HAMMER2_XOP_PARENTONFLUSH) ||
1374                             chain->bref.type != HAMMER2_BREF_TYPE_INODE) {
1375                                 parent = chain->parent;
1376                                 if (parent)
1377                                         hammer2_chain_setflush(parent);
1378                         }
1379 #endif
1380                 }
1381                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
1382                         ispfsroot = 1;
1383                 hammer2_chain_unlock(chain);
1384                 hammer2_chain_drop(chain);
1385                 chain = NULL;
1386         } else {
1387                 hmp = NULL;
1388         }
1389
1390         /*
1391          * Only flush the volume header if asked to, plus the inode must also
1392          * be the PFS root.
1393          */
1394         if ((xop->head.flags & HAMMER2_XOP_VOLHDR) == 0)
1395                 goto skip;
1396         if (ispfsroot == 0)
1397                 goto skip;
1398
1399         /*
1400          * Flush volume roots.  Avoid replication, we only want to
1401          * flush each hammer2_dev (hmp) once.
1402          */
1403         for (j = clindex - 1; j >= 0; --j) {
1404                 if ((chain = xop->head.ip1->cluster.array[j].chain) != NULL) {
1405                         if (chain->hmp == hmp) {
1406                                 chain = NULL;   /* safety */
1407                                 goto skip;
1408                         }
1409                 }
1410         }
1411         chain = NULL;   /* safety */
1412
1413         /*
1414          * spmp transaction.  The super-root is never directly mounted so
1415          * there shouldn't be any vnodes, let alone any dirty vnodes
1416          * associated with it, so we shouldn't have to mess around with any
1417          * vnode flushes here.
1418          */
1419         hammer2_trans_init(hmp->spmp, HAMMER2_TRANS_ISFLUSH);
1420
1421         /*
1422          * Media mounts have two 'roots', vchain for the topology
1423          * and fchain for the free block table.  Flush both.
1424          *
1425          * Note that the topology and free block table are handled
1426          * independently, so the free block table can wind up being
1427          * ahead of the topology.  We depend on the bulk free scan
1428          * code to deal with any loose ends.
1429          *
1430          * vchain and fchain do not error on-lock since their data does
1431          * not have to be re-read from media.
1432          */
1433         hammer2_chain_ref(&hmp->vchain);
1434         hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
1435         hammer2_chain_ref(&hmp->fchain);
1436         hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
1437         if (hmp->fchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
1438                 /*
1439                  * This will also modify vchain as a side effect,
1440                  * mark vchain as modified now.
1441                  */
1442                 hammer2_voldata_modify(hmp);
1443                 chain = &hmp->fchain;
1444                 flush_error |= hammer2_flush(chain, HAMMER2_FLUSH_TOP);
1445                 KKASSERT(chain == &hmp->fchain);
1446         }
1447         hammer2_chain_unlock(&hmp->fchain);
1448         hammer2_chain_unlock(&hmp->vchain);
1449         hammer2_chain_drop(&hmp->fchain);
1450         /* vchain dropped down below */
1451
1452         hammer2_chain_lock(&hmp->vchain, HAMMER2_RESOLVE_ALWAYS);
1453         if (hmp->vchain.flags & HAMMER2_CHAIN_FLUSH_MASK) {
1454                 chain = &hmp->vchain;
1455                 flush_error |= hammer2_flush(chain, HAMMER2_FLUSH_TOP);
1456                 KKASSERT(chain == &hmp->vchain);
1457         }
1458         hammer2_chain_unlock(&hmp->vchain);
1459         hammer2_chain_drop(&hmp->vchain);
1460
1461         /*
1462          * We can't safely flush the volume header until we have
1463          * flushed any device buffers which have built up.
1464          *
1465          * XXX this isn't being incremental
1466          */
1467         vn_lock(hmp->devvp, LK_EXCLUSIVE | LK_RETRY);
1468         fsync_error = VOP_FSYNC(hmp->devvp, MNT_WAIT, 0);
1469         vn_unlock(hmp->devvp);
1470         if (fsync_error || flush_error) {
1471                 kprintf("hammer2: sync error fsync=%d h2flush=0x%04x dev=%s\n",
1472                         fsync_error, flush_error, hmp->devrepname);
1473         }
1474
1475         /*
1476          * The flush code sets CHAIN_VOLUMESYNC to indicate that the
1477          * volume header needs synchronization via hmp->volsync.
1478          *
1479          * XXX synchronize the flag & data with only this flush XXX
1480          */
1481         if (fsync_error == 0 && flush_error == 0 &&
1482             (hmp->vchain.flags & HAMMER2_CHAIN_VOLUMESYNC)) {
1483                 struct buf *bp;
1484                 int vol_error = 0;
1485
1486                 /*
1487                  * Synchronize the disk before flushing the volume
1488                  * header.
1489                  */
1490                 bp = getpbuf(NULL);
1491                 bp->b_bio1.bio_offset = 0;
1492                 bp->b_bufsize = 0;
1493                 bp->b_bcount = 0;
1494                 bp->b_cmd = BUF_CMD_FLUSH;
1495                 bp->b_bio1.bio_done = biodone_sync;
1496                 bp->b_bio1.bio_flags |= BIO_SYNC;
1497                 vn_strategy(hmp->devvp, &bp->b_bio1);
1498                 fsync_error = biowait(&bp->b_bio1, "h2vol");
1499                 relpbuf(bp, NULL);
1500
1501                 /*
1502                  * Then we can safely flush the version of the
1503                  * volume header synchronized by the flush code.
1504                  */
1505                 j = hmp->volhdrno + 1;
1506                 if (j < 0)
1507                         j = 0;
1508                 if (j >= HAMMER2_NUM_VOLHDRS)
1509                         j = 0;
1510                 if (j * HAMMER2_ZONE_BYTES64 + HAMMER2_SEGSIZE >
1511                     hmp->volsync.volu_size) {
1512                         j = 0;
1513                 }
1514                 if (hammer2_debug & 0x8000) {
1515                         /* debug only, avoid syslogd loop */
1516                         kprintf("sync volhdr %d %jd\n",
1517                                 j, (intmax_t)hmp->volsync.volu_size);
1518                 }
1519                 bp = getblk(hmp->devvp, j * HAMMER2_ZONE_BYTES64,
1520                             HAMMER2_PBUFSIZE, GETBLK_KVABIO, 0);
1521                 atomic_clear_int(&hmp->vchain.flags,
1522                                  HAMMER2_CHAIN_VOLUMESYNC);
1523                 bkvasync(bp);
1524                 bcopy(&hmp->volsync, bp->b_data, HAMMER2_PBUFSIZE);
1525                 vol_error = bwrite(bp);
1526                 hmp->volhdrno = j;
1527                 if (vol_error)
1528                         fsync_error = vol_error;
1529         }
1530         if (flush_error)
1531                 total_error = flush_error;
1532         if (fsync_error)
1533                 total_error = hammer2_errno_to_error(fsync_error);
1534
1535         /* spmp trans */
1536         hammer2_trans_done(hmp->spmp, HAMMER2_TRANS_ISFLUSH);
1537 skip:
1538         hammer2_xop_feed(&xop->head, NULL, clindex, total_error);
1539 }