Merge branch 'vendor/LIBEDIT'
[dragonfly.git] / sys / vfs / hammer2 / hammer2_flush.c
1 /*
2  * Copyright (c) 2011-2013 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 #include <sys/cdefs.h>
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/types.h>
40 #include <sys/lock.h>
41 #include <sys/uuid.h>
42
43 #include "hammer2.h"
44
45 /*
46  * Recursively flush the specified chain.  The chain is locked and
47  * referenced by the caller and will remain so on return.  The chain
48  * will remain referenced throughout but can temporarily lose its
49  * lock during the recursion to avoid unnecessarily stalling user
50  * processes.
51  */
52 struct hammer2_flush_info {
53         hammer2_mount_t *hmp;
54         hammer2_chain_t *parent;
55         hammer2_trans_t *trans;
56         int             depth;
57         int             diddeferral;
58         struct flush_deferral_list flush_list;
59         hammer2_tid_t   sync_tid;       /* flush synchronization point */
60         hammer2_tid_t   mirror_tid;     /* collect mirror TID updates */
61 };
62
63 typedef struct hammer2_flush_info hammer2_flush_info_t;
64
65 static void hammer2_chain_flush_core(hammer2_flush_info_t *info,
66                                 hammer2_chain_t *chain);
67 static int hammer2_chain_flush_scan1(hammer2_chain_t *child, void *data);
68 static int hammer2_chain_flush_scan2(hammer2_chain_t *child, void *data);
69
70 /*
71  * Transaction support functions for writing to the filesystem.
72  *
73  * Initializing a new transaction allocates a transaction ID.  We
74  * don't bother marking the volume header MODIFIED.  Instead, the volume
75  * will be synchronized at a later time as part of a larger flush sequence.
76  *
77  * Non-flush transactions can typically run concurrently.  However if
78  * there are non-flush transaction both before AND after a flush trans,
79  * the transactions after stall until the ones before finish.
80  *
81  * Non-flush transactions occuring after a flush pointer can run concurrently
82  * with that flush.  They only have to wait for transactions prior to the
83  * flush trans to complete before they unstall.
84  *
85  * WARNING! Modifications to the root volume cannot dup the root volume
86  *          header to handle synchronization points, so alloc_tid can
87  *          wind up (harmlessly) more advanced on flush.
88  *
89  * WARNING! Operations which might call inode_duplicate()/chain_duplicate()
90  *          depend heavily on having a unique sync_tid to avoid duplication
91  *          collisions (which key off of delete_tid).
92  */
93 void
94 hammer2_trans_init(hammer2_mount_t *hmp, hammer2_trans_t *trans, int flags)
95 {
96         hammer2_trans_t *scan;
97
98         bzero(trans, sizeof(*trans));
99         trans->hmp = hmp;
100
101         hammer2_voldata_lock(hmp);
102         trans->sync_tid = hmp->voldata.alloc_tid++;
103         trans->flags = flags;
104         trans->td = curthread;
105         TAILQ_INSERT_TAIL(&hmp->transq, trans, entry);
106
107         if (flags & HAMMER2_TRANS_ISFLUSH) {
108                 /*
109                  * If we are a flush we have to wait for all transactions
110                  * prior to our flush synchronization point to complete
111                  * before we can start our flush.
112                  */
113                 ++hmp->flushcnt;
114                 if (hmp->curflush == NULL) {
115                         hmp->curflush = trans;
116                         hmp->flush_tid = trans->sync_tid;
117                 }
118                 while (TAILQ_FIRST(&hmp->transq) != trans) {
119                         lksleep(&trans->sync_tid, &hmp->voldatalk,
120                                 0, "h2syncw", hz);
121                 }
122
123                 /*
124                  * Once we become the running flush we can wakeup anyone
125                  * who blocked on us.
126                  */
127                 scan = trans;
128                 while ((scan = TAILQ_NEXT(scan, entry)) != NULL) {
129                         if (scan->flags & HAMMER2_TRANS_ISFLUSH)
130                                 break;
131                         if (scan->blocked == 0)
132                                 break;
133                         scan->blocked = 0;
134                         wakeup(&scan->blocked);
135                 }
136         } else {
137                 /*
138                  * If we are not a flush but our sync_tid is after a
139                  * stalled flush, we have to wait until that flush unstalls
140                  * (that is, all transactions prior to that flush complete),
141                  * but then we can run concurrently with that flush.
142                  *
143                  * (flushcnt check only good as pre-condition, otherwise it
144                  *  may represent elements queued after us after we block).
145                  */
146                 if (hmp->flushcnt > 1 ||
147                     (hmp->curflush &&
148                      TAILQ_FIRST(&hmp->transq) != hmp->curflush)) {
149                         trans->blocked = 1;
150                         while (trans->blocked) {
151                                 lksleep(&trans->blocked, &hmp->voldatalk,
152                                         0, "h2trans", hz);
153                         }
154                 }
155         }
156         hammer2_voldata_unlock(hmp, 0);
157 }
158
159 void
160 hammer2_trans_done(hammer2_trans_t *trans)
161 {
162         hammer2_mount_t *hmp = trans->hmp;
163         hammer2_trans_t *scan;
164
165         hammer2_voldata_lock(hmp);
166         TAILQ_REMOVE(&hmp->transq, trans, entry);
167         if (trans->flags & HAMMER2_TRANS_ISFLUSH) {
168                 /*
169                  * If we were a flush we have to adjust curflush to the
170                  * next flush.
171                  *
172                  * flush_tid is used to partition copy-on-write operations
173                  * (mostly duplicate-on-modify ops), which is what allows
174                  * us to execute a flush concurrent with modifying operations
175                  * with higher TIDs.
176                  */
177                 --hmp->flushcnt;
178                 if (hmp->flushcnt) {
179                         TAILQ_FOREACH(scan, &hmp->transq, entry) {
180                                 if (scan->flags & HAMMER2_TRANS_ISFLUSH)
181                                         break;
182                         }
183                         KKASSERT(scan);
184                         hmp->curflush = scan;
185                         hmp->flush_tid = scan->sync_tid;
186                 } else {
187                         /*
188                          * Theoretically we don't have to clear flush_tid
189                          * here since the flush will have synchronized
190                          * all operations <= flush_tid already.  But for
191                          * now zero-it.
192                          */
193                         hmp->curflush = NULL;
194                         hmp->flush_tid = 0;
195                 }
196         } else {
197                 /*
198                  * If we are not a flush but a flush is now at the head
199                  * of the queue and we were previously blocking it,
200                  * we can now unblock it.
201                  */
202                 if (hmp->flushcnt &&
203                     (scan = TAILQ_FIRST(&hmp->transq)) != NULL &&
204                     trans->sync_tid < scan->sync_tid &&
205                     (scan->flags & HAMMER2_TRANS_ISFLUSH)) {
206                         wakeup(&scan->sync_tid);
207                 }
208         }
209         hammer2_voldata_unlock(hmp, 0);
210
211         trans->hmp = NULL;
212 }
213
214 /*
215  * Flush the chain and all modified sub-chains through the specified
216  * synchronization point (sync_tid), propagating parent chain modifications
217  * and mirror_tid updates back up as needed.  Since we are recursing downward
218  * we do not have to deal with the complexities of multi-homed chains (chains
219  * with multiple parents).
220  *
221  * Caller must have interlocked against any non-flush-related modifying
222  * operations in progress whos modify_tid values are less than or equal
223  * to the passed sync_tid.
224  *
225  * Caller must have already vetted synchronization points to ensure they
226  * are properly flushed.  Only snapshots and cluster flushes can create
227  * these sorts of synchronization points.
228  *
229  * SUBMODIFIED is not cleared if modified elements with higher modify_tid
230  * values (thus not flushed) are still present after the flush.
231  *
232  * If a chain is unable to completely flush we have to be sure that
233  * SUBMODIFIED remains set up the parent chain, and that MOVED is not
234  * cleared or our desynchronized bref will not properly update in the
235  * parent.  The parent's indirect block is copied-on-write and adjusted
236  * as needed so it no longer needs to be placemarked by the subchains,
237  * allowing the sub-chains to be cleaned out.
238  *
239  * This routine can be called from several places but the most important
240  * is from the hammer2_vop_reclaim() function.  We want to try to completely
241  * clean out the inode structure to prevent disconnected inodes from
242  * building up and blowing out the kmalloc pool.  However, it is not actually
243  * necessary to flush reclaimed inodes to maintain HAMMER2's crash recovery
244  * capability.
245  *
246  * chain is locked on call and will remain locked on return.  If a flush
247  * occured, the chain's MOVED bit will be set indicating that its parent
248  * (which is not part of the flush) should be updated.
249  */
250 void
251 hammer2_chain_flush(hammer2_trans_t *trans, hammer2_chain_t *chain)
252 {
253         hammer2_chain_t *scan;
254         hammer2_chain_core_t *core;
255         hammer2_flush_info_t info;
256
257         /*
258          * Execute the recursive flush and handle deferrals.
259          *
260          * Chains can be ridiculously long (thousands deep), so to
261          * avoid blowing out the kernel stack the recursive flush has a
262          * depth limit.  Elements at the limit are placed on a list
263          * for re-execution after the stack has been popped.
264          */
265         bzero(&info, sizeof(info));
266         TAILQ_INIT(&info.flush_list);
267         info.hmp = trans->hmp;
268         info.trans = trans;
269         info.sync_tid = trans->sync_tid;
270         info.mirror_tid = 0;
271
272         core = chain->core;
273
274         for (;;) {
275                 /*
276                  * Unwind deep recursions which had been deferred.  This
277                  * can leave MOVED set for these chains, which will be
278                  * handled when we [re]flush chain after the unwind.
279                  */
280                 while ((scan = TAILQ_FIRST(&info.flush_list)) != NULL) {
281                         KKASSERT(scan->flags & HAMMER2_CHAIN_DEFERRED);
282                         TAILQ_REMOVE(&info.flush_list, scan, flush_node);
283                         atomic_clear_int(&scan->flags, HAMMER2_CHAIN_DEFERRED);
284
285                         /*
286                          * Now that we've popped back up we can do a secondary
287                          * recursion on the deferred elements.
288                          */
289                         if (hammer2_debug & 0x0040)
290                                 kprintf("defered flush %p\n", scan);
291                         hammer2_chain_lock(scan, HAMMER2_RESOLVE_MAYBE);
292                         hammer2_chain_flush(trans, scan);
293                         hammer2_chain_unlock(scan);
294                         hammer2_chain_drop(scan);       /* ref from deferral */
295                 }
296
297                 /*
298                  * Flush pass1 on root.  SUBMODIFIED can remain set after
299                  * this call for numerous reasons, including write failures,
300                  * but most likely due to only a partial flush being
301                  * requested or the chain element belongs to the wrong
302                  * synchronization point.
303                  */
304                 info.diddeferral = 0;
305                 hammer2_chain_flush_core(&info, chain);
306 #if FLUSH_DEBUG
307                 kprintf("flush_core_done parent=<base> chain=%p.%d %08x\n",
308                         chain, chain->bref.type, chain->flags);
309 #endif
310
311                 /*
312                  * Only loop if deep recursions have been deferred.
313                  */
314                 if (TAILQ_EMPTY(&info.flush_list))
315                         break;
316         }
317
318         /*
319          * SUBMODIFIED can be temporarily cleared and then re-set, which
320          * can prevent concurrent setsubmods from reaching all the way to
321          * the root.  If after the flush we find the node is still in need
322          * of flushing (though possibly due to modifications made outside
323          * the requested synchronization zone), we must call setsubmod again
324          * to cover the race.
325          */
326         if (chain->flags & (HAMMER2_CHAIN_MOVED |
327                             HAMMER2_CHAIN_DELETED |
328                             HAMMER2_CHAIN_MODIFIED |
329                             HAMMER2_CHAIN_SUBMODIFIED)) {
330                 hammer2_chain_setsubmod(trans, chain);
331         }
332 }
333
334 /*
335  * This is the core of the chain flushing code.  The chain is locked by the
336  * caller and remains locked on return.  This function is keyed off of
337  * the SUBMODIFIED bit but must make fine-grained choices based on the
338  * synchronization point we are flushing to.
339  *
340  * If the flush accomplished any work chain will be flagged MOVED
341  * indicating a copy-on-write propagation back up is required.
342  * Deep sub-nodes may also have been entered onto the deferral list.
343  * MOVED is never set on the volume root.
344  *
345  * NOTE: modify_tid is different from MODIFIED.  modify_tid is updated
346  *       only when a chain is specifically modified, and not updated
347  *       for copy-on-write propagations.  MODIFIED is set on any modification
348  *       including copy-on-write propagations.
349  */
350 static void
351 hammer2_chain_flush_core(hammer2_flush_info_t *info, hammer2_chain_t *chain)
352 {
353         hammer2_mount_t *hmp;
354         hammer2_blockref_t *bref;
355         hammer2_off_t pbase;
356         hammer2_tid_t saved_sync;
357         hammer2_trans_t *trans = info->trans;
358         hammer2_chain_core_t *core;
359         size_t bbytes;
360         size_t boff;
361         char *bdata;
362         struct buf *bp;
363         int error;
364         int wasmodified;
365         int diddeferral = 0;
366
367         hmp = info->hmp;
368
369 #if FLUSH_DEBUG
370         if (info->parent)
371                 kprintf("flush_core %p->%p.%d %08x (%s)\n",
372                         info->parent, chain, chain->bref.type,
373                         chain->flags,
374                         ((chain->bref.type == HAMMER2_BREF_TYPE_INODE) ?
375                                 chain->data->ipdata.filename : "?"));
376         else
377                 kprintf("flush_core NULL->%p.%d %08x (%s)\n",
378                         chain, chain->bref.type,
379                         chain->flags,
380                         ((chain->bref.type == HAMMER2_BREF_TYPE_INODE) ?
381                                 chain->data->ipdata.filename : "?"));
382 #endif
383         /*
384          * Ignore chains modified beyond the current flush point.  These
385          * will be treated as if they did not exist.
386          */
387         if (chain->modify_tid > info->sync_tid)
388                 return;
389
390         /*
391          * Deleted chains which have not been destroyed must be retained,
392          * and we probably have to recurse to clean-up any sub-trees.
393          * However, restricted flushes can stop processing here because
394          * the chain cleanup will be handled by a later normal flush.
395          *
396          * The MODIFIED bit can likely be cleared in this situation and we
397          * will do so later on in this procedure.
398          */
399         if (chain->delete_tid <= info->sync_tid) {
400                 if (trans->flags & HAMMER2_TRANS_RESTRICTED)
401                         return;
402         }
403
404         saved_sync = info->sync_tid;
405         core = chain->core;
406
407         /*
408          * If SUBMODIFIED is set we recurse the flush and adjust the
409          * blockrefs accordingly.
410          *
411          * NOTE: Looping on SUBMODIFIED can prevent a flush from ever
412          *       finishing in the face of filesystem activity.
413          */
414         if (chain->flags & HAMMER2_CHAIN_SUBMODIFIED) {
415                 hammer2_chain_t *saved_parent;
416                 hammer2_tid_t saved_mirror;
417
418                 /*
419                  * Clear SUBMODIFIED to catch races.  Note that any child
420                  * with MODIFIED, DELETED, or MOVED set during Scan2, after
421                  * it processes the child, will cause SUBMODIFIED to be
422                  * re-set.
423                  * child has to be flushed SUBMODIFIED will wind up being
424                  * set again (for next time), but this does not stop us from
425                  * synchronizing block updates which occurred.
426                  *
427                  * We don't want to set our chain to MODIFIED gratuitously.
428                  *
429                  * We need an extra ref on chain because we are going to
430                  * release its lock temporarily in our child loop.
431                  */
432                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_SUBMODIFIED);
433                 hammer2_chain_ref(chain);
434
435                 /*
436                  * Run two passes.  The first pass handles MODIFIED and
437                  * SUBMODIFIED chains and recurses while the second pass
438                  * handles MOVED chains on the way back up.
439                  *
440                  * If the stack gets too deep we defer scan1, but must
441                  * be sure to still run scan2 if on the next loop the
442                  * deferred chain has been flushed and now needs MOVED
443                  * handling on the way back up.
444                  *
445                  * Scan1 is recursive.
446                  *
447                  * NOTE: The act of handling a modified/submodified chain can
448                  *       cause the MOVED Flag to be set.  It can also be set
449                  *       via hammer2_chain_delete() and in other situations.
450                  *
451                  * NOTE: RB_SCAN() must be used instead of RB_FOREACH()
452                  *       because children can be physically removed during
453                  *       the scan.
454                  */
455                 saved_parent = info->parent;
456                 saved_mirror = info->mirror_tid;
457                 info->parent = chain;
458                 info->mirror_tid = chain->bref.mirror_tid;
459
460                 if (info->depth == HAMMER2_FLUSH_DEPTH_LIMIT) {
461                         if ((chain->flags & HAMMER2_CHAIN_DEFERRED) == 0) {
462                                 hammer2_chain_ref(chain);
463                                 TAILQ_INSERT_TAIL(&info->flush_list,
464                                                   chain, flush_node);
465                                 atomic_set_int(&chain->flags,
466                                                HAMMER2_CHAIN_DEFERRED);
467                         }
468                         diddeferral = 1;
469                 } else {
470                         info->diddeferral = 0;
471                         spin_lock(&core->cst.spin);
472                         RB_SCAN(hammer2_chain_tree, &chain->core->rbtree,
473                                 NULL, hammer2_chain_flush_scan1, info);
474                         spin_unlock(&core->cst.spin);
475                         diddeferral += info->diddeferral;
476                 }
477
478                 /*
479                  * Handle successfully flushed children who are in the MOVED
480                  * state on the way back up the recursion.  This can have
481                  * the side-effect of clearing MOVED.
482                  *
483                  * We execute this even if there were deferrals to try to
484                  * keep the chain topology cleaner.
485                  *
486                  * Scan2 is non-recursive.
487                  */
488                 if (diddeferral) {
489                         atomic_set_int(&chain->flags,
490                                        HAMMER2_CHAIN_SUBMODIFIED);
491                 } else {
492 #if FLUSH_DEBUG
493                         kprintf("scan2_start parent %p %08x\n", chain, chain->flags);
494 #endif
495                         spin_lock(&core->cst.spin);
496                         RB_SCAN(hammer2_chain_tree, &core->rbtree,
497                                 NULL, hammer2_chain_flush_scan2, info);
498                         spin_unlock(&core->cst.spin);
499 #if FLUSH_DEBUG
500                         kprintf("scan2_stop  parent %p %08x\n", chain, chain->flags);
501 #endif
502                 }
503                 chain->bref.mirror_tid = info->mirror_tid;
504                 info->mirror_tid = saved_mirror;
505                 info->parent = saved_parent;
506                 hammer2_chain_drop(chain);
507         }
508
509         /*
510          * Restore sync_tid in case it was restricted by a delete/duplicate.
511          */
512         info->sync_tid = saved_sync;
513
514         /*
515          * Rollup diddeferral for caller.  Note direct assignment, not +=.
516          */
517         info->diddeferral = diddeferral;
518
519         /*
520          * Do not flush chain if there were any deferrals.  It will be
521          * retried later after the deferrals are independently handled.
522          */
523         if (diddeferral) {
524                 if (hammer2_debug & 0x0008) {
525                         kprintf("%*.*s} %p/%d %04x (deferred)",
526                                 info->depth, info->depth, "",
527                                 chain, chain->refs, chain->flags);
528                 }
529                 return;
530         }
531
532         /*
533          * If we encounter a deleted chain within our flush we can clear
534          * the MODIFIED bit and avoid flushing it whether it has been
535          * destroyed or not.
536          */
537         if (chain->delete_tid <= info->sync_tid) {
538                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
539                         if (chain->bp)
540                                 chain->bp->b_flags |= B_INVAL|B_RELBUF;
541                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
542                         hammer2_chain_drop(chain);
543                 }
544                 return;
545         }
546 #if 0
547         if ((chain->flags & HAMMER2_CHAIN_DESTROYED) &&
548             (chain->flags & HAMMER2_CHAIN_DELETED) &&
549             (trans->flags & HAMMER2_TRANS_RESTRICTED) == 0) {
550                 /*
551                  * Throw-away the MODIFIED flag
552                  */
553                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
554                         if (chain->bp)
555                                 chain->bp->b_flags |= B_INVAL|B_RELBUF;
556                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
557                         hammer2_chain_drop(chain);
558                 }
559                 return;
560         }
561 #endif
562
563         /*
564          * A degenerate flush might not have flushed anything and thus not
565          * processed modified blocks on the way back up.  Detect the case.
566          *
567          * Note that MOVED can be set without MODIFIED being set due to
568          * a deletion, in which case it is handled by Scan2 later on.
569          *
570          * Both bits can be set along with DELETED due to a deletion if
571          * modified data within the synchronization zone and the chain
572          * was then deleted beyond the zone, in which case we still have
573          * to flush for synchronization point consistency.  Otherwise though
574          * DELETED and MODIFIED are treated as separate flags.
575          */
576         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
577                 return;
578
579         /*
580          * Issue flush.
581          *
582          * A DESTROYED node that reaches this point must be flushed for
583          * synchronization point consistency.
584          */
585
586         /*
587          * Update mirror_tid, clear MODIFIED, and set MOVED.
588          *
589          * The caller will update the parent's reference to this chain
590          * by testing MOVED as long as the modification was in-bounds.
591          *
592          * MOVED is never set on the volume root as there is no parent
593          * to adjust.
594          */
595         if (chain->bref.mirror_tid < info->sync_tid)
596                 chain->bref.mirror_tid = info->sync_tid;
597         wasmodified = (chain->flags & HAMMER2_CHAIN_MODIFIED) != 0;
598         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
599         if (chain == &hmp->vchain)
600                 kprintf("(FLUSHED VOLUME HEADER)\n");
601
602         if ((chain->flags & HAMMER2_CHAIN_MOVED) ||
603             chain == &hmp->vchain) {
604                 /*
605                  * Drop the ref from the MODIFIED bit we cleared.
606                  */
607                 if (wasmodified)
608                         hammer2_chain_drop(chain);
609         } else {
610                 /*
611                  * If we were MODIFIED we inherit the ref from clearing
612                  * that bit, otherwise we need another ref.
613                  */
614                 if (wasmodified == 0)
615                         hammer2_chain_ref(chain);
616                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
617         }
618
619         /*
620          * If this is part of a recursive flush we can go ahead and write
621          * out the buffer cache buffer and pass a new bref back up the chain
622          * via the MOVED bit.
623          *
624          * Volume headers are NOT flushed here as they require special
625          * processing.
626          */
627         switch(chain->bref.type) {
628         case HAMMER2_BREF_TYPE_VOLUME:
629                 /*
630                  * The volume header is flushed manually by the syncer, not
631                  * here.  All we do is adjust the crc's.
632                  */
633                 KKASSERT(chain->data != NULL);
634                 KKASSERT(chain->bp == NULL);
635                 kprintf("volume header mirror_tid %jd\n",
636                         hmp->voldata.mirror_tid);
637
638                 hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT1]=
639                         hammer2_icrc32(
640                                 (char *)&hmp->voldata +
641                                  HAMMER2_VOLUME_ICRC1_OFF,
642                                 HAMMER2_VOLUME_ICRC1_SIZE);
643                 hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT0]=
644                         hammer2_icrc32(
645                                 (char *)&hmp->voldata +
646                                  HAMMER2_VOLUME_ICRC0_OFF,
647                                 HAMMER2_VOLUME_ICRC0_SIZE);
648                 hmp->voldata.icrc_volheader =
649                         hammer2_icrc32(
650                                 (char *)&hmp->voldata +
651                                  HAMMER2_VOLUME_ICRCVH_OFF,
652                                 HAMMER2_VOLUME_ICRCVH_SIZE);
653                 hmp->volsync = hmp->voldata;
654                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_VOLUMESYNC);
655                 break;
656         case HAMMER2_BREF_TYPE_DATA:
657                 /*
658                  * Data elements have already been flushed via the logical
659                  * file buffer cache.  Their hash was set in the bref by
660                  * the vop_write code.
661                  *
662                  * Make sure any device buffer(s) have been flushed out here.
663                  * (there aren't usually any to flush).
664                  */
665                 bbytes = chain->bytes;
666                 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
667                 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
668
669                 bp = getblk(hmp->devvp, pbase, bbytes, GETBLK_NOWAIT, 0);
670                 if (bp) {
671                         if ((bp->b_flags & (B_CACHE | B_DIRTY)) ==
672                             (B_CACHE | B_DIRTY)) {
673                                 cluster_awrite(bp);
674                         } else {
675                                 bp->b_flags |= B_RELBUF;
676                                 brelse(bp);
677                         }
678                 }
679                 break;
680         case HAMMER2_BREF_TYPE_INDIRECT:
681                 /*
682                  * Indirect blocks may be in an INITIAL state.  Use the
683                  * chain_lock() call to ensure that the buffer has been
684                  * instantiated (even though it is already locked the buffer
685                  * might not have been instantiated).
686                  *
687                  * Only write the buffer out if it is dirty, it is possible
688                  * the operating system had already written out the buffer.
689                  */
690                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
691                 KKASSERT(chain->bp != NULL);
692
693                 bp = chain->bp;
694                 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) ||
695                     (bp->b_flags & B_DIRTY)) {
696                         bdwrite(chain->bp);
697                 } else {
698                         brelse(chain->bp);
699                 }
700                 chain->bp = NULL;
701                 chain->data = NULL;
702                 hammer2_chain_unlock(chain);
703                 break;
704         default:
705                 /*
706                  * Embedded elements have to be flushed out.
707                  */
708                 KKASSERT(chain->data != NULL);
709                 KKASSERT(chain->bp == NULL);
710                 bref = &chain->bref;
711
712                 KKASSERT((bref->data_off & HAMMER2_OFF_MASK) != 0);
713                 KKASSERT(HAMMER2_DEC_CHECK(chain->bref.methods) ==
714                          HAMMER2_CHECK_ISCSI32);
715
716                 if (chain->bp == NULL) {
717                         /*
718                          * The data is embedded, we have to acquire the
719                          * buffer cache buffer and copy the data into it.
720                          */
721                         if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
722                                 bbytes = HAMMER2_MINIOSIZE;
723                         pbase = bref->data_off & ~(hammer2_off_t)(bbytes - 1);
724                         boff = bref->data_off & HAMMER2_OFF_MASK & (bbytes - 1);
725
726                         /*
727                          * The getblk() optimization can only be used if the
728                          * physical block size matches the request.
729                          */
730                         if (chain->bytes == bbytes) {
731                                 bp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
732                                 error = 0;
733                         } else {
734                                 error = bread(hmp->devvp, pbase, bbytes, &bp);
735                                 KKASSERT(error == 0);
736                         }
737                         bdata = (char *)bp->b_data + boff;
738
739                         /*
740                          * Copy the data to the buffer, mark the buffer
741                          * dirty, and convert the chain to unmodified.
742                          */
743                         bcopy(chain->data, bdata, chain->bytes);
744                         bp->b_flags |= B_CLUSTEROK;
745                         bdwrite(bp);
746                         bp = NULL;
747                         chain->bref.check.iscsi32.value =
748                                 hammer2_icrc32(chain->data, chain->bytes);
749                         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
750                                 ++hammer2_iod_meta_write;
751                         else
752                                 ++hammer2_iod_indr_write;
753                 } else {
754                         chain->bref.check.iscsi32.value =
755                                 hammer2_icrc32(chain->data, chain->bytes);
756                 }
757         }
758 }
759
760 /*
761  * Flush helper scan1 (recursive)
762  *
763  * Flushes the children of the caller's chain (parent) and updates
764  * the blockref, restricted by sync_tid.
765  *
766  * Ripouts during the loop should not cause any problems.  Because we are
767  * flushing to a synchronization point, modification races will occur after
768  * sync_tid and do not have to be flushed anyway.
769  *
770  * It is also ok if the parent is chain_duplicate()'d while unlocked because
771  * the delete/duplication will install a delete_tid that is still larger than
772  * our current sync_tid.
773  */
774 static int
775 hammer2_chain_flush_scan1(hammer2_chain_t *child, void *data)
776 {
777         hammer2_flush_info_t *info = data;
778         hammer2_trans_t *trans = info->trans;
779         hammer2_chain_t *parent = info->parent;
780         /*hammer2_mount_t *hmp = info->hmp;*/
781         int diddeferral;
782
783         /*
784          * We should only need to recurse if SUBMODIFIED is set, but as
785          * a safety also recurse if MODIFIED is also set.  Return early
786          * if neither bit is set.
787          */
788         if ((child->flags & (HAMMER2_CHAIN_MODIFIED |
789                              HAMMER2_CHAIN_SUBMODIFIED)) == 0) {
790                 return (0);
791         }
792         if (child->modify_tid > trans->sync_tid) {
793                 return (0);
794         }
795
796         hammer2_chain_ref(child);
797         spin_unlock(&parent->core->cst.spin);
798
799         /*
800          * The caller has added a ref to the parent so we can temporarily
801          * unlock it in order to lock the child.  Re-check the flags before
802          * continuing.
803          */
804         hammer2_chain_unlock(parent);
805         hammer2_chain_lock(child, HAMMER2_RESOLVE_MAYBE);
806
807         if ((child->flags & (HAMMER2_CHAIN_MODIFIED |
808                              HAMMER2_CHAIN_SUBMODIFIED)) == 0) {
809                 hammer2_chain_unlock(child);
810                 hammer2_chain_drop(child);
811                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
812                 spin_lock(&parent->core->cst.spin);
813                 return (0);
814         }
815         if (child->modify_tid > trans->sync_tid) {
816                 hammer2_chain_unlock(child);
817                 hammer2_chain_drop(child);
818                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
819                 spin_lock(&parent->core->cst.spin);
820                 return (0);
821         }
822
823         /*
824          * The DESTROYED flag can only be initially set on an unreferenced
825          * deleted inode and will propagate downward via the mechanic below.
826          * Such inode chains have been deleted for good and should no longer
827          * be subject to delete/duplication.
828          *
829          * This optimization allows the inode reclaim (destroy unlinked file
830          * on vnode reclamation after last close) to be flagged by just
831          * setting HAMMER2_CHAIN_DESTROYED at the top level and then will
832          * cause the chains to be terminated and related buffers to be
833          * invalidated and not flushed out.
834          *
835          * We have to be careful not to propagate the DESTROYED flag if
836          * the destruction occurred after our flush sync_tid.
837          */
838         if ((parent->flags & HAMMER2_CHAIN_DESTROYED) &&
839             (child->flags & HAMMER2_CHAIN_DELETED) &&
840             (child->flags & HAMMER2_CHAIN_DESTROYED) == 0) {
841                 atomic_set_int(&child->flags, HAMMER2_CHAIN_DESTROYED |
842                                               HAMMER2_CHAIN_SUBMODIFIED);
843         }
844
845         /*
846          * Recurse and collect deferral data.
847          */
848         diddeferral = info->diddeferral;
849         ++info->depth;
850         hammer2_chain_flush_core(info, child);
851 #if FLUSH_DEBUG
852         kprintf("flush_core_done parent=%p flags=%08x child=%p.%d %08x\n",
853                 parent, parent->flags, child, child->bref.type, child->flags);
854 #endif
855         --info->depth;
856         info->diddeferral += diddeferral;
857
858         hammer2_chain_unlock(child);
859         hammer2_chain_drop(child);
860
861         hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
862
863         spin_lock(&parent->core->cst.spin);
864         return (0);
865 }
866
867 /*
868  * Flush helper scan2 (non-recursive)
869  *
870  * This pass on a chain's children propagates any MOVED or DELETED
871  * elements back up the chain towards the root after those elements have
872  * been fully flushed.  Unlike scan1, this function is NOT recursive and
873  * the parent remains locked across the entire scan.
874  *
875  * NOTE!  We must re-set SUBMODIFIED on the parent(s) as appropriate, and
876  *        due to the above conditions it is possible to do this and still
877  *        have some children flagged MOVED depending on the synchronization.
878  *
879  * NOTE!  A deletion is a visbility issue, there can still be referenced to
880  *        deleted elements (for example, to an unlinked file which is still
881  *        open), and there can also be multiple chains pointing to the same
882  *        bref where some are deleted and some are not (for example due to
883  *        a rename).   So a chain marked for deletion is basically considered
884  *        to be live until it is explicitly destroyed or until its ref-count
885  *        reaches zero (also implying that MOVED and MODIFIED are clear).
886  */
887 static int
888 hammer2_chain_flush_scan2(hammer2_chain_t *child, void *data)
889 {
890         hammer2_flush_info_t *info = data;
891         hammer2_chain_t *parent = info->parent;
892         hammer2_chain_core_t *above = child->above;
893         hammer2_mount_t *hmp = info->hmp;
894         hammer2_trans_t *trans = info->trans;
895         hammer2_blockref_t *base;
896         int count;
897
898         /*
899          * Inodes with stale children that have been converted to DIRECTDATA
900          * mode (file extension or hardlink conversion typically) need to
901          * skipped right now before we start messing with a non-existant
902          * block table.
903          */
904         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
905             (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)) {
906 #if FLUSH_DEBUG
907                 kprintf("B");
908 #endif
909                 goto finalize;
910         }
911
912         /*
913          * Ignore children created after our flush point, treating them as
914          * if they did not exist).  These children will not cause the parent
915          * to be updated.
916          *
917          * When we encounter such children and the parent chain has not been
918          * deleted, delete/duplicated, or delete/duplicated-for-move, then
919          * the parent may be used to funnel through several flush points.
920          * We must re-set the SUBMODIFIED flag in the parent to ensure that
921          * those flushes have visbility.  A simple test of delete_tid suffices
922          * to determine if the parent spans beyond our current flush.
923          */
924         if (child->modify_tid > trans->sync_tid) {
925 #if FLUSH_DEBUG
926                 kprintf("E");
927 #endif
928                 if (parent->delete_tid > trans->sync_tid) {
929                         atomic_set_int(&parent->flags,
930                                         HAMMER2_CHAIN_SUBMODIFIED);
931                 }
932                 goto finalize;
933         }
934
935         /*
936          * Ignore children which have not changed.  The parent's block table
937          * is already correct.
938          */
939         if ((child->flags & HAMMER2_CHAIN_MOVED) == 0) {
940 #if FLUSH_DEBUG
941                 kprintf("D");
942 #endif
943                 goto finalize;
944         }
945
946
947         hammer2_chain_ref(child);
948         spin_unlock(&above->cst.spin);
949
950         /*
951          * The MOVED bit implies an additional reference which prevents
952          * the child from being destroyed out from under our operation
953          * so we can lock the child safely without worrying about it
954          * getting ripped up (?).
955          *
956          * We can only update parents where child->parent matches.  The
957          * child->parent link will migrate along the chain but the flush
958          * order must be enforced absolutely.  Parent reflushed after the
959          * child has passed them by should skip due to the modify_tid test.
960          */
961         hammer2_chain_lock(child, HAMMER2_RESOLVE_NEVER);
962
963         /*
964          * The parent's blockref to the child must be deleted or updated.
965          *
966          * This point is not reached on successful DESTROYED optimizations
967          * but can be reached on recursive deletions and restricted flushes.
968          *
969          * Because flushes are ordered we do not have to make a
970          * modify/duplicate of indirect blocks.  That is, the flush
971          * code does not have to kmalloc or duplicate anything.  We
972          * can adjust the indirect block table in-place and reuse the
973          * chain.  It IS possible that the chain has already been duplicated
974          * or may wind up being duplicated on-the-fly by modifying code
975          * on the frontend.  We simply use the original and ignore such
976          * chains.  However, it does mean we can't clear the MOVED bit.
977          *
978          * XXX recursive deletions not optimized.
979          */
980         hammer2_chain_modify(trans, &parent,
981                              HAMMER2_MODIFY_NO_MODIFY_TID |
982                              HAMMER2_MODIFY_ASSERTNOCOPY);
983
984         switch(parent->bref.type) {
985         case HAMMER2_BREF_TYPE_INODE:
986                 /*
987                  * XXX Should assert that OPFLAG_DIRECTDATA is 0 once we
988                  * properly duplicate the inode headers and do proper flush
989                  * range checks (all the children should be beyond the flush
990                  * point).  For now just don't sync the non-applicable
991                  * children.
992                  *
993                  * XXX Can also occur due to hardlink consolidation.  We
994                  * set OPFLAG_DIRECTDATA to prevent the indirect and data
995                  * blocks from syncing ot the hardlink pointer.
996                  */
997 #if 0
998                 KKASSERT((parent->data->ipdata.op_flags &
999                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
1000 #endif
1001                 if (parent->data->ipdata.op_flags &
1002                     HAMMER2_OPFLAG_DIRECTDATA) {
1003                         base = NULL;
1004                 } else {
1005                         base = &parent->data->ipdata.u.blockset.blockref[0];
1006                         count = HAMMER2_SET_COUNT;
1007                 }
1008                 break;
1009         case HAMMER2_BREF_TYPE_INDIRECT:
1010                 if (parent->data) {
1011                         base = &parent->data->npdata.blockref[0];
1012                 } else {
1013                         base = NULL;
1014                         KKASSERT(child->flags & HAMMER2_CHAIN_DELETED);
1015                 }
1016                 count = parent->bytes / sizeof(hammer2_blockref_t);
1017                 break;
1018         case HAMMER2_BREF_TYPE_VOLUME:
1019                 base = &hmp->voldata.sroot_blockset.blockref[0];
1020                 count = HAMMER2_SET_COUNT;
1021                 break;
1022         default:
1023                 base = NULL;
1024                 count = 0;
1025                 panic("hammer2_chain_get: "
1026                       "unrecognized blockref type: %d",
1027                       parent->bref.type);
1028         }
1029
1030         /*
1031          * Update the parent's blockref table and propagate mirror_tid.
1032          *
1033          * NOTE! Children with modify_tid's beyond our flush point are
1034          *       considered to not exist for the purposes of updating the
1035          *       parent's blockref array.
1036          *
1037          * NOTE! Updates to a parent's blockref table do not adjust the
1038          *       parent's bref.modify_tid, only its bref.mirror_tid.
1039          */
1040         KKASSERT(child->index >= 0);
1041         if (child->delete_tid <= trans->sync_tid) {
1042                 if (base) {
1043                         KKASSERT(child->index < count);
1044                         bzero(&base[child->index], sizeof(child->bref));
1045                         if (info->mirror_tid < child->delete_tid)
1046                                 info->mirror_tid = child->delete_tid;
1047                 }
1048         } else {
1049                 if (base) {
1050                         KKASSERT(child->index < count);
1051                         base[child->index] = child->bref;
1052                         if (info->mirror_tid < child->modify_tid)
1053                                 info->mirror_tid = child->modify_tid;
1054                 }
1055         }
1056
1057         if (info->mirror_tid < child->bref.mirror_tid) {
1058                 info->mirror_tid = child->bref.mirror_tid;
1059         }
1060         if (parent->bref.type == HAMMER2_BREF_TYPE_VOLUME &&
1061             hmp->voldata.mirror_tid < child->bref.mirror_tid) {
1062                 hmp->voldata.mirror_tid = child->bref.mirror_tid;
1063         }
1064
1065         /*
1066          * When can we safely clear the MOVED flag?  Flushes down duplicate
1067          * paths can occur out of order, for example if an inode is moved
1068          * as part of a hardlink consolidation or if an inode is moved into
1069          * an indirect block indexed before the inode.
1070          *
1071          * Only clear MOVED once all possible parents have been flushed.
1072          */
1073 #if 1
1074         if (child->flags & HAMMER2_CHAIN_MOVED) {
1075                 hammer2_chain_t *scan;
1076                 int ok = 1;
1077
1078                 spin_lock(&above->cst.spin);
1079                 for (scan = above->first_parent; scan;
1080                      scan = scan->next_parent) {
1081                         if (scan->flags & HAMMER2_CHAIN_SUBMODIFIED) {
1082                                 ok = 0;
1083                                 break;
1084                         }
1085                 }
1086                 spin_unlock(&above->cst.spin);
1087                 if (ok) {
1088                         atomic_clear_int(&child->flags, HAMMER2_CHAIN_MOVED);
1089                         hammer2_chain_drop(child);      /* flag */
1090                 }
1091         }
1092 #endif
1093 #if 0
1094         if (child->flags & HAMMER2_CHAIN_MOVED) {
1095                 if (above->sharecnt == 1) {
1096                         atomic_clear_int(&child->flags, HAMMER2_CHAIN_MOVED);
1097                         hammer2_chain_drop(child);      /* flag */
1098                 }
1099         }
1100 #endif
1101
1102         /*
1103          * Unlock the child.  This can wind up dropping the child's
1104          * last ref, removing it from the parent's RB tree, and deallocating
1105          * the structure.  The RB_SCAN() our caller is doing handles the
1106          * situation.
1107          */
1108         hammer2_chain_unlock(child);
1109         hammer2_chain_drop(child);
1110         spin_lock(&above->cst.spin);
1111 #if FLUSH_DEBUG
1112         kprintf("F");
1113 #endif
1114
1115         /*
1116          * The parent cleared SUBMODIFIED prior to the scan.  If the child
1117          * still requires a flush (possibly due to being outside the current
1118          * synchronization zone), we must re-set SUBMODIFIED on the way back
1119          * up.
1120          */
1121 finalize:
1122 #if FLUSH_DEBUG
1123         kprintf("G child %p 08x\n", child, child->flags);
1124 #endif
1125         return (0);
1126 }