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