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