hammer2 - Implement crash recovery, cleanups, stabilization
[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 #define FLUSH_DEBUG 0
46
47 /*
48  * Recursively flush the specified chain.  The chain is locked and
49  * referenced by the caller and will remain so on return.  The chain
50  * will remain referenced throughout but can temporarily lose its
51  * lock during the recursion to avoid unnecessarily stalling user
52  * processes.
53  */
54 struct hammer2_flush_info {
55         hammer2_chain_t *parent;
56         hammer2_trans_t *trans;
57         int             depth;
58         int             diddeferral;
59         int             pass;
60         int             cache_index;
61         int             domodify;
62         struct h2_flush_deferral_list flush_list;
63         hammer2_tid_t   sync_tid;       /* flush synchronization point */
64 };
65
66 typedef struct hammer2_flush_info hammer2_flush_info_t;
67
68 static void hammer2_chain_flush_core(hammer2_flush_info_t *info,
69                                 hammer2_chain_t **chainp);
70 static int hammer2_chain_flush_scan1(hammer2_chain_t *child, void *data);
71 static int hammer2_chain_flush_scan2(hammer2_chain_t *child, void *data);
72 static void hammer2_rollup_stats(hammer2_chain_t *parent,
73                                 hammer2_chain_t *child, int how);
74
75 #if 0
76 static __inline
77 void
78 hammer2_updatestats(hammer2_flush_info_t *info, hammer2_blockref_t *bref,
79                     int how)
80 {
81         hammer2_key_t bytes;
82
83         if (bref->type != 0) {
84                 bytes = 1 << (bref->data_off & HAMMER2_OFF_MASK_RADIX);
85                 if (bref->type == HAMMER2_BREF_TYPE_INODE)
86                         info->inode_count += how;
87                 if (how < 0)
88                         info->data_count -= bytes;
89                 else
90                         info->data_count += bytes;
91         }
92 }
93 #endif
94
95 /*
96  * Transaction support functions for writing to the filesystem.
97  *
98  * Initializing a new transaction allocates a transaction ID.  Typically
99  * passed a pmp (hmp passed as NULL), indicating a cluster transaction.  Can
100  * be passed a NULL pmp and non-NULL hmp to indicate a transaction on a single
101  * media target.  The latter mode is used by the recovery code.
102  *
103  * We don't bother marking the volume header MODIFIED.  Instead, the volume
104  * will be synchronized at a later time as part of a larger flush sequence.
105  *
106  * Non-flush transactions can typically run concurrently.  However if
107  * there are non-flush transaction both before AND after a flush trans,
108  * the transactions after stall until the ones before finish.
109  *
110  * Non-flush transactions occuring after a flush pointer can run concurrently
111  * with that flush.  They only have to wait for transactions prior to the
112  * flush trans to complete before they unstall.
113  *
114  * WARNING! Transaction ids are only allocated when the transaction becomes
115  *          active, which allows other transactions to insert ahead of us
116  *          if we are forced to block (only bioq transactions do that).
117  *
118  * WARNING! Modifications to the root volume cannot dup the root volume
119  *          header to handle synchronization points, so alloc_tid can
120  *          wind up (harmlessly) more advanced on flush.
121  */
122 void
123 hammer2_trans_init(hammer2_trans_t *trans, hammer2_pfsmount_t *pmp,
124                    hammer2_mount_t *hmp, int flags)
125 {
126         hammer2_trans_t *head;
127
128         bzero(trans, sizeof(*trans));
129         if (pmp) {
130                 trans->pmp = pmp;
131                 KKASSERT(hmp == NULL);
132                 hmp = pmp->cluster.chains[0]->hmp;      /* XXX */
133         } else {
134                 trans->hmp_single = hmp;
135                 KKASSERT(hmp);
136         }
137
138         hammer2_voldata_lock(hmp);
139         trans->flags = flags;
140         trans->td = curthread;
141         /*trans->delete_gen = 0;*/      /* multiple deletions within trans */
142
143         if (flags & HAMMER2_TRANS_ISFLUSH) {
144                 /*
145                  * If multiple flushes are trying to run we have to
146                  * wait until it is our turn.  All flushes are serialized.
147                  *
148                  * We queue ourselves and then wait to become the head
149                  * of the queue, allowing all prior flushes to complete.
150                  */
151                 ++hmp->flushcnt;
152                 trans->sync_tid = hmp->voldata.alloc_tid++;
153                 trans->real_tid = trans->sync_tid;
154                 TAILQ_INSERT_TAIL(&hmp->transq, trans, entry);
155                 if (TAILQ_FIRST(&hmp->transq) != trans) {
156                         trans->blocked = 1;
157                         while (trans->blocked) {
158                                 lksleep(&trans->sync_tid, &hmp->voldatalk,
159                                         0, "h2multf", hz);
160                         }
161                 }
162         } else if (hmp->flushcnt == 0) {
163                 /*
164                  * No flushes are pending, we can go.
165                  */
166                 TAILQ_INSERT_TAIL(&hmp->transq, trans, entry);
167                 trans->sync_tid = hmp->voldata.alloc_tid;
168                 trans->real_tid = trans->sync_tid;
169
170                 /* XXX improve/optimize inode allocation */
171         } else {
172                 /*
173                  * One or more flushes are pending.  We insert after
174                  * the current flush and may block.  We have priority
175                  * over any flushes that are not the current flush.
176                  *
177                  * TRANS_BUFCACHE transactions cannot block.
178                  */
179                 TAILQ_FOREACH(head, &hmp->transq, entry) {
180                         if (head->flags & HAMMER2_TRANS_ISFLUSH)
181                                 break;
182                 }
183                 KKASSERT(head);
184                 TAILQ_INSERT_AFTER(&hmp->transq, head, trans, entry);
185                 trans->sync_tid = head->real_tid + 1;
186                 trans->real_tid = trans->sync_tid;
187
188                 if ((trans->flags & HAMMER2_TRANS_BUFCACHE) == 0) {
189                         if (TAILQ_FIRST(&hmp->transq) != head) {
190                                 trans->blocked = 1;
191                                 while (trans->blocked) {
192                                         lksleep(&trans->sync_tid,
193                                                 &hmp->voldatalk, 0,
194                                                 "h2multf", hz);
195                                 }
196                         }
197                 }
198         }
199         if (flags & HAMMER2_TRANS_NEWINODE)
200                 trans->inode_tid = hmp->voldata.inode_tid++;
201         hammer2_voldata_unlock(hmp, 0);
202 }
203
204 void
205 hammer2_trans_done(hammer2_trans_t *trans)
206 {
207         hammer2_mount_t *hmp;
208         hammer2_trans_t *head;
209         hammer2_trans_t *scan;
210
211         if (trans->pmp)
212                 hmp = trans->pmp->cluster.chains[0]->hmp;
213         else
214                 hmp = trans->hmp_single;
215
216         /*
217          * Remove and adjust flushcnt
218          */
219         hammer2_voldata_lock(hmp);
220         TAILQ_REMOVE(&hmp->transq, trans, entry);
221         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
222                 --hmp->flushcnt;
223
224         /*
225          * Unblock the head of the queue and any additional transactions
226          * up to the next flush.
227          */
228         head = TAILQ_FIRST(&hmp->transq);
229         if (head && head->blocked) {
230                 head->blocked = 0;
231                 wakeup(&head->sync_tid);
232
233                 scan = TAILQ_NEXT(head, entry);
234                 while (scan && (scan->flags & HAMMER2_TRANS_ISFLUSH) == 0) {
235                         if (scan->blocked) {
236                                 scan->blocked = 0;
237                                 wakeup(&scan->sync_tid);
238                         }
239                         scan = TAILQ_NEXT(scan, entry);
240                 }
241         }
242         hammer2_voldata_unlock(hmp, 0);
243 }
244
245 /*
246  * Flush the chain and all modified sub-chains through the specified
247  * synchronization point (sync_tid), propagating parent chain modifications
248  * and mirror_tid updates back up as needed.  Since we are recursing downward
249  * we do not have to deal with the complexities of multi-homed chains (chains
250  * with multiple parents).
251  *
252  * Caller must have interlocked against any non-flush-related modifying
253  * operations in progress whos modify_tid values are less than or equal
254  * to the passed sync_tid.
255  *
256  * Caller must have already vetted synchronization points to ensure they
257  * are properly flushed.  Only snapshots and cluster flushes can create
258  * these sorts of synchronization points.
259  *
260  * This routine can be called from several places but the most important
261  * is from the hammer2_vop_reclaim() function.  We want to try to completely
262  * clean out the inode structure to prevent disconnected inodes from
263  * building up and blowing out the kmalloc pool.  However, it is not actually
264  * necessary to flush reclaimed inodes to maintain HAMMER2's crash recovery
265  * capability.
266  *
267  * chain is locked on call and will remain locked on return.  If a flush
268  * occured, the chain's MOVED bit will be set indicating that its parent
269  * (which is not part of the flush) should be updated.  The chain may be
270  * replaced by the call.
271  */
272 void
273 hammer2_chain_flush(hammer2_trans_t *trans, hammer2_chain_t **chainp)
274 {
275         hammer2_chain_t *chain = *chainp;
276         hammer2_chain_t *scan;
277         hammer2_chain_core_t *core;
278         hammer2_flush_info_t info;
279         int loops;
280
281         /*
282          * Execute the recursive flush and handle deferrals.
283          *
284          * Chains can be ridiculously long (thousands deep), so to
285          * avoid blowing out the kernel stack the recursive flush has a
286          * depth limit.  Elements at the limit are placed on a list
287          * for re-execution after the stack has been popped.
288          */
289         bzero(&info, sizeof(info));
290         TAILQ_INIT(&info.flush_list);
291         info.trans = trans;
292         info.sync_tid = trans->sync_tid;
293         info.cache_index = -1;
294
295         core = chain->core;
296 #if FLUSH_DEBUG
297         kprintf("CHAIN FLUSH trans %p.%016jx chain %p.%d mod %016jx upd %016jx\n", trans, trans->sync_tid, chain, chain->bref.type, chain->modify_tid, core->update_lo);
298 #endif
299
300         /*
301          * Extra ref needed because flush_core expects it when replacing
302          * chain.
303          */
304         hammer2_chain_ref(chain);
305         loops = 0;
306
307         for (;;) {
308                 /*
309                  * Unwind deep recursions which had been deferred.  This
310                  * can leave MOVED set for these chains, which will be
311                  * handled when we [re]flush chain after the unwind.
312                  */
313                 while ((scan = TAILQ_FIRST(&info.flush_list)) != NULL) {
314                         KKASSERT(scan->flags & HAMMER2_CHAIN_DEFERRED);
315                         TAILQ_REMOVE(&info.flush_list, scan, flush_node);
316                         atomic_clear_int(&scan->flags, HAMMER2_CHAIN_DEFERRED);
317
318                         /*
319                          * Now that we've popped back up we can do a secondary
320                          * recursion on the deferred elements.
321                          *
322                          * NOTE: hammer2_chain_flush() may replace scan.
323                          */
324                         if (hammer2_debug & 0x0040)
325                                 kprintf("deferred flush %p\n", scan);
326                         hammer2_chain_lock(scan, HAMMER2_RESOLVE_MAYBE);
327                         hammer2_chain_drop(scan);       /* ref from deferral */
328                         hammer2_chain_flush(trans, &scan);
329                         hammer2_chain_unlock(scan);
330                 }
331
332                 /*
333                  * [re]flush chain.
334                  */
335                 info.diddeferral = 0;
336                 hammer2_chain_flush_core(&info, &chain);
337 #if FLUSH_DEBUG
338                 kprintf("flush_core_done parent=<base> chain=%p.%d %08x\n",
339                         chain, chain->bref.type, chain->flags);
340 #endif
341
342                 /*
343                  * Only loop if deep recursions have been deferred.
344                  */
345                 if (TAILQ_EMPTY(&info.flush_list))
346                         break;
347
348                 if (++loops % 1000 == 0) {
349                         kprintf("hammer2_chain_flush: excessive loops on %p\n",
350                                 chain);
351                         if (hammer2_debug & 0x100000)
352                                 Debugger("hell4");
353                 }
354         }
355         hammer2_chain_drop(chain);
356         *chainp = chain;
357 }
358
359 /*
360  * This is the core of the chain flushing code.  The chain is locked by the
361  * caller and must also have an extra ref on it by the caller, and remains
362  * locked and will have an extra ref on return.
363  *
364  * If the flush accomplished any work chain will be flagged MOVED
365  * indicating a copy-on-write propagation back up is required.
366  * Deep sub-nodes may also have been entered onto the deferral list.
367  * MOVED is never set on the volume root.
368  *
369  * NOTE: modify_tid is different from MODIFIED.  modify_tid is updated
370  *       only when a chain is specifically modified, and not updated
371  *       for copy-on-write propagations.  MODIFIED is set on any modification
372  *       including copy-on-write propagations.
373  *
374  * NOTE: We are responsible for updating chain->bref.mirror_tid and
375  *       core->update_lo  The caller is responsible for processing us into
376  *       our parent (if any).
377  *
378  *       We are also responsible for updating chain->core->update_lo to
379  *       prevent repeated recursions due to deferrals.
380  */
381 static void
382 hammer2_chain_flush_core(hammer2_flush_info_t *info, hammer2_chain_t **chainp)
383 {
384         hammer2_chain_t *chain = *chainp;
385         hammer2_mount_t *hmp;
386         hammer2_blockref_t *bref;
387         hammer2_chain_core_t *core;
388         char *bdata;
389         hammer2_io_t *dio;
390         int error;
391         int diddeferral;
392
393         hmp = chain->hmp;
394         core = chain->core;
395         diddeferral = info->diddeferral;
396
397 #if FLUSH_DEBUG
398         if (info->parent)
399                 kprintf("flush_core %p->%p.%d %08x (%s)\n",
400                         info->parent, chain, chain->bref.type,
401                         chain->flags,
402                         ((chain->bref.type == HAMMER2_BREF_TYPE_INODE) ?
403                                 (char *)chain->data->ipdata.filename : "?"));
404         else
405                 kprintf("flush_core NULL->%p.%d %08x (%s)\n",
406                         chain, chain->bref.type,
407                         chain->flags,
408                         ((chain->bref.type == HAMMER2_BREF_TYPE_INODE) ?
409                                 (char *)chain->data->ipdata.filename : "?"));
410         kprintf("PUSH   %p.%d %08x mod=%016jx del=%016jx mirror=%016jx (sync %016jx, update_lo %016jx)\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid, chain->bref.mirror_tid, info->sync_tid, core->update_lo);
411 #endif
412
413         /*
414          * Check if we even have any work to do.
415          *
416          * We do not update bref.mirror_tid if nothing is being modified.
417          * We do not update core->update_lo because there might be other
418          * paths to the core and we haven't actually checked it.
419          *
420          * This bit of code is capable of short-cutting entire sub-trees
421          * if they have not been touched.
422          */
423         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0 &&
424             (core->update_lo >= info->sync_tid ||
425              chain->bref.mirror_tid >= info->sync_tid ||
426              chain->bref.mirror_tid >= core->update_hi)) {
427                 return;
428         }
429
430         /*
431          * Ignore chains modified beyond the current flush point.  These
432          * will be treated as if they did not exist.  Subchains with lower
433          * modify_tid's will still be accessible via other parents.
434          *
435          * Do not update bref.mirror_tid here, it will interfere with
436          * synchronization.  e.g. inode flush tid 1, concurrent D-D tid 2,
437          * then later on inode flush tid 2.  If we were to set mirror_tid
438          * to 1 during inode flush tid 1 the blockrefs would only be partially
439          * updated (and likely panic).
440          *
441          * Do not update core->update_lo here, there might be other paths
442          * to the core and we haven't actually flushed it.
443          *
444          * (vchain and fchain are exceptions since they cannot be duplicated)
445          */
446         if (chain->modify_tid > info->sync_tid &&
447             chain != &hmp->fchain && chain != &hmp->vchain) {
448                 chain->debug_reason = (chain->debug_reason & ~255) | 5;
449                 /* do not update bref.mirror_tid */
450                 /* do not update core->update_lo, there may be another path */
451                 return;
452         }
453
454 retry:
455         /*
456          * Early handling of deleted chains is required to avoid double
457          * recursions.  If the deleted chain has been duplicated then the
458          * flush will have visibility into chain->core via some other chain
459          * and we can safely terminate the operation right here.
460          *
461          * If the deleted chain has not been duplicated then the deletion
462          * is terminal and we must recurse to deal with any dirty chains
463          * under the deletion, including possibly flushing them out (e.g.
464          * open descriptor on an unlinked file).
465          */
466         if (chain->delete_tid <= info->sync_tid &&
467             (chain->flags & HAMMER2_CHAIN_DUPLICATED)) {
468                 chain->debug_reason = (chain->debug_reason & ~255) | 9;
469                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
470 #if 1
471                         /*
472                          * XXX what if we have a snapshot?
473                          */
474                         if (chain->dio) {
475                                 hammer2_io_setinval(chain->dio, chain->bytes);
476                         }
477 #endif
478                         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
479                                 hammer2_chain_ref(chain);
480                                 atomic_set_int(&chain->flags,
481                                                HAMMER2_CHAIN_MOVED);
482                         }
483                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
484                         hammer2_chain_drop(chain);
485                 }
486
487                 /*
488                  * Update mirror_tid, indicating that chain is synchronized
489                  * on its modification and block table.
490                  */
491                 if (chain->bref.mirror_tid < info->sync_tid)
492                         chain->bref.mirror_tid = info->sync_tid;
493                 /* do not update core->update_lo, there may be another path */
494                 return;
495         }
496
497         /*
498          * Recurse if we are not up-to-date.  Once we are done we will
499          * update update_lo if there were no deferrals.  update_lo can become
500          * higher than update_hi and is used to prevent re-recursions during
501          * the same flush cycle.
502          *
503          * update_hi was already checked and prevents initial recursions on
504          * subtrees which have not been modified.
505          *
506          * NOTE: We must recurse whether chain is flagged DELETED or not.
507          *       However, if it is flagged DELETED we limit sync_tid to
508          *       delete_tid to ensure that the chain's bref.mirror_tid is
509          *       not fully updated and causes it to miss the non-DELETED
510          *       path.
511          *
512          * NOTE: If a deferral occurs hammer2_chain_flush() will flush the
513          *       deferred chain independently which will update it's
514          *       bref.mirror_tid and prevent it from deferred again.
515          */
516         if (chain->bref.mirror_tid < info->sync_tid &&
517             chain->bref.mirror_tid < core->update_hi) {
518                 hammer2_chain_t *saved_parent;
519                 hammer2_chain_layer_t *layer;
520                 int saved_domodify;
521                 int save_gen;
522
523                 /*
524                  * Races will bump update_hi above trans->sync_tid causing
525                  * us to catch the issue in a later flush.
526                  *
527                  * We don't want to set our chain to MODIFIED gratuitously.
528                  *
529                  * We need an extra ref on chain because we are going to
530                  * release its lock temporarily in our child loop.
531                  */
532
533                 /*
534                  * Run two passes.  The first pass handles MODIFIED and
535                  * update_lo recursions while the second pass handles
536                  * MOVED chains on the way back up.
537                  *
538                  * If the stack gets too deep we defer the chain.   Since
539                  * hammer2_chain_core's can be shared at multiple levels
540                  * in the tree, we may encounter a chain that we had already
541                  * deferred.  We could undefer it but it will probably just
542                  * defer again so it is best to leave it deferred.
543                  *
544                  * Scan1 is recursive.
545                  *
546                  * NOTE: The act of handling a modified/submodified chain can
547                  *       cause the MOVED Flag to be set.  It can also be set
548                  *       via hammer2_chain_delete() and in other situations.
549                  *
550                  * NOTE: RB_SCAN() must be used instead of RB_FOREACH()
551                  *       because children can be physically removed during
552                  *       the scan.
553                  *
554                  * NOTE: We would normally not care about insertions except
555                  *       that some insertions might occur from the flush
556                  *       itself, so loop on generation number changes.
557                  */
558                 saved_parent = info->parent;
559                 saved_domodify = info->domodify;
560                 info->parent = chain;
561                 info->domodify = 0;
562                 chain->debug_reason = (chain->debug_reason & ~255) | 6;
563
564                 if (chain->flags & HAMMER2_CHAIN_DEFERRED) {
565                         ++info->diddeferral;
566                 } else if (info->depth == HAMMER2_FLUSH_DEPTH_LIMIT) {
567                         if ((chain->flags & HAMMER2_CHAIN_DEFERRED) == 0) {
568                                 hammer2_chain_ref(chain);
569                                 TAILQ_INSERT_TAIL(&info->flush_list,
570                                                   chain, flush_node);
571                                 atomic_set_int(&chain->flags,
572                                                HAMMER2_CHAIN_DEFERRED);
573                         }
574                         ++info->diddeferral;
575                 } else {
576                         spin_lock(&core->cst.spin);
577                         KKASSERT(core->good == 0x1234 && core->sharecnt > 0);
578                         do {
579                                 save_gen = core->generation;
580                                 TAILQ_FOREACH_REVERSE(layer, &core->layerq,
581                                                       h2_layer_list, entry) {
582                                         ++layer->refs;
583                                         KKASSERT(layer->good == 0xABCD);
584                                         RB_SCAN(hammer2_chain_tree,
585                                                 &layer->rbtree,
586                                                 NULL, hammer2_chain_flush_scan1,
587                                                 info);
588                                         --layer->refs;
589                                 }
590                         } while (core->generation != save_gen);
591                         spin_unlock(&core->cst.spin);
592                 }
593
594                 if (info->parent != chain) {
595                         kprintf("ZZZ\n");
596                         hammer2_chain_drop(chain);
597                         hammer2_chain_ref(info->parent);
598                 }
599                 chain = info->parent;
600
601                 /*
602                  * We unlock the parent during the scan1 recursion, parent
603                  * may have been deleted out from under us.
604                  * parent may have been destroyed out from under us
605                  */
606                 if (chain->delete_tid <= info->sync_tid &&
607                     (chain->flags & HAMMER2_CHAIN_DUPLICATED)) {
608                         kprintf("xxx\n");
609                         goto retry;
610                 }
611                 if (chain->bref.mirror_tid >= info->sync_tid ||
612                     chain->bref.mirror_tid >= core->update_hi) {
613                         kprintf("yyy\n");
614                         goto retry;
615                 }
616
617                 /*
618                  * If any deferral occurred we must set domodify to 0 to avoid
619                  * potentially modifying the parent twice (now and when we run
620                  * the deferral list), as doing so could cause the blockref
621                  * update to run on a block array which has already been
622                  * updated.
623                  */
624                 if (info->domodify && diddeferral != info->diddeferral)
625                         info->domodify = 0;
626
627                 /*
628                  * We are responsible for setting the parent into a modified
629                  * state before we scan the children to update the parent's
630                  * block table.  This must essentially be done as an atomic
631                  * operation (the parent must remain locked throughout the
632                  * operation).
633                  *
634                  * Care must be taken to not try to update the parent twice
635                  * during the current flush cycle, which would likely
636                  * result in an assertion getting hit.  The MOVED bit on
637                  * the children does not add any measure of safety since it
638                  * cannot be immediately cleared (there might be other
639                  * parents that require action XXX).
640                  *
641                  * NOTE: Blockrefs are only updated on live chains.
642                  *
643                  * NOTE: Modifying the parent generally causes a
644                  *       delete-duplicate to occur from within the flush
645                  *       itself, with an allocation from the freemap occuring
646                  *       as an additional side-effect.
647                  *
648                  * NOTE: If the parent was deleted our modified chain will
649                  *       also be marked deleted, but since it inherits the
650                  *       parent's delete_tid it will still appear to be
651                  *       'live' for the purposes of the flush.
652                  */
653                 if (info->domodify && chain->delete_tid > info->sync_tid) {
654                         KKASSERT(chain->modify_tid < info->sync_tid ||
655                                  (chain->flags & HAMMER2_CHAIN_FLUSHED) == 0);
656                         hammer2_chain_modify(info->trans, &info->parent,
657                                              HAMMER2_MODIFY_NO_MODIFY_TID);
658                         if (info->parent != chain) {
659                                 hammer2_chain_drop(chain);
660                                 hammer2_chain_ref(info->parent);
661                         }
662                         chain = info->parent;
663                 }
664                 if (info->domodify)
665                         KKASSERT(chain->modify_tid == info->sync_tid);
666                 chain->debug_reason = (chain->debug_reason & ~255) | 7;
667
668                 KKASSERT(chain == info->parent);
669
670                 /*
671                  * Handle successfully flushed children who are in the MOVED
672                  * state on the way back up the recursion.  This can have
673                  * the side-effect of clearing MOVED.
674                  *
675                  * Scan2 may replace info->parent.  If it does it will also
676                  * replace the extra ref we made.
677                  *
678                  * Scan2 is non-recursive.
679                  */
680                 if (diddeferral != info->diddeferral) {
681                         spin_lock(&core->cst.spin);
682                 } else {
683                         KKASSERT(chain == info->parent);
684                         KKASSERT(info->domodify == 0 ||
685                                  (chain->flags & HAMMER2_CHAIN_FLUSHED) == 0);
686                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSHED);
687                         spin_lock(&core->cst.spin);
688                         KKASSERT(core->good == 0x1234 && core->sharecnt > 0);
689                         KKASSERT(info->parent->core == core);
690                         TAILQ_FOREACH_REVERSE(layer, &core->layerq,
691                                               h2_layer_list, entry) {
692                                 info->pass = 1;
693                                 ++layer->refs;
694                                 KKASSERT(layer->good == 0xABCD);
695                                 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
696                                         NULL, hammer2_chain_flush_scan2, info);
697                                 info->pass = 2;
698                                 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
699                                         NULL, hammer2_chain_flush_scan2, info);
700                                 --layer->refs;
701                         }
702
703                         /*
704                          * chain is now considered up-to-date, adjust
705                          * bref.mirror_tid and update_lo before running
706                          * pass3.
707                          *
708                          * (no deferral in this path)
709                          */
710                         if (core->update_lo < info->sync_tid)
711                                 core->update_lo = info->sync_tid;
712
713                         TAILQ_FOREACH_REVERSE(layer, &core->layerq,
714                                               h2_layer_list, entry) {
715                                 info->pass = 3;
716                                 ++layer->refs;
717                                 KKASSERT(layer->good == 0xABCD);
718                                 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
719                                         NULL, hammer2_chain_flush_scan2, info);
720                                 --layer->refs;
721                                 KKASSERT(info->parent->core == core);
722                         }
723                 }
724
725                 /*
726                  * info->parent must not have been replaced again
727                  */
728                 KKASSERT(info->parent == chain);
729
730                 chain->debug_reason = (chain->debug_reason & ~255) | 8;
731                 *chainp = chain;
732
733                 hammer2_chain_layer_check_locked(chain->hmp, core);
734                 spin_unlock(&core->cst.spin);
735
736                 info->parent = saved_parent;
737                 info->domodify = saved_domodify;
738                 KKASSERT(chain->refs > 1);
739         } else {
740                 /*
741                  * chain is now considered up-to-date, adjust
742                  * bref.mirror_tid and update_lo.
743                  *
744                  * (no deferral in this path)
745                  */
746                 if (core->update_lo < info->sync_tid)
747                         core->update_lo = info->sync_tid;
748
749         }
750
751 #if FLUSH_DEBUG
752         kprintf("POP    %p.%d defer=%d\n", chain, chain->bref.type, diddeferral);
753 #endif
754
755         /*
756          * Do not flush chain if there were any deferrals.  It will be
757          * retried later after the deferrals are independently handled.
758          * Do not update update_lo or bref.mirror_tid.
759          */
760         if (diddeferral != info->diddeferral) {
761                 chain->debug_reason = (chain->debug_reason & ~255) | 99;
762                 if (hammer2_debug & 0x0008) {
763                         kprintf("%*.*s} %p/%d %04x (deferred)",
764                                 info->depth, info->depth, "",
765                                 chain, chain->refs, chain->flags);
766                 }
767                 /* do not update core->update_lo */
768                 return;
769         }
770
771         /*
772          * non-deferred path - mirror_tid and update_lo have been updated
773          * at this point.
774          *
775          * Deal with deleted chains on the way back up.  Deleted inodes may
776          * still be active due to open descriptors so test whether the inode
777          * has been DESTROYED (aka deactivated after being unlinked) or not.
778          * Clear the modified bit if it is set.
779          *
780          * NOTE: We optimize this by noting that only 'inode' chains require
781          *       this treatment.  When a file with an open descriptor is
782          *       deleted only its inode is marked deleted.  Other deletions,
783          *       such as indirect block deletions, will no longer be visible
784          *       to the live filesystem and do not need to be updated.
785          *
786          * NOTE: scan2 has already executed above so statistics have
787          *       already been rolled up.
788          */
789         if (chain->delete_tid <= info->sync_tid &&
790             (chain->bref.type != HAMMER2_BREF_TYPE_INODE ||
791               (chain->flags & HAMMER2_CHAIN_DESTROYED))) {
792                 /*
793                  * At the moment we unconditionally set the MOVED bit because
794                  * there are situations where it might not have been set due
795                  * to similar delete-destroyed optimizations, and the parent
796                  * of the parent still may need to be notified of the deletion.
797                  */
798                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
799                         hammer2_chain_ref(chain);
800                         atomic_set_int(&chain->flags,
801                                        HAMMER2_CHAIN_MOVED);
802                 }
803                 chain->debug_reason = (chain->debug_reason & ~255) | 9;
804                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
805 #if 1
806                         /*
807                          * XXX what if we have a snapshot?
808                          * Can only destroy the buffer if the chain represents
809                          * the entire contents of the buffer.
810                          */
811                         if (chain->dio) {
812                                 hammer2_io_setinval(chain->dio, chain->bytes);
813                         }
814 #endif
815                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
816                         hammer2_chain_drop(chain);
817                 }
818
819                 /*
820                  * Update mirror_tid, indicating that chain is synchronized
821                  * on its modification and block table.
822                  */
823                 if (chain->bref.mirror_tid < info->sync_tid)
824                         chain->bref.mirror_tid = info->sync_tid;
825                 return;
826         }
827
828         /*
829          * A degenerate flush might not have flushed anything and thus not
830          * processed modified blocks on the way back up.  Detect the case.
831          */
832         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
833                 kprintf("chain %p.%d %08x recursed but wasn't "
834                         "modified mirr=%016jx "
835                         "update_lo=%016jx synctid=%016jx\n",
836                         chain, chain->bref.type, chain->flags,
837                         chain->bref.mirror_tid,
838                         core->update_lo, info->sync_tid);
839 #if 0
840                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
841                         hammer2_chain_ref(chain);
842                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
843                 }
844 #endif
845                 chain->debug_reason = (chain->debug_reason & ~255) | 10;
846
847                 /*
848                  * Update mirror_tid, indicating that chain is synchronized
849                  * on its modification and block table.
850                  */
851                 if (chain->bref.mirror_tid < info->sync_tid)
852                         chain->bref.mirror_tid = info->sync_tid;
853                 return;
854         }
855
856         chain->debug_reason = (chain->debug_reason & ~255) | 11;
857
858         /*
859          * Issue flush.
860          *
861          * A DESTROYED node that reaches this point must be flushed for
862          * synchronization point consistency.
863          *
864          * Update bref.mirror_tid, clear MODIFIED, and set MOVED.
865          *
866          * The caller will update the parent's reference to this chain
867          * by testing MOVED as long as the modification was in-bounds.
868          *
869          * MOVED is never set on the volume root as there is no parent
870          * to adjust.
871          */
872         if (hammer2_debug & 0x1000) {
873                 kprintf("Flush %p.%d %016jx/%d sync_tid %016jx\n",
874                         chain, chain->bref.type,
875                         chain->bref.key, chain->bref.keybits,
876                         info->sync_tid);
877         }
878         if (hammer2_debug & 0x2000) {
879                 Debugger("Flush hell");
880         }
881
882         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
883
884         if ((chain->flags & HAMMER2_CHAIN_MOVED) ||
885             chain == &hmp->vchain ||
886             chain == &hmp->fchain) {
887                 /*
888                  * Drop the ref from the MODIFIED bit we cleared,
889                  * net -1 ref.
890                  */
891                 hammer2_chain_drop(chain);
892         } else {
893                 /*
894                  * Drop the ref from the MODIFIED bit we cleared and
895                  * set a ref for the MOVED bit we are setting.  Net 0 refs.
896                  */
897                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
898         }
899
900         /*
901          * We are writing out the parent (writing out of the volume root is
902          * deferred but we still do some hand-waving).
903          *
904          * Update mirror_tid on the parent.
905          */
906         if (chain->bref.mirror_tid < info->sync_tid)
907                 chain->bref.mirror_tid = info->sync_tid;
908
909         /*
910          * If this is part of a recursive flush we can go ahead and write
911          * out the buffer cache buffer and pass a new bref back up the chain
912          * via the MOVED bit.
913          *
914          * Volume headers are NOT flushed here as they require special
915          * processing.
916          */
917         switch(chain->bref.type) {
918         case HAMMER2_BREF_TYPE_FREEMAP:
919                 hammer2_modify_volume(hmp);
920                 hmp->voldata.freemap_tid = hmp->fchain.bref.mirror_tid;
921                 break;
922         case HAMMER2_BREF_TYPE_VOLUME:
923                 /*
924                  * The free block table is flushed by hammer2_vfs_sync()
925                  * before it flushes vchain.  We must still hold fchain
926                  * locked while copying voldata to volsync, however.
927                  */
928                 hammer2_chain_lock(&hmp->fchain, HAMMER2_RESOLVE_ALWAYS);
929 #if 0
930                 if ((hmp->fchain.flags & HAMMER2_CHAIN_MODIFIED) ||
931                     hmp->voldata.freemap_tid < info->trans->sync_tid) {
932                         /* this will modify vchain as a side effect */
933                         hammer2_chain_t *tmp = &hmp->fchain;
934                         hammer2_chain_flush(info->trans, &tmp);
935                         KKASSERT(tmp == &hmp->fchain);
936                 }
937 #endif
938
939                 /*
940                  * There is no parent to our root vchain and fchain to
941                  * synchronize the bref to, their updated mirror_tid's
942                  * must be synchronized to the volume header.
943                  */
944                 hmp->voldata.mirror_tid = chain->bref.mirror_tid;
945                 /*hmp->voldata.freemap_tid = hmp->fchain.bref.mirror_tid;*/
946
947                 /*
948                  * The volume header is flushed manually by the syncer, not
949                  * here.  All we do here is adjust the crc's.
950                  */
951                 KKASSERT(chain->data != NULL);
952                 KKASSERT(chain->dio == NULL);
953
954                 hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT1]=
955                         hammer2_icrc32(
956                                 (char *)&hmp->voldata +
957                                  HAMMER2_VOLUME_ICRC1_OFF,
958                                 HAMMER2_VOLUME_ICRC1_SIZE);
959                 hmp->voldata.icrc_sects[HAMMER2_VOL_ICRC_SECT0]=
960                         hammer2_icrc32(
961                                 (char *)&hmp->voldata +
962                                  HAMMER2_VOLUME_ICRC0_OFF,
963                                 HAMMER2_VOLUME_ICRC0_SIZE);
964                 hmp->voldata.icrc_volheader =
965                         hammer2_icrc32(
966                                 (char *)&hmp->voldata +
967                                  HAMMER2_VOLUME_ICRCVH_OFF,
968                                 HAMMER2_VOLUME_ICRCVH_SIZE);
969                 hmp->volsync = hmp->voldata;
970                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_VOLUMESYNC);
971                 hammer2_chain_unlock(&hmp->fchain);
972                 break;
973         case HAMMER2_BREF_TYPE_DATA:
974                 /*
975                  * Data elements have already been flushed via the logical
976                  * file buffer cache.  Their hash was set in the bref by
977                  * the vop_write code.
978                  *
979                  * Make sure any device buffer(s) have been flushed out here.
980                  * (there aren't usually any to flush).
981                  */
982 #if 0
983                 /* XXX */
984                 /* chain and chain->bref, NOWAIT operation */
985 #endif
986                 break;
987 #if 0
988         case HAMMER2_BREF_TYPE_INDIRECT:
989                 /*
990                  * Indirect blocks may be in an INITIAL state.  Use the
991                  * chain_lock() call to ensure that the buffer has been
992                  * instantiated (even though it is already locked the buffer
993                  * might not have been instantiated).
994                  *
995                  * Only write the buffer out if it is dirty, it is possible
996                  * the operating system had already written out the buffer.
997                  */
998                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
999                 KKASSERT(chain->dio != NULL);
1000
1001                 chain->data = NULL;
1002                 hammer2_io_bqrelse(&chain->dio);
1003                 hammer2_chain_unlock(chain);
1004                 break;
1005 #endif
1006         case HAMMER2_BREF_TYPE_INDIRECT:
1007         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1008                 /*
1009                  * Device-backed.  Buffer will be flushed by the sync
1010                  * code XXX.
1011                  */
1012                 KKASSERT((chain->flags & HAMMER2_CHAIN_EMBEDDED) == 0);
1013                 break;
1014         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1015         default:
1016                 /*
1017                  * Embedded elements have to be flushed out.
1018                  * (Basically just BREF_TYPE_INODE).
1019                  */
1020                 KKASSERT(chain->flags & HAMMER2_CHAIN_EMBEDDED);
1021                 KKASSERT(chain->data != NULL);
1022                 KKASSERT(chain->dio == NULL);
1023                 bref = &chain->bref;
1024
1025                 KKASSERT((bref->data_off & HAMMER2_OFF_MASK) != 0);
1026                 KKASSERT(HAMMER2_DEC_CHECK(chain->bref.methods) ==
1027                          HAMMER2_CHECK_ISCSI32 ||
1028                          HAMMER2_DEC_CHECK(chain->bref.methods) ==
1029                          HAMMER2_CHECK_FREEMAP);
1030
1031                 /*
1032                  * The data is embedded, we have to acquire the
1033                  * buffer cache buffer and copy the data into it.
1034                  */
1035                 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
1036                                          &dio);
1037                 KKASSERT(error == 0);
1038                 bdata = hammer2_io_data(dio, bref->data_off);
1039
1040                 /*
1041                  * Copy the data to the buffer, mark the buffer
1042                  * dirty, and convert the chain to unmodified.
1043                  */
1044                 bcopy(chain->data, bdata, chain->bytes);
1045                 hammer2_io_bdwrite(&dio);
1046
1047                 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
1048                 case HAMMER2_CHECK_FREEMAP:
1049                         chain->bref.check.freemap.icrc32 =
1050                                 hammer2_icrc32(chain->data, chain->bytes);
1051                         break;
1052                 case HAMMER2_CHECK_ISCSI32:
1053                         chain->bref.check.iscsi32.value =
1054                                 hammer2_icrc32(chain->data, chain->bytes);
1055                         break;
1056                 default:
1057                         panic("hammer2_flush_core: bad crc type");
1058                         break; /* NOT REACHED */
1059                 }
1060                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
1061                         ++hammer2_iod_meta_write;
1062                 else
1063                         ++hammer2_iod_indr_write;
1064         }
1065 }
1066
1067 /*
1068  * Flush helper scan1 (recursive)
1069  *
1070  * Flushes the children of the caller's chain (parent) and updates
1071  * the blockref, restricted by sync_tid.
1072  *
1073  * Ripouts during the loop should not cause any problems.  Because we are
1074  * flushing to a synchronization point, modification races will occur after
1075  * sync_tid and do not have to be flushed anyway.
1076  *
1077  * It is also ok if the parent is chain_duplicate()'d while unlocked because
1078  * the delete/duplication will install a delete_tid that is still larger than
1079  * our current sync_tid.
1080  *
1081  * WARNING! If we do not call chain_flush_core we must update bref.mirror_tid
1082  *          ourselves.
1083  */
1084 static int
1085 hammer2_chain_flush_scan1(hammer2_chain_t *child, void *data)
1086 {
1087         hammer2_flush_info_t *info = data;
1088         hammer2_trans_t *trans = info->trans;
1089         hammer2_chain_t *parent = info->parent;
1090         int     diddeferral;
1091
1092         if (hammer2_debug & 0x80000)
1093                 Debugger("hell3");
1094         diddeferral = info->diddeferral;
1095
1096         /*
1097          * Child is beyond the flush synchronization zone, don't persue.
1098          * Remember that modifications generally delete-duplicate so if the
1099          * sub-tree is dirty another child will get us there.  But not this
1100          * one.
1101          *
1102          * Or MODIFIED is not set and child is already fully synchronized
1103          * with its sub-tree.  Don't persue.
1104          *
1105          * (child can never be fchain or vchain so a special check isn't
1106          *  needed).
1107          */
1108         if (child->modify_tid > trans->sync_tid) {
1109                 KKASSERT(child->delete_tid >= child->modify_tid);
1110                 child->debug_reason = (child->debug_reason & ~255) | 1;
1111                 /* do not update child->core->update_lo, core not flushed */
1112                 /* do not update core->update_lo, there may be another path */
1113                 return (0);
1114         }
1115
1116         /*
1117          * We must ref the child before unlocking the spinlock.
1118          *
1119          * The caller has added a ref to the parent so we can temporarily
1120          * unlock it in order to lock the child.
1121          */
1122         hammer2_chain_ref(child);
1123         spin_unlock(&parent->core->cst.spin);
1124
1125         hammer2_chain_unlock(parent);
1126         hammer2_chain_lock(child, HAMMER2_RESOLVE_MAYBE);
1127
1128 #if 0
1129         /*
1130          * This isn't working atm, it seems to be causing necessary
1131          * updates to be thrown away, probably due to aliasing, resulting
1132          * base_insert/base_delete panics.
1133          */
1134         /*
1135          * The DESTROYED flag can only be initially set on an unreferenced
1136          * deleted inode and will propagate downward via the mechanic below.
1137          * Such inode chains have been deleted for good and should no longer
1138          * be subject to delete/duplication.
1139          *
1140          * This optimization allows the inode reclaim (destroy unlinked file
1141          * on vnode reclamation after last close) to be flagged by just
1142          * setting HAMMER2_CHAIN_DESTROYED at the top level and then will
1143          * cause the chains to be terminated and related buffers to be
1144          * invalidated and not flushed out.
1145          *
1146          * We have to be careful not to propagate the DESTROYED flag if
1147          * the destruction occurred after our flush sync_tid.
1148          */
1149         if (parent->delete_tid <= trans->sync_tid &&
1150             (parent->flags & HAMMER2_CHAIN_DESTROYED) &&
1151             (child->flags & HAMMER2_CHAIN_DESTROYED) == 0) {
1152                 /*
1153                  * Force downward recursion by bringing update_hi up to
1154                  * at least sync_tid, and setting the DESTROYED flag.
1155                  * Parent's mirror_tid has not yet been updated.
1156                  *
1157                  * We do not mark the child DELETED because this would
1158                  * cause unnecessary modifications/updates.  Instead, the
1159                  * DESTROYED flag propagates downward and causes the flush
1160                  * to ignore any pre-existing modified chains.
1161                  *
1162                  * Vnode reclamation may have forced update_hi to MAX_TID
1163                  * (we do this because there was no transaction at the time).
1164                  * In this situation bring it down to something reasonable
1165                  * so the elements being destroyed can be retired.
1166                  */
1167                 atomic_set_int(&child->flags, HAMMER2_CHAIN_DESTROYED);
1168                 spin_lock(&child->core->cst.spin);
1169                 if (child->core->update_hi < trans->sync_tid)
1170                         child->core->update_hi = trans->sync_tid;
1171                 spin_unlock(&child->core->cst.spin);
1172         }
1173 #endif
1174
1175         /*
1176          * No recursion needed if neither the child or anything under it
1177          * was messed with.
1178          */
1179         if ((child->flags & HAMMER2_CHAIN_MODIFIED) == 0 &&
1180             child->core->update_lo >= info->sync_tid) {
1181                 child->debug_reason = (child->debug_reason & ~255) | 2;
1182                 goto skip;
1183         }
1184
1185         /*
1186          * Re-check original pre-lock conditions after locking.
1187          */
1188         if (child->modify_tid > trans->sync_tid) {
1189                 child->debug_reason = (child->debug_reason & ~255) | 3;
1190                 hammer2_chain_unlock(child);
1191                 hammer2_chain_drop(child);
1192                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
1193                 spin_lock(&parent->core->cst.spin);
1194                 return (0);
1195         }
1196
1197         if ((child->flags & HAMMER2_CHAIN_MODIFIED) == 0 &&
1198             child->core->update_lo >= info->sync_tid) {
1199                 child->debug_reason = (child->debug_reason & ~255) | 4;
1200                 goto skip;
1201         }
1202
1203         /*
1204          * Recurse and collect deferral data.
1205          */
1206         ++info->depth;
1207         hammer2_chain_flush_core(info, &child);
1208         --info->depth;
1209
1210 skip:
1211         /*
1212          * Consider us flushed if there was no deferral.  This will have
1213          * already been handled by hammer2_chain_flush_core() but we also
1214          * have to deal with anyone who goto'd skip.
1215          */
1216         if (diddeferral == info->diddeferral) {
1217                 if (child->bref.mirror_tid < info->sync_tid)
1218                         child->bref.mirror_tid = info->sync_tid;
1219         }
1220
1221         /*
1222          * Check the conditions that could cause SCAN2 to modify the parent.
1223          * Modify the parent here instead of in SCAN2, which would cause
1224          * rollup chicken-and-egg races.
1225          *
1226          * Scan2 is expected to update bref.mirror_tid in the domodify case,
1227          * but will skip the child otherwise giving us the responsibility to
1228          * update bref.mirror_tid.
1229          */
1230         if (parent->delete_tid <= trans->sync_tid &&
1231             (parent->bref.type != HAMMER2_BREF_TYPE_INODE ||
1232              (parent->flags & HAMMER2_CHAIN_DESTROYED))) {
1233                 /*
1234                  * Special optimization matching similar tests done in
1235                  * flush_core, scan1, and scan2.  Avoid updating the block
1236                  * table in the parent if the parent is no longer visible.
1237                  * A deleted parent is no longer visible unless it's an
1238                  * inode (in which case it might have an open fd).. the
1239                  * DESTROYED flag must also be checked for inodes.
1240                  */
1241                 ;
1242         } else if (child->delete_tid <= trans->sync_tid &&
1243                    child->delete_tid > parent->bref.mirror_tid &&
1244                    child->modify_tid <= parent->bref.mirror_tid) {
1245                 info->domodify = 1;
1246         } else if (child->delete_tid > trans->sync_tid &&
1247                    child->modify_tid > parent->bref.mirror_tid) {
1248                 info->domodify = 1;             /* base insertion */
1249         }
1250
1251         /*
1252          * Relock to continue the loop
1253          */
1254         hammer2_chain_unlock(child);
1255         hammer2_chain_lock(parent, HAMMER2_RESOLVE_MAYBE);
1256         hammer2_chain_drop(child);
1257         KKASSERT(info->parent == parent);
1258
1259         spin_lock(&parent->core->cst.spin);
1260         return (0);
1261 }
1262
1263 /*
1264  * Flush helper scan2 (non-recursive)
1265  *
1266  * This pass on a chain's children propagates any MOVED or DELETED
1267  * elements back up the chain towards the root after those elements have
1268  * been fully flushed.  Unlike scan1, this function is NOT recursive and
1269  * the parent remains locked across the entire scan.
1270  *
1271  * SCAN2 is called twice, once with pass set to 1 and once with it set to 2.
1272  * We have to do this so base[] elements can be deleted in pass 1 to make
1273  * room for adding new elements in pass 2.
1274  *
1275  * This function also rolls up storage statistics.
1276  *
1277  * NOTE!  A deletion is a visbility issue, there can still be references to
1278  *        deleted elements (for example, to an unlinked file which is still
1279  *        open), and there can also be multiple chains pointing to the same
1280  *        bref where some are deleted and some are not (for example due to
1281  *        a rename).   So a chain marked for deletion is basically considered
1282  *        to be live until it is explicitly destroyed or until its ref-count
1283  *        reaches zero (also implying that MOVED and MODIFIED are clear).
1284  *
1285  * NOTE!  Info->parent will be locked but will only be instantiated/modified
1286  *        if it is either MODIFIED or if scan1 determined that block table
1287  *        updates will occur.
1288  *
1289  * NOTE!  SCAN2 is responsible for updating child->bref.mirror_tid only in
1290  *        the case where it modifies the parent (does a base insertion
1291  *        or deletion).  SCAN1 handled all other cases.
1292  */
1293 static int
1294 hammer2_chain_flush_scan2(hammer2_chain_t *child, void *data)
1295 {
1296         hammer2_flush_info_t *info = data;
1297         hammer2_chain_t *parent = info->parent;
1298         hammer2_chain_core_t *above = child->above;
1299         hammer2_mount_t *hmp = child->hmp;
1300         hammer2_trans_t *trans = info->trans;
1301         hammer2_blockref_t *base;
1302         int count;
1303         int ok;
1304
1305 #if FLUSH_DEBUG
1306         kprintf("SCAN2 %p.%d %08x mod=%016jx del=%016jx trans=%016jx\n", child, child->bref.type, child->flags, child->modify_tid, child->delete_tid, info->trans->sync_tid);
1307 #endif
1308         /*
1309          * Ignore children created after our flush point, treating them as
1310          * if they did not exist).  These children will not cause the parent
1311          * to be updated.
1312          *
1313          * Children deleted after our flush point are treated as having been
1314          * created for the purposes of the flush.  The parent's update_hi
1315          * will already be higher than our trans->sync_tid so the path for
1316          * the next flush is left intact.
1317          *
1318          * When we encounter such children and the parent chain has not been
1319          * deleted, delete/duplicated, or delete/duplicated-for-move, then
1320          * the parent may be used to funnel through several flush points.
1321          * These chains will still be visible to later flushes due to having
1322          * a higher update_hi than we can set in the current flush.
1323          */
1324         if (child->modify_tid > trans->sync_tid) {
1325                 KKASSERT(child->delete_tid >= child->modify_tid);
1326                 goto finalize;
1327         }
1328
1329 #if 0
1330         /*
1331          * Ignore children which have not changed.  The parent's block table
1332          * is already correct.
1333          *
1334          * XXX The MOVED bit is only cleared when all multi-homed parents
1335          *     have flushed, creating a situation where a re-flush can occur
1336          *     via a parent which has already flushed.  The hammer2_base_*()
1337          *     functions currently have a hack to deal with this case but
1338          *     we need something better.
1339          */
1340         if ((child->flags & HAMMER2_CHAIN_MOVED) == 0) {
1341                 KKASSERT((child->flags & HAMMER2_CHAIN_MODIFIED) == 0);
1342                 goto finalize;
1343         }
1344 #endif
1345
1346         /*
1347          * Make sure child is referenced before we unlock.
1348          */
1349         hammer2_chain_ref(child);
1350         spin_unlock(&above->cst.spin);
1351
1352         /*
1353          * Parent reflushed after the child has passed them by should skip
1354          * due to the modify_tid test. XXX
1355          */
1356         hammer2_chain_lock(child, HAMMER2_RESOLVE_NEVER);
1357         KKASSERT(child->above == above);
1358         KKASSERT(parent->core == above);
1359
1360         /*
1361          * The parent's blockref to the child must be deleted or updated.
1362          *
1363          * This point is not reached on successful DESTROYED optimizations
1364          * but can be reached on recursive deletions and restricted flushes.
1365          *
1366          * The chain_modify here may delete-duplicate the block.  This can
1367          * cause a multitude of issues if the block was already modified
1368          * by a later (post-flush) transaction.  Primarily blockrefs in
1369          * the later block can be out-of-date, so if the situation occurs
1370          * we can't throw away the MOVED bit on the current blocks until
1371          * the later blocks are flushed (so as to be able to regenerate all
1372          * the changes that were made).
1373          *
1374          * Because flushes are ordered we do not have to make a
1375          * modify/duplicate of indirect blocks.  That is, the flush
1376          * code does not have to kmalloc or duplicate anything.  We
1377          * can adjust the indirect block table in-place and reuse the
1378          * chain.  It IS possible that the chain has already been duplicated
1379          * or may wind up being duplicated on-the-fly by modifying code
1380          * on the frontend.  We simply use the original and ignore such
1381          * chains.  However, it does mean we can't clear the MOVED bit.
1382          *
1383          * XXX recursive deletions not optimized.
1384          */
1385
1386         switch(parent->bref.type) {
1387         case HAMMER2_BREF_TYPE_INODE:
1388                 /*
1389                  * Access the inode's block array.  However, there is no
1390                  * block array if the inode is flagged DIRECTDATA.  The
1391                  * DIRECTDATA case typicaly only occurs when a hardlink has
1392                  * been shifted up the tree and the original inode gets
1393                  * replaced with an OBJTYPE_HARDLINK placeholding inode.
1394                  */
1395                 if (parent->data &&
1396                     (parent->data->ipdata.op_flags &
1397                      HAMMER2_OPFLAG_DIRECTDATA) == 0) {
1398                         base = &parent->data->ipdata.u.blockset.blockref[0];
1399                 } else {
1400                         base = NULL;
1401                 }
1402                 count = HAMMER2_SET_COUNT;
1403                 break;
1404         case HAMMER2_BREF_TYPE_INDIRECT:
1405         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1406                 if (parent->data)
1407                         base = &parent->data->npdata[0];
1408                 else
1409                         base = NULL;
1410                 count = parent->bytes / sizeof(hammer2_blockref_t);
1411                 break;
1412         case HAMMER2_BREF_TYPE_VOLUME:
1413                 base = &hmp->voldata.sroot_blockset.blockref[0];
1414                 count = HAMMER2_SET_COUNT;
1415                 break;
1416         case HAMMER2_BREF_TYPE_FREEMAP:
1417                 base = &parent->data->npdata[0];
1418                 count = HAMMER2_SET_COUNT;
1419                 break;
1420         default:
1421                 base = NULL;
1422                 count = 0;
1423                 panic("hammer2_chain_flush_scan2: "
1424                       "unrecognized blockref type: %d",
1425                       parent->bref.type);
1426         }
1427
1428         /*
1429          * Don't bother updating a deleted + destroyed parent's blockrefs.
1430          * We MUST update deleted + non-destroyed parent's blockrefs since
1431          * they could represent an open file.
1432          *
1433          * Otherwise, we need to be COUNTEDBREFS synchronized for the
1434          * hammer2_base_*() functions.
1435          *
1436          * NOTE: We optimize this by noting that only 'inode' chains require
1437          *       this treatment.  When a file with an open descriptor is
1438          *       deleted only its inode is marked deleted.  Other deletions,
1439          *       such as indirect block deletions, will no longer be visible
1440          *       to the live filesystem and do not need to be updated.
1441          *
1442          *       rm -rf's generally wind up setting DESTROYED on the way down
1443          *       and the result is typically that no disk I/O is needed at all
1444          *       when rm -rf'ing an entire directory topology.
1445          *
1446          *       This test must match the similar one in flush_core.
1447          */
1448 #if FLUSH_DEBUG
1449         kprintf("SCAN2 base=%p pass=%d PARENT %p.%d DTID=%016jx SYNC=%016jx\n",
1450                 base,
1451                 info->pass, parent, parent->bref.type, parent->delete_tid, trans->sync_tid);
1452 #endif
1453         if (parent->delete_tid <= trans->sync_tid &&
1454             ((parent->flags & HAMMER2_CHAIN_DESTROYED) ||
1455              parent->bref.type != HAMMER2_BREF_TYPE_INODE)) {
1456                 base = NULL;
1457         }
1458
1459         /*
1460          * Update the parent's blockref table and propagate mirror_tid.
1461          *
1462          * NOTE! Children with modify_tid's beyond our flush point are
1463          *       considered to not exist for the purposes of updating the
1464          *       parent's blockref array.
1465          *
1466          * NOTE! SCAN1 has already put the parent in a modified state
1467          *       so if it isn't we panic.
1468          *
1469          * NOTE! chain->modify_tid vs chain->bref.modify_tid.  The chain's
1470          *       internal modify_tid is always updated based on creation
1471          *       or delete-duplicate.  However, the bref.modify_tid is NOT
1472          *       updated due to simple blockref updates.
1473          */
1474 #if FLUSH_DEBUG
1475         kprintf("chain %p->%p pass %d trans %016jx sync %p.%d %016jx/%d C=%016jx D=%016jx PMIRROR %016jx\n",
1476                 parent, child,
1477                 info->pass, trans->sync_tid,
1478                 child, child->bref.type,
1479                 child->bref.key, child->bref.keybits,
1480                 child->modify_tid, child->delete_tid, parent->bref.mirror_tid);
1481 #endif
1482
1483         if (info->pass == 1 && child->delete_tid <= trans->sync_tid) {
1484                 /*
1485                  * Deleting.  The block array is expected to contain the
1486                  * child's entry if:
1487                  *
1488                  * (1) The deletion occurred after the parent's block table
1489                  *     was last synchronized (delete_tid), and
1490                  *
1491                  * (2) The creation occurred before or during the parent's
1492                  *     last block table synchronization.
1493                  */
1494 #if FLUSH_DEBUG
1495                 kprintf("S2A %p b=%p d/b=%016jx/%016jx m/b=%016jx/%016jx\n",
1496                         child, base, child->delete_tid, parent->bref.mirror_tid,
1497                         child->modify_tid, parent->bref.mirror_tid);
1498 #endif
1499                 ok = 1;
1500                 if (base &&
1501                     child->delete_tid > parent->bref.mirror_tid &&
1502                     child->modify_tid <= parent->bref.mirror_tid) {
1503                         KKASSERT(child->flags & HAMMER2_CHAIN_MOVED);
1504                         KKASSERT(parent->modify_tid == trans->sync_tid ||
1505                                  (parent == &hmp->vchain ||
1506                                   parent == &hmp->fchain));
1507                         hammer2_rollup_stats(parent, child, -1);
1508                         spin_lock(&above->cst.spin);
1509 #if FLUSH_DEBUG
1510                         kprintf("trans %jx parent %p.%d child %p.%d m/d %016jx/%016jx "
1511                                 "flg=%08x %016jx/%d delete\n",
1512                                 trans->sync_tid,
1513                                 parent, parent->bref.type,
1514                                 child, child->bref.type,
1515                                 child->modify_tid, child->delete_tid,
1516                                 child->flags,
1517                                 child->bref.key, child->bref.keybits);
1518 #endif
1519                         hammer2_base_delete(parent, base, count,
1520                                             &info->cache_index, child);
1521                         spin_unlock(&above->cst.spin);
1522                 }
1523         } else if (info->pass == 2 && child->delete_tid > trans->sync_tid) {
1524                 /*
1525                  * Inserting.  The block array is expected to NOT contain
1526                  * the child's entry if:
1527                  *
1528                  * (1) The creation occurred after the parent's block table
1529                  *     was last synchronized (modify_tid), and
1530                  *
1531                  * (2) The child is not being deleted in the same
1532                  *     transaction.
1533                  */
1534                 ok = 1;
1535                 if (base &&
1536                     child->modify_tid > parent->bref.mirror_tid) {
1537                         KKASSERT(child->flags & HAMMER2_CHAIN_MOVED);
1538                         KKASSERT(parent->modify_tid == trans->sync_tid ||
1539                                  (parent == &hmp->vchain ||
1540                                   parent == &hmp->fchain));
1541                         hammer2_rollup_stats(parent, child, 1);
1542                         spin_lock(&above->cst.spin);
1543 #if FLUSH_DEBUG
1544                         kprintf("trans %jx parent %p.%d child %p.%d m/d %016jx/%016jx "
1545                                 "flg=%08x %016jx/%d insert\n",
1546                                 trans->sync_tid,
1547                                 parent, parent->bref.type,
1548                                 child, child->bref.type,
1549                                 child->modify_tid, child->delete_tid,
1550                                 child->flags,
1551                                 child->bref.key, child->bref.keybits);
1552 #endif
1553                         hammer2_base_insert(parent, base, count,
1554                                             &info->cache_index, child);
1555                         spin_unlock(&above->cst.spin);
1556                 }
1557         } else if (info->pass == 3 && (child->flags & HAMMER2_CHAIN_MOVED)) {
1558                 /*
1559                  * Only clear MOVED once all possible parents have been
1560                  * flushed.  When can we safely clear the MOVED flag?
1561                  * Flushes down duplicate paths can occur out of order,
1562                  * for example if an inode is moved as part of a hardlink
1563                  * consolidation or if an inode is moved into an indirect
1564                  * block indexed before the inode.
1565                  */
1566                 hammer2_chain_t *scan;
1567
1568                 if (hammer2_debug & 0x4000)
1569                         kprintf("CHECKMOVED %p (parent=%p)", child, parent);
1570
1571                 ok = 1;
1572                 spin_lock(&above->cst.spin);
1573                 TAILQ_FOREACH(scan, &above->ownerq, core_entry) {
1574                         /*
1575                          * Can't clear child's MOVED until all parent's have
1576                          * synchronized with it.
1577                          *
1578                          * ignore any parents which have been deleted as-of
1579                          * our transaction id (their block array doesn't get
1580                          * updated).
1581                          */
1582                         if (scan->delete_tid <= trans->sync_tid)
1583                                 continue;
1584
1585                         /*
1586                          * parent not synchronized if child modified or
1587                          * deleted after the parent's last sync point.
1588                          *
1589                          * (For the purpose of clearing the MOVED bit
1590                          *  we do not restrict the tests to just flush
1591                          *  transactions).
1592                          */
1593                         if (scan->bref.mirror_tid < child->modify_tid ||
1594                             ((child->flags & HAMMER2_CHAIN_DELETED) &&
1595                              scan->bref.mirror_tid < child->delete_tid)) {
1596                                 if (hammer2_debug & 0x4000)
1597                                         kprintf("(fail scan %p %016jx/%016jx)",
1598                                                 scan, scan->bref.mirror_tid,
1599                                                 child->modify_tid);
1600                                 ok = 0;
1601                         }
1602                 }
1603                 if (hammer2_debug & 0x4000)
1604                         kprintf("\n");
1605                 spin_unlock(&above->cst.spin);
1606
1607                 /*
1608                  * Can we finally clear MOVED?
1609                  */
1610                 if (ok) {
1611                         if (hammer2_debug & 0x4000)
1612                                 kprintf("clear moved %p.%d %016jx/%d\n",
1613                                         child, child->bref.type,
1614                                         child->bref.key, child->bref.keybits);
1615                         if (child->modify_tid <= trans->sync_tid &&
1616                             (child->delete_tid == HAMMER2_MAX_TID ||
1617                              child->delete_tid <= trans->sync_tid)) {
1618                                 atomic_clear_int(&child->flags,
1619                                                  HAMMER2_CHAIN_MOVED);
1620                                 hammer2_chain_drop(child);      /* flag */
1621                                 KKASSERT((child->flags &
1622                                                 HAMMER2_CHAIN_MODIFIED) == 0);
1623                         } else {
1624                                 kprintf("ok problem child %p %016jx/%016jx vs %016jx\n", child, child->modify_tid, child->delete_tid, trans->sync_tid);
1625                         }
1626                 } else {
1627                         if (hammer2_debug & 0x4000)
1628                                 kprintf("keep  moved %p.%d %016jx/%d\n",
1629                                         child, child->bref.type,
1630                                         child->bref.key, child->bref.keybits);
1631                 }
1632         }
1633
1634         /*
1635          * Unlock the child.  This can wind up dropping the child's
1636          * last ref, removing it from the parent's RB tree, and deallocating
1637          * the structure.  The RB_SCAN() our caller is doing handles the
1638          * situation.
1639          */
1640         hammer2_chain_unlock(child);
1641         hammer2_chain_drop(child);
1642         spin_lock(&above->cst.spin);
1643
1644         /*
1645          * The parent may have been delete-duplicated.
1646          */
1647         info->parent = parent;
1648 finalize:
1649         return (0);
1650 }
1651
1652 static
1653 void
1654 hammer2_rollup_stats(hammer2_chain_t *parent, hammer2_chain_t *child, int how)
1655 {
1656 #if 0
1657         hammer2_chain_t *grandp;
1658 #endif
1659
1660         parent->data_count += child->data_count;
1661         parent->inode_count += child->inode_count;
1662         child->data_count = 0;
1663         child->inode_count = 0;
1664         if (how < 0) {
1665                 parent->data_count -= child->bytes;
1666                 if (child->bref.type == HAMMER2_BREF_TYPE_INODE) {
1667                         parent->inode_count -= 1;
1668 #if 0
1669                         /* XXX child->data may be NULL atm */
1670                         parent->data_count -= child->data->ipdata.data_count;
1671                         parent->inode_count -= child->data->ipdata.inode_count;
1672 #endif
1673                 }
1674         } else if (how > 0) {
1675                 parent->data_count += child->bytes;
1676                 if (child->bref.type == HAMMER2_BREF_TYPE_INODE) {
1677                         parent->inode_count += 1;
1678 #if 0
1679                         /* XXX child->data may be NULL atm */
1680                         parent->data_count += child->data->ipdata.data_count;
1681                         parent->inode_count += child->data->ipdata.inode_count;
1682 #endif
1683                 }
1684         }
1685         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
1686                 parent->data->ipdata.data_count += parent->data_count;
1687                 parent->data->ipdata.inode_count += parent->inode_count;
1688 #if 0
1689                 for (grandp = parent->above->first_parent;
1690                      grandp;
1691                      grandp = grandp->next_parent) {
1692                         grandp->data_count += parent->data_count;
1693                         grandp->inode_count += parent->inode_count;
1694                 }
1695 #endif
1696                 parent->data_count = 0;
1697                 parent->inode_count = 0;
1698         }
1699 }