1d45feb46792db049725470f60b290df57e1b523
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2015 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  * and 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  * This subsystem implements most of the core support functions for
37  * the hammer2_chain structure.
38  *
39  * Chains are the in-memory version on media objects (volume header, inodes,
40  * indirect blocks, data blocks, etc).  Chains represent a portion of the
41  * HAMMER2 topology.
42  *
43  * Chains are no-longer delete-duplicated.  Instead, the original in-memory
44  * chain will be moved along with its block reference (e.g. for things like
45  * renames, hardlink operations, modifications, etc), and will be indexed
46  * on a secondary list for flush handling instead of propagating a flag
47  * upward to the root.
48  *
49  * Concurrent front-end operations can still run against backend flushes
50  * as long as they do not cross the current flush boundary.  An operation
51  * running above the current flush (in areas not yet flushed) can become
52  * part of the current flush while ano peration running below the current
53  * flush can become part of the next flush.
54  */
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
59 #include <sys/lock.h>
60 #include <sys/kern_syscall.h>
61 #include <sys/uuid.h>
62
63 #include <crypto/sha2/sha2.h>
64
65 #include "hammer2.h"
66
67 static hammer2_chain_t *hammer2_chain_create_indirect(
68                 hammer2_chain_t *parent,
69                 hammer2_key_t key, int keybits,
70                 hammer2_tid_t mtid, int for_type, int *errorp);
71 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain);
72 static hammer2_chain_t *hammer2_combined_find(
73                 hammer2_chain_t *parent,
74                 hammer2_blockref_t *base, int count,
75                 hammer2_key_t *key_nextp,
76                 hammer2_key_t key_beg, hammer2_key_t key_end,
77                 hammer2_blockref_t **bresp);
78
79 /*
80  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
81  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
82  * dbtree or to dbq.
83  *
84  * Chains in delete-duplicate sequences can always iterate through core_entry
85  * to locate the live version of the chain.
86  */
87 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
88
89 int
90 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
91 {
92         hammer2_key_t c1_beg;
93         hammer2_key_t c1_end;
94         hammer2_key_t c2_beg;
95         hammer2_key_t c2_end;
96
97         /*
98          * Compare chains.  Overlaps are not supposed to happen and catch
99          * any software issues early we count overlaps as a match.
100          */
101         c1_beg = chain1->bref.key;
102         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
103         c2_beg = chain2->bref.key;
104         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
105
106         if (c1_end < c2_beg)    /* fully to the left */
107                 return(-1);
108         if (c1_beg > c2_end)    /* fully to the right */
109                 return(1);
110         return(0);              /* overlap (must not cross edge boundary) */
111 }
112
113 /*
114  * Assert that a chain has no media data associated with it.
115  */
116 static __inline void
117 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
118 {
119         KKASSERT(chain->dio == NULL);
120         if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
121             chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
122             chain->data) {
123                 panic("hammer2_assert_no_data: chain %p still has data", chain);
124         }
125 }
126
127 /*
128  * Make a chain visible to the flusher.  The flusher needs to be able to
129  * do flushes of subdirectory chains or single files so it does a top-down
130  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
131  * or UPDATE chains and flushes back up the chain to the volume root.
132  *
133  * This routine sets ONFLUSH upward until it hits the volume root.  For
134  * simplicity we ignore PFSROOT boundaries whos rules can be complex.
135  * Extra ONFLUSH flagging doesn't hurt the filesystem.
136  */
137 void
138 hammer2_chain_setflush(hammer2_chain_t *chain)
139 {
140         hammer2_chain_t *parent;
141
142         if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
143                 hammer2_spin_sh(&chain->core.spin);
144                 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
146                         if ((parent = chain->parent) == NULL)
147                                 break;
148                         hammer2_spin_sh(&parent->core.spin);
149                         hammer2_spin_unsh(&chain->core.spin);
150                         chain = parent;
151                 }
152                 hammer2_spin_unsh(&chain->core.spin);
153         }
154 }
155
156 /*
157  * Allocate a new disconnected chain element representing the specified
158  * bref.  chain->refs is set to 1 and the passed bref is copied to
159  * chain->bref.  chain->bytes is derived from the bref.
160  *
161  * chain->pmp inherits pmp unless the chain is an inode (other than the
162  * super-root inode).
163  *
164  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
165  */
166 hammer2_chain_t *
167 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
168                     hammer2_blockref_t *bref)
169 {
170         hammer2_chain_t *chain;
171         u_int bytes;
172
173         /*
174          * Special case - radix of 0 indicates a chain that does not
175          * need a data reference (context is completely embedded in the
176          * bref).
177          */
178         if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
179                 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
180         else
181                 bytes = 0;
182
183         atomic_add_long(&hammer2_chain_allocs, 1);
184
185         /*
186          * Construct the appropriate system structure.
187          */
188         switch(bref->type) {
189         case HAMMER2_BREF_TYPE_DIRENT:
190         case HAMMER2_BREF_TYPE_INODE:
191         case HAMMER2_BREF_TYPE_INDIRECT:
192         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
193         case HAMMER2_BREF_TYPE_DATA:
194         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
195                 /*
196                  * Chain's are really only associated with the hmp but we
197                  * maintain a pmp association for per-mount memory tracking
198                  * purposes.  The pmp can be NULL.
199                  */
200                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
201                 break;
202         case HAMMER2_BREF_TYPE_VOLUME:
203         case HAMMER2_BREF_TYPE_FREEMAP:
204                 /*
205                  * Only hammer2_chain_bulksnap() calls this function with these
206                  * types.
207                  */
208                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
209                 break;
210         default:
211                 chain = NULL;
212                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
213                       bref->type);
214         }
215
216         /*
217          * Initialize the new chain structure.  pmp must be set to NULL for
218          * chains belonging to the super-root topology of a device mount.
219          */
220         if (pmp == hmp->spmp)
221                 chain->pmp = NULL;
222         else
223                 chain->pmp = pmp;
224         chain->hmp = hmp;
225         chain->bref = *bref;
226         chain->bytes = bytes;
227         chain->refs = 1;
228         chain->flags = HAMMER2_CHAIN_ALLOCATED;
229
230         /*
231          * Set the PFS boundary flag if this chain represents a PFS root.
232          */
233         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
234                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
235         hammer2_chain_core_init(chain);
236
237         return (chain);
238 }
239
240 /*
241  * Initialize a chain's core structure.  This structure used to be allocated
242  * but is now embedded.
243  *
244  * The core is not locked.  No additional refs on the chain are made.
245  * (trans) must not be NULL if (core) is not NULL.
246  */
247 void
248 hammer2_chain_core_init(hammer2_chain_t *chain)
249 {
250         /*
251          * Fresh core under nchain (no multi-homing of ochain's
252          * sub-tree).
253          */
254         RB_INIT(&chain->core.rbtree);   /* live chains */
255         hammer2_mtx_init(&chain->lock, "h2chain");
256 }
257
258 /*
259  * Add a reference to a chain element, preventing its destruction.
260  *
261  * (can be called with spinlock held)
262  */
263 void
264 hammer2_chain_ref(hammer2_chain_t *chain)
265 {
266         if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
267                 /*
268                  * 0->non-zero transition must ensure that chain is removed
269                  * from the LRU list.
270                  *
271                  * NOTE: Already holding lru_spin here so we cannot call
272                  *       hammer2_chain_ref() to get it off lru_list, do
273                  *       it manually.
274                  */
275                 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
276                         hammer2_pfs_t *pmp = chain->pmp;
277                         hammer2_spin_ex(&pmp->lru_spin);
278                         if (chain->flags & HAMMER2_CHAIN_ONLRU) {
279                                 atomic_add_int(&pmp->lru_count, -1);
280                                 atomic_clear_int(&chain->flags,
281                                                  HAMMER2_CHAIN_ONLRU);
282                                 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
283                         }
284                         hammer2_spin_unex(&pmp->lru_spin);
285                 }
286         }
287 #if 0
288         kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
289         print_backtrace(8);
290 #endif
291 }
292
293 /*
294  * Ref a locked chain and force the data to be held across an unlock.
295  * Chain must be currently locked.  The user of the chain who desires
296  * to release the hold must call hammer2_chain_lock_unhold() to relock
297  * and unhold the chain, then unlock normally, or may simply call
298  * hammer2_chain_drop_unhold() (which is safer against deadlocks).
299  */
300 void
301 hammer2_chain_ref_hold(hammer2_chain_t *chain)
302 {
303         atomic_add_int(&chain->lockcnt, 1);
304         hammer2_chain_ref(chain);
305 }
306
307 /*
308  * Insert the chain in the core rbtree.
309  *
310  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
311  * chain is a special case used by the flush code that is placed on the
312  * unstaged deleted list to avoid confusing the live view.
313  */
314 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
315 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
316 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
317
318 static
319 int
320 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
321                      int flags, int generation)
322 {
323         hammer2_chain_t *xchain;
324         int error = 0;
325
326         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
327                 hammer2_spin_ex(&parent->core.spin);
328
329         /*
330          * Interlocked by spinlock, check for race
331          */
332         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
333             parent->core.generation != generation) {
334                 error = EAGAIN;
335                 goto failed;
336         }
337
338         /*
339          * Insert chain
340          */
341         xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
342         KASSERT(xchain == NULL,
343                 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
344                 chain, xchain, chain->bref.key));
345         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
346         chain->parent = parent;
347         ++parent->core.chain_count;
348         ++parent->core.generation;      /* XXX incs for _get() too, XXX */
349
350         /*
351          * We have to keep track of the effective live-view blockref count
352          * so the create code knows when to push an indirect block.
353          */
354         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
355                 atomic_add_int(&parent->core.live_count, 1);
356 failed:
357         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
358                 hammer2_spin_unex(&parent->core.spin);
359         return error;
360 }
361
362 /*
363  * Drop the caller's reference to the chain.  When the ref count drops to
364  * zero this function will try to disassociate the chain from its parent and
365  * deallocate it, then recursely drop the parent using the implied ref
366  * from the chain's chain->parent.
367  *
368  * Nobody should own chain's mutex on the 1->0 transition, unless this drop
369  * races an acquisition by another cpu.  Therefore we can loop if we are
370  * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
371  * race against another drop.
372  */
373 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
374
375 void
376 hammer2_chain_drop(hammer2_chain_t *chain)
377 {
378         u_int refs;
379
380         if (hammer2_debug & 0x200000)
381                 Debugger("drop");
382 #if 0
383         kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
384         print_backtrace(8);
385 #endif
386
387         KKASSERT(chain->refs > 0);
388
389         while (chain) {
390                 refs = chain->refs;
391                 cpu_ccfence();
392                 KKASSERT(refs > 0);
393
394                 if (refs == 1) {
395                         if (mtx_lock_ex_try(&chain->lock) == 0)
396                                 chain = hammer2_chain_lastdrop(chain);
397                         /* retry the same chain */
398                 } else {
399                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
400                                 break;
401                         /* retry the same chain */
402                 }
403                 cpu_pause();
404         }
405 }
406
407 /*
408  * Unhold a held and probably not-locked chain, ensure that the data is
409  * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
410  * lock and then simply unlocking the chain.
411  */
412 void
413 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
414 {
415         u_int lockcnt;
416         int iter = 0;
417
418         for (;;) {
419                 lockcnt = chain->lockcnt;
420                 cpu_ccfence();
421                 if (lockcnt > 1) {
422                         if (atomic_cmpset_int(&chain->lockcnt,
423                                               lockcnt, lockcnt - 1)) {
424                                 break;
425                         }
426                 } else if (mtx_lock_ex_try(&chain->lock) == 0) {
427                         hammer2_chain_unlock(chain);
428                         break;
429                 } else {
430                         /*
431                          * This situation can easily occur on SMP due to
432                          * the gap inbetween the 1->0 transition and the
433                          * final unlock.  We cannot safely block on the
434                          * mutex because lockcnt might go above 1.
435                          *
436                          * XXX Sleep for one tick if it takes too long.
437                          */
438                         if (++iter > 1000) {
439                                 if (iter > 1000 + hz) {
440                                         kprintf("hammer2: h2race1 %p\n", chain);
441                                         iter = 1000;
442                                 }
443                                 tsleep(&iter, 0, "h2race1", 1);
444                         }
445                         cpu_pause();
446                 }
447         }
448         hammer2_chain_drop(chain);
449 }
450
451 /*
452  * Handles the (potential) last drop of chain->refs from 1->0.  Called with
453  * the mutex exclusively locked, refs == 1, and lockcnt 0.  SMP races are
454  * possible against refs and lockcnt.  We must dispose of the mutex on chain.
455  *
456  * This function returns an unlocked chain for recursive drop or NULL.  It
457  * can return the same chain if it determines it has raced another ref.
458  *
459  * --
460  *
461  * When two chains need to be recursively dropped we use the chain we
462  * would otherwise free to placehold the additional chain.  It's a bit
463  * convoluted but we can't just recurse without potentially blowing out
464  * the kernel stack.
465  *
466  * The chain cannot be freed if it has any children.
467  * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
468  * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
469  * Any dedup registration can remain intact.
470  *
471  * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
472  */
473 static
474 hammer2_chain_t *
475 hammer2_chain_lastdrop(hammer2_chain_t *chain)
476 {
477         hammer2_pfs_t *pmp;
478         hammer2_dev_t *hmp;
479         hammer2_chain_t *parent;
480         hammer2_chain_t *rdrop;
481 #if 0
482         hammer2_io_t *dio;
483 #endif
484
485 #if 0
486         /*
487          * On last drop if there is no parent and data_off is good (at
488          * least does not represent the volume root), the modified chain
489          * is probably going to be destroyed.  We have to make sure that
490          * the data area is not registered for dedup.
491          *
492          * XXX removed. In fact, we do not have to make sure that the
493          *     data area is not registered for dedup.  The data area
494          *     can, in fact, still be used for dedup because it is
495          *     still allocated in the freemap and the underlying I/O
496          *     will still be flushed.
497          */
498         if (chain->parent == NULL &&
499             (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
500             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
501                 hmp = chain->hmp;
502                 hammer2_io_dedup_delete(hmp, chain->bref.type,
503                                         chain->bref.data_off, chain->bytes);
504         }
505 #endif
506         /*
507          * We need chain's spinlock to interlock the sub-tree test.
508          * We already have chain's mutex, protecting chain->parent.
509          *
510          * Remember that chain->refs can be in flux.
511          */
512         hammer2_spin_ex(&chain->core.spin);
513
514         if ((parent = chain->parent) != NULL) {
515                 /*
516                  * If the chain has a parent the UPDATE bit prevents scrapping
517                  * as the chain is needed to properly flush the parent.  Try
518                  * to complete the 1->0 transition and return NULL.  Retry
519                  * (return chain) if we are unable to complete the 1->0
520                  * transition, else return NULL (nothing more to do).
521                  *
522                  * If the chain has a parent the MODIFIED bit prevents
523                  * scrapping.
524                  *
525                  * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
526                  */
527                 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
528                                     HAMMER2_CHAIN_MODIFIED)) {
529                         if (atomic_cmpset_int(&chain->refs, 1, 0)) {
530                                 hammer2_spin_unex(&chain->core.spin);
531 #if 0
532                                 dio = hammer2_chain_drop_data(chain, 0);
533                                 if (dio)
534                                         hammer2_io_bqrelse(&dio);
535 #endif
536                                 hammer2_chain_assert_no_data(chain);
537                                 hammer2_mtx_unlock(&chain->lock);
538                                 chain = NULL;
539                         } else {
540                                 hammer2_spin_unex(&chain->core.spin);
541                                 hammer2_mtx_unlock(&chain->lock);
542                         }
543                         return (chain);
544                 }
545                 /* spinlock still held */
546         } else {
547                 /*
548                  * The chain has no parent and can be flagged for destruction.
549                  * Since it has no parent, UPDATE can also be cleared.
550                  */
551                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
552                 if (chain->flags & HAMMER2_CHAIN_UPDATE)
553                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
554
555                 /*
556                  * If the chain has children we must still flush the chain.
557                  * Any dedup is already handled by the underlying DIO, so
558                  * we do not have to specifically flush it here.
559                  *
560                  * In the case where it has children, the DESTROY flag test
561                  * in the flush code will prevent unnecessary flushes of
562                  * MODIFIED chains that are not flagged DEDUP so don't worry
563                  * about that here.
564                  */
565                 if (chain->core.chain_count) {
566                         /*
567                          * Put on flushq (should ensure refs > 1), retry
568                          * the drop.
569                          */
570                         hammer2_spin_unex(&chain->core.spin);
571                         hammer2_delayed_flush(chain);
572                         hammer2_mtx_unlock(&chain->lock);
573
574                         return(chain);  /* retry drop */
575                 }
576
577                 /*
578                  * Otherwise we can scrap the MODIFIED bit if it is set,
579                  * and continue along the freeing path.
580                  *
581                  * Be sure to clean-out any dedup bits.  Without a parent
582                  * this chain will no longer be visible to the flush code.
583                  * Easy check data_off to avoid the volume root.
584                  */
585                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
586                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
587                         atomic_add_long(&hammer2_count_modified_chains, -1);
588                         if (chain->pmp)
589                                 hammer2_pfs_memory_wakeup(chain->pmp);
590                 }
591                 /* spinlock still held */
592         }
593
594         /* spinlock still held */
595 #if 0
596         dio = NULL;
597 #endif
598
599         /*
600          * If any children exist we must leave the chain intact with refs == 0.
601          * They exist because chains are retained below us which have refs or
602          * may require flushing.
603          *
604          * Retry (return chain) if we fail to transition the refs to 0, else
605          * return NULL indication nothing more to do.
606          *
607          * Chains with children are NOT put on the LRU list.
608          */
609         if (chain->core.chain_count) {
610                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
611                         hammer2_spin_unex(&chain->core.spin);
612                         hammer2_chain_assert_no_data(chain);
613                         hammer2_mtx_unlock(&chain->lock);
614                         chain = NULL;
615                 } else {
616                         hammer2_spin_unex(&chain->core.spin);
617                         hammer2_mtx_unlock(&chain->lock);
618                 }
619                 return (chain);
620         }
621         /* spinlock still held */
622         /* no chains left under us */
623
624         /*
625          * chain->core has no children left so no accessors can get to our
626          * chain from there.  Now we have to lock the parent core to interlock
627          * remaining possible accessors that might bump chain's refs before
628          * we can safely drop chain's refs with intent to free the chain.
629          */
630         hmp = chain->hmp;
631         pmp = chain->pmp;       /* can be NULL */
632         rdrop = NULL;
633
634         parent = chain->parent;
635
636         /*
637          * WARNING! chain's spin lock is still held here, and other spinlocks
638          *          will be acquired and released in the code below.  We
639          *          cannot be making fancy procedure calls!
640          */
641
642         /*
643          * We can cache the chain if it is associated with a pmp
644          * and not flagged as being destroyed or requesting a full
645          * release.  In this situation the chain is not removed
646          * from its parent, i.e. it can still be looked up.
647          *
648          * We intentionally do not cache DATA chains because these
649          * were likely used to load data into the logical buffer cache
650          * and will not be accessed again for some time.
651          */
652         if ((chain->flags &
653              (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
654             chain->pmp &&
655             chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
656                 if (parent)
657                         hammer2_spin_ex(&parent->core.spin);
658                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
659                         /*
660                          * 1->0 transition failed, retry.  Do not drop
661                          * the chain's data yet!
662                          */
663                         if (parent)
664                                 hammer2_spin_unex(&parent->core.spin);
665                         hammer2_spin_unex(&chain->core.spin);
666                         hammer2_mtx_unlock(&chain->lock);
667
668                         return(chain);
669                 }
670
671                 /*
672                  * Success
673                  */
674 #if 0
675                 dio = hammer2_chain_drop_data(chain, 1);
676 #endif
677                 hammer2_chain_assert_no_data(chain);
678
679                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
680                 hammer2_spin_ex(&pmp->lru_spin);
681                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
682                 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
683
684                 /*
685                  * If we are over the LRU limit we need to drop something.
686                  */
687                 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
688                         rdrop = TAILQ_FIRST(&pmp->lru_list);
689                         atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
690                         TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
691                         atomic_add_int(&rdrop->refs, 1);
692                         atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
693                 } else {
694                         atomic_add_int(&pmp->lru_count, 1);
695                 }
696                 hammer2_spin_unex(&pmp->lru_spin);
697                 if (parent) {
698                         hammer2_spin_unex(&parent->core.spin);
699                         parent = NULL;  /* safety */
700                 }
701                 hammer2_spin_unex(&chain->core.spin);
702                 hammer2_mtx_unlock(&chain->lock);
703 #if 0
704                 if (dio)
705                         hammer2_io_bqrelse(&dio);
706 #endif
707
708                 return rdrop;
709                 /* NOT REACHED */
710         }
711
712         /*
713          * Spinlock the parent and try to drop the last ref on chain.
714          * On success determine if we should dispose of the chain
715          * (remove the chain from its parent, etc).
716          *
717          * (normal core locks are top-down recursive but we define
718          * core spinlocks as bottom-up recursive, so this is safe).
719          */
720         if (parent) {
721                 hammer2_spin_ex(&parent->core.spin);
722                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
723 #if 0
724                         /* XXX remove, don't try to drop data on fail */
725                         hammer2_spin_unex(&parent->core.spin);
726                         dio = hammer2_chain_drop_data(chain, 0);
727                         hammer2_spin_unex(&chain->core.spin);
728                         if (dio)
729                                 hammer2_io_bqrelse(&dio);
730 #endif
731                         /*
732                          * 1->0 transition failed, retry.
733                          */
734                         hammer2_spin_unex(&parent->core.spin);
735                         hammer2_spin_unex(&chain->core.spin);
736                         hammer2_mtx_unlock(&chain->lock);
737
738                         return(chain);
739                 }
740
741                 /*
742                  * 1->0 transition successful, parent spin held to prevent
743                  * new lookups, chain spinlock held to protect parent field.
744                  * Remove chain from the parent.
745                  */
746                 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
747                         RB_REMOVE(hammer2_chain_tree,
748                                   &parent->core.rbtree, chain);
749                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
750                         --parent->core.chain_count;
751                         chain->parent = NULL;
752                 }
753
754                 /*
755                  * If our chain was the last chain in the parent's core the
756                  * core is now empty and its parent might have to be
757                  * re-dropped if it has 0 refs.
758                  */
759                 if (parent->core.chain_count == 0) {
760                         rdrop = parent;
761                         atomic_add_int(&rdrop->refs, 1);
762                         /*
763                         if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
764                                 rdrop = NULL;
765                         */
766                 }
767                 hammer2_spin_unex(&parent->core.spin);
768                 parent = NULL;  /* safety */
769                 /* FALL THROUGH */
770         } else {
771                 /*
772                  * No-parent case.
773                  */
774                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
775                         /*
776                          * 1->0 transition failed, retry.
777                          */
778                         hammer2_spin_unex(&parent->core.spin);
779                         hammer2_spin_unex(&chain->core.spin);
780                         hammer2_mtx_unlock(&chain->lock);
781
782                         return(chain);
783                 }
784         }
785
786         /*
787          * Successful 1->0 transition, no parent, no children... no way for
788          * anyone to ref this chain any more.  We can clean-up and free it.
789          *
790          * We still have the core spinlock, and core's chain_count is 0.
791          * Any parent spinlock is gone.
792          */
793         hammer2_spin_unex(&chain->core.spin);
794         hammer2_chain_assert_no_data(chain);
795         hammer2_mtx_unlock(&chain->lock);
796         KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
797                  chain->core.chain_count == 0);
798
799         /*
800          * All locks are gone, no pointers remain to the chain, finish
801          * freeing it.
802          */
803         KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
804                                   HAMMER2_CHAIN_MODIFIED)) == 0);
805 #if 0
806         dio = hammer2_chain_drop_data(chain, 1);
807         if (dio)
808                 hammer2_io_bqrelse(&dio);
809 #endif
810
811         /*
812          * Once chain resources are gone we can use the now dead chain
813          * structure to placehold what might otherwise require a recursive
814          * drop, because we have potentially two things to drop and can only
815          * return one directly.
816          */
817         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
818                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
819                 chain->hmp = NULL;
820                 kfree(chain, hmp->mchain);
821         }
822
823         /*
824          * Possible chaining loop when parent re-drop needed.
825          */
826         return(rdrop);
827 }
828
829 /*
830  * On last lock release.
831  */
832 static hammer2_io_t *
833 hammer2_chain_drop_data(hammer2_chain_t *chain)
834 {
835         hammer2_io_t *dio;
836
837         if ((dio = chain->dio) != NULL) {
838                 chain->dio = NULL;
839                 chain->data = NULL;
840         } else {
841                 switch(chain->bref.type) {
842                 case HAMMER2_BREF_TYPE_VOLUME:
843                 case HAMMER2_BREF_TYPE_FREEMAP:
844                         break;
845                 default:
846                         if (chain->data != NULL) {
847                                 hammer2_spin_unex(&chain->core.spin);
848                                 panic("chain data not null: "
849                                       "chain %p bref %016jx.%02x "
850                                       "refs %d parent %p dio %p data %p",
851                                       chain, chain->bref.data_off,
852                                       chain->bref.type, chain->refs,
853                                       chain->parent,
854                                       chain->dio, chain->data);
855                         }
856                         KKASSERT(chain->data == NULL);
857                         break;
858                 }
859         }
860         return dio;
861 }
862
863 /*
864  * Lock a referenced chain element, acquiring its data with I/O if necessary,
865  * and specify how you would like the data to be resolved.
866  *
867  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
868  *
869  * The lock is allowed to recurse, multiple locking ops will aggregate
870  * the requested resolve types.  Once data is assigned it will not be
871  * removed until the last unlock.
872  *
873  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
874  *                         (typically used to avoid device/logical buffer
875  *                          aliasing for data)
876  *
877  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
878  *                         the INITIAL-create state (indirect blocks only).
879  *
880  *                         Do not resolve data elements for DATA chains.
881  *                         (typically used to avoid device/logical buffer
882  *                          aliasing for data)
883  *
884  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
885  *
886  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
887  *                         it will be locked exclusive.
888  *
889  * NOTE: Embedded elements (volume header, inodes) are always resolved
890  *       regardless.
891  *
892  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
893  *       element will instantiate and zero its buffer, and flush it on
894  *       release.
895  *
896  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
897  *       so as not to instantiate a device buffer, which could alias against
898  *       a logical file buffer.  However, if ALWAYS is specified the
899  *       device buffer will be instantiated anyway.
900  *
901  * WARNING! This function blocks on I/O if data needs to be fetched.  This
902  *          blocking can run concurrent with other compatible lock holders
903  *          who do not need data returning.  The lock is not upgraded to
904  *          exclusive during a data fetch, a separate bit is used to
905  *          interlock I/O.  However, an exclusive lock holder can still count
906  *          on being interlocked against an I/O fetch managed by a shared
907  *          lock holder.
908  */
909 void
910 hammer2_chain_lock(hammer2_chain_t *chain, int how)
911 {
912         /*
913          * Ref and lock the element.  Recursive locks are allowed.
914          */
915         KKASSERT(chain->refs > 0);
916         atomic_add_int(&chain->lockcnt, 1);
917
918         /*
919          * Get the appropriate lock.  If LOCKAGAIN is flagged with SHARED
920          * the caller expects a shared lock to already be present and we
921          * are giving it another ref.  This case must importantly not block
922          * if there is a pending exclusive lock request.
923          */
924         if (how & HAMMER2_RESOLVE_SHARED) {
925                 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
926                         hammer2_mtx_sh_again(&chain->lock);
927                 } else {
928                         hammer2_mtx_sh(&chain->lock);
929                 }
930         } else {
931                 hammer2_mtx_ex(&chain->lock);
932         }
933         ++curthread->td_tracker;
934
935         /*
936          * If we already have a valid data pointer no further action is
937          * necessary.
938          */
939         if (chain->data)
940                 return;
941
942         /*
943          * Do we have to resolve the data?  This is generally only
944          * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
945          * Other BREF types expects the data to be there.
946          */
947         switch(how & HAMMER2_RESOLVE_MASK) {
948         case HAMMER2_RESOLVE_NEVER:
949                 return;
950         case HAMMER2_RESOLVE_MAYBE:
951                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
952                         return;
953                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
954                         return;
955 #if 0
956                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
957                         return;
958                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
959                         return;
960 #endif
961                 /* fall through */
962         case HAMMER2_RESOLVE_ALWAYS:
963         default:
964                 break;
965         }
966
967         /*
968          * Caller requires data
969          */
970         hammer2_chain_load_data(chain);
971 }
972
973 /*
974  * Lock the chain, retain the hold, and drop the data persistence count.
975  * The data should remain valid because we never transitioned lockcnt
976  * through 0.
977  */
978 void
979 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
980 {
981         hammer2_chain_lock(chain, how);
982         atomic_add_int(&chain->lockcnt, -1);
983 }
984
985 #if 0
986 /*
987  * Downgrade an exclusive chain lock to a shared chain lock.
988  *
989  * NOTE: There is no upgrade equivalent due to the ease of
990  *       deadlocks in that direction.
991  */
992 void
993 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
994 {
995         hammer2_mtx_downgrade(&chain->lock);
996 }
997 #endif
998
999 #if 0
1000 /*
1001  * Obtains a second shared lock on the chain, does not account the second
1002  * shared lock as being owned by the current thread.
1003  *
1004  * Caller must already own a shared lock on this chain.
1005  *
1006  * The lock function is required to obtain the second shared lock without
1007  * blocking on pending exclusive requests.
1008  */
1009 void
1010 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
1011 {
1012         hammer2_mtx_sh_again(&chain->lock);
1013         atomic_add_int(&chain->lockcnt, 1);
1014         /* do not count in td_tracker for this thread */
1015 }
1016
1017 /*
1018  * Accounts for a shared lock that was pushed to us as being owned by our
1019  * thread.
1020  */
1021 void
1022 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
1023 {
1024         ++curthread->td_tracker;
1025 }
1026 #endif
1027
1028 /*
1029  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
1030  * may be of any type.
1031  *
1032  * Once chain->data is set it cannot be disposed of until all locks are
1033  * released.
1034  */
1035 void
1036 hammer2_chain_load_data(hammer2_chain_t *chain)
1037 {
1038         hammer2_blockref_t *bref;
1039         hammer2_dev_t *hmp;
1040         hammer2_io_t *dio;
1041         char *bdata;
1042         int error;
1043
1044         /*
1045          * Degenerate case, data already present, or chain is not expected
1046          * to have any data.
1047          */
1048         if (chain->data)
1049                 return;
1050         if ((chain->bref.data_off & HAMMER2_OFF_MASK_RADIX) == 0)
1051                 return;
1052
1053         hmp = chain->hmp;
1054         KKASSERT(hmp != NULL);
1055
1056         /*
1057          * Gain the IOINPROG bit, interlocked block.
1058          */
1059         for (;;) {
1060                 u_int oflags;
1061                 u_int nflags;
1062
1063                 oflags = chain->flags;
1064                 cpu_ccfence();
1065                 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1066                         nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1067                         tsleep_interlock(&chain->flags, 0);
1068                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1069                                 tsleep(&chain->flags, PINTERLOCKED,
1070                                         "h2iocw", 0);
1071                         }
1072                         /* retry */
1073                 } else {
1074                         nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1075                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1076                                 break;
1077                         }
1078                         /* retry */
1079                 }
1080         }
1081
1082         /*
1083          * We own CHAIN_IOINPROG
1084          *
1085          * Degenerate case if we raced another load.
1086          */
1087         if (chain->data)
1088                 goto done;
1089
1090         /*
1091          * We must resolve to a device buffer, either by issuing I/O or
1092          * by creating a zero-fill element.  We do not mark the buffer
1093          * dirty when creating a zero-fill element (the hammer2_chain_modify()
1094          * API must still be used to do that).
1095          *
1096          * The device buffer is variable-sized in powers of 2 down
1097          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
1098          * chunk always contains buffers of the same size. (XXX)
1099          *
1100          * The minimum physical IO size may be larger than the variable
1101          * block size.
1102          */
1103         bref = &chain->bref;
1104
1105         /*
1106          * The getblk() optimization can only be used on newly created
1107          * elements if the physical block size matches the request.
1108          */
1109         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1110                 error = hammer2_io_new(hmp, bref->type,
1111                                        bref->data_off, chain->bytes,
1112                                        &chain->dio);
1113         } else {
1114                 error = hammer2_io_bread(hmp, bref->type,
1115                                          bref->data_off, chain->bytes,
1116                                          &chain->dio);
1117                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1118         }
1119         if (error) {
1120                 chain->error = HAMMER2_ERROR_IO;
1121                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1122                         (intmax_t)bref->data_off, error);
1123                 hammer2_io_bqrelse(&chain->dio);
1124                 goto done;
1125         }
1126         chain->error = 0;
1127
1128         /*
1129          * This isn't perfect and can be ignored on OSs which do not have
1130          * an indication as to whether a buffer is coming from cache or
1131          * if I/O was actually issued for the read.  TESTEDGOOD will work
1132          * pretty well without the B_IOISSUED logic because chains are
1133          * cached, but in that situation (without B_IOISSUED) it will not
1134          * detect whether a re-read via I/O is corrupted verses the original
1135          * read.
1136          *
1137          * We can't re-run the CRC on every fresh lock.  That would be
1138          * insanely expensive.
1139          *
1140          * If the underlying kernel buffer covers the entire chain we can
1141          * use the B_IOISSUED indication to determine if we have to re-run
1142          * the CRC on chain data for chains that managed to stay cached
1143          * across the kernel disposal of the original buffer.
1144          */
1145         if ((dio = chain->dio) != NULL && dio->bp) {
1146                 struct buf *bp = dio->bp;
1147
1148                 if (dio->psize == chain->bytes &&
1149                     (bp->b_flags & B_IOISSUED)) {
1150                         atomic_clear_int(&chain->flags,
1151                                          HAMMER2_CHAIN_TESTEDGOOD);
1152                         bp->b_flags &= ~B_IOISSUED;
1153                 }
1154         }
1155
1156         /*
1157          * NOTE: A locked chain's data cannot be modified without first
1158          *       calling hammer2_chain_modify().
1159          */
1160
1161         /*
1162          * Clear INITIAL.  In this case we used io_new() and the buffer has
1163          * been zero'd and marked dirty.
1164          */
1165         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1166
1167         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1168                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1169                 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1170         } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1171                 /*
1172                  * check data not currently synchronized due to
1173                  * modification.  XXX assumes data stays in the buffer
1174                  * cache, which might not be true (need biodep on flush
1175                  * to calculate crc?  or simple crc?).
1176                  */
1177         } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1178                 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1179                         chain->error = HAMMER2_ERROR_CHECK;
1180                 } else {
1181                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1182                 }
1183         }
1184
1185         /*
1186          * Setup the data pointer, either pointing it to an embedded data
1187          * structure and copying the data from the buffer, or pointing it
1188          * into the buffer.
1189          *
1190          * The buffer is not retained when copying to an embedded data
1191          * structure in order to avoid potential deadlocks or recursions
1192          * on the same physical buffer.
1193          *
1194          * WARNING! Other threads can start using the data the instant we
1195          *          set chain->data non-NULL.
1196          */
1197         switch (bref->type) {
1198         case HAMMER2_BREF_TYPE_VOLUME:
1199         case HAMMER2_BREF_TYPE_FREEMAP:
1200                 /*
1201                  * Copy data from bp to embedded buffer
1202                  */
1203                 panic("hammer2_chain_load_data: unresolved volume header");
1204                 break;
1205         case HAMMER2_BREF_TYPE_DIRENT:
1206                 KKASSERT(chain->bytes != 0);
1207                 /* fall through */
1208         case HAMMER2_BREF_TYPE_INODE:
1209         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1210         case HAMMER2_BREF_TYPE_INDIRECT:
1211         case HAMMER2_BREF_TYPE_DATA:
1212         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1213         default:
1214                 /*
1215                  * Point data at the device buffer and leave dio intact.
1216                  */
1217                 chain->data = (void *)bdata;
1218                 break;
1219         }
1220
1221         /*
1222          * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1223          */
1224 done:
1225         for (;;) {
1226                 u_int oflags;
1227                 u_int nflags;
1228
1229                 oflags = chain->flags;
1230                 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1231                                     HAMMER2_CHAIN_IOSIGNAL);
1232                 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1233                 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1234                         if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1235                                 wakeup(&chain->flags);
1236                         break;
1237                 }
1238         }
1239 }
1240
1241 /*
1242  * Unlock and deref a chain element.
1243  *
1244  * Remember that the presence of children under chain prevent the chain's
1245  * destruction but do not add additional references, so the dio will still
1246  * be dropped.
1247  */
1248 void
1249 hammer2_chain_unlock(hammer2_chain_t *chain)
1250 {
1251         hammer2_io_t *dio;
1252         u_int lockcnt;
1253         int iter = 0;
1254
1255         --curthread->td_tracker;
1256
1257         /*
1258          * If multiple locks are present (or being attempted) on this
1259          * particular chain we can just unlock, drop refs, and return.
1260          *
1261          * Otherwise fall-through on the 1->0 transition.
1262          */
1263         for (;;) {
1264                 lockcnt = chain->lockcnt;
1265                 KKASSERT(lockcnt > 0);
1266                 cpu_ccfence();
1267                 if (lockcnt > 1) {
1268                         if (atomic_cmpset_int(&chain->lockcnt,
1269                                               lockcnt, lockcnt - 1)) {
1270                                 hammer2_mtx_unlock(&chain->lock);
1271                                 return;
1272                         }
1273                 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1274                         /* while holding the mutex exclusively */
1275                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1276                                 break;
1277                 } else {
1278                         /*
1279                          * This situation can easily occur on SMP due to
1280                          * the gap inbetween the 1->0 transition and the
1281                          * final unlock.  We cannot safely block on the
1282                          * mutex because lockcnt might go above 1.
1283                          *
1284                          * XXX Sleep for one tick if it takes too long.
1285                          */
1286                         if (++iter > 1000) {
1287                                 if (iter > 1000 + hz) {
1288                                         kprintf("hammer2: h2race2 %p\n", chain);
1289                                         iter = 1000;
1290                                 }
1291                                 tsleep(&iter, 0, "h2race2", 1);
1292                         }
1293                         cpu_pause();
1294                 }
1295                 /* retry */
1296         }
1297
1298         /*
1299          * Last unlock / mutex upgraded to exclusive.  Drop the data
1300          * reference.
1301          */
1302         dio = hammer2_chain_drop_data(chain);
1303         if (dio)
1304                 hammer2_io_bqrelse(&dio);
1305         hammer2_mtx_unlock(&chain->lock);
1306 }
1307
1308 /*
1309  * Unlock and hold chain data intact
1310  */
1311 void
1312 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1313 {
1314         atomic_add_int(&chain->lockcnt, 1);
1315         hammer2_chain_unlock(chain);
1316 }
1317
1318 /*
1319  * Helper to obtain the blockref[] array base and count for a chain.
1320  *
1321  * XXX Not widely used yet, various use cases need to be validated and
1322  *     converted to use this function.
1323  */
1324 static
1325 hammer2_blockref_t *
1326 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1327 {
1328         hammer2_blockref_t *base;
1329         int count;
1330
1331         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1332                 base = NULL;
1333
1334                 switch(parent->bref.type) {
1335                 case HAMMER2_BREF_TYPE_INODE:
1336                         count = HAMMER2_SET_COUNT;
1337                         break;
1338                 case HAMMER2_BREF_TYPE_INDIRECT:
1339                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1340                         count = parent->bytes / sizeof(hammer2_blockref_t);
1341                         break;
1342                 case HAMMER2_BREF_TYPE_VOLUME:
1343                         count = HAMMER2_SET_COUNT;
1344                         break;
1345                 case HAMMER2_BREF_TYPE_FREEMAP:
1346                         count = HAMMER2_SET_COUNT;
1347                         break;
1348                 default:
1349                         panic("hammer2_chain_create_indirect: "
1350                               "unrecognized blockref type: %d",
1351                               parent->bref.type);
1352                         count = 0;
1353                         break;
1354                 }
1355         } else {
1356                 switch(parent->bref.type) {
1357                 case HAMMER2_BREF_TYPE_INODE:
1358                         base = &parent->data->ipdata.u.blockset.blockref[0];
1359                         count = HAMMER2_SET_COUNT;
1360                         break;
1361                 case HAMMER2_BREF_TYPE_INDIRECT:
1362                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1363                         base = &parent->data->npdata[0];
1364                         count = parent->bytes / sizeof(hammer2_blockref_t);
1365                         break;
1366                 case HAMMER2_BREF_TYPE_VOLUME:
1367                         base = &parent->data->voldata.
1368                                         sroot_blockset.blockref[0];
1369                         count = HAMMER2_SET_COUNT;
1370                         break;
1371                 case HAMMER2_BREF_TYPE_FREEMAP:
1372                         base = &parent->data->blkset.blockref[0];
1373                         count = HAMMER2_SET_COUNT;
1374                         break;
1375                 default:
1376                         panic("hammer2_chain_create_indirect: "
1377                               "unrecognized blockref type: %d",
1378                               parent->bref.type);
1379                         count = 0;
1380                         break;
1381                 }
1382         }
1383         *countp = count;
1384
1385         return base;
1386 }
1387
1388 /*
1389  * This counts the number of live blockrefs in a block array and
1390  * also calculates the point at which all remaining blockrefs are empty.
1391  * This routine can only be called on a live chain.
1392  *
1393  * NOTE: Flag is not set until after the count is complete, allowing
1394  *       callers to test the flag without holding the spinlock.
1395  *
1396  * NOTE: If base is NULL the related chain is still in the INITIAL
1397  *       state and there are no blockrefs to count.
1398  *
1399  * NOTE: live_count may already have some counts accumulated due to
1400  *       creation and deletion and could even be initially negative.
1401  */
1402 void
1403 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1404                          hammer2_blockref_t *base, int count)
1405 {
1406         hammer2_spin_ex(&chain->core.spin);
1407         if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1408                 if (base) {
1409                         while (--count >= 0) {
1410                                 if (base[count].type)
1411                                         break;
1412                         }
1413                         chain->core.live_zero = count + 1;
1414                         while (count >= 0) {
1415                                 if (base[count].type)
1416                                         atomic_add_int(&chain->core.live_count,
1417                                                        1);
1418                                 --count;
1419                         }
1420                 } else {
1421                         chain->core.live_zero = 0;
1422                 }
1423                 /* else do not modify live_count */
1424                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1425         }
1426         hammer2_spin_unex(&chain->core.spin);
1427 }
1428
1429 /*
1430  * Resize the chain's physical storage allocation in-place.  This function does
1431  * not usually adjust the data pointer and must be followed by (typically) a
1432  * hammer2_chain_modify() call to copy any old data over and adjust the
1433  * data pointer.
1434  *
1435  * Chains can be resized smaller without reallocating the storage.  Resizing
1436  * larger will reallocate the storage.  Excess or prior storage is reclaimed
1437  * asynchronously at a later time.
1438  *
1439  * An nradix value of 0 is special-cased to mean that the storage should
1440  * be disassociated, that is the chain is being resized to 0 bytes (not 1
1441  * byte).
1442  *
1443  * Must be passed an exclusively locked parent and chain.
1444  *
1445  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1446  * to avoid instantiating a device buffer that conflicts with the vnode data
1447  * buffer.  However, because H2 can compress or encrypt data, the chain may
1448  * have a dio assigned to it in those situations, and they do not conflict.
1449  *
1450  * XXX return error if cannot resize.
1451  */
1452 void
1453 hammer2_chain_resize(hammer2_chain_t *chain,
1454                      hammer2_tid_t mtid, hammer2_off_t dedup_off,
1455                      int nradix, int flags)
1456 {
1457         hammer2_dev_t *hmp;
1458         size_t obytes;
1459         size_t nbytes;
1460
1461         hmp = chain->hmp;
1462
1463         /*
1464          * Only data and indirect blocks can be resized for now.
1465          * (The volu root, inodes, and freemap elements use a fixed size).
1466          */
1467         KKASSERT(chain != &hmp->vchain);
1468         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1469                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1470                  chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1471
1472         /*
1473          * Nothing to do if the element is already the proper size
1474          */
1475         obytes = chain->bytes;
1476         nbytes = (nradix) ? (1U << nradix) : 0;
1477         if (obytes == nbytes)
1478                 return;
1479
1480         /*
1481          * Make sure the old data is instantiated so we can copy it.  If this
1482          * is a data block, the device data may be superfluous since the data
1483          * might be in a logical block, but compressed or encrypted data is
1484          * another matter.
1485          *
1486          * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1487          */
1488         hammer2_chain_modify(chain, mtid, dedup_off, 0);
1489
1490         /*
1491          * Relocate the block, even if making it smaller (because different
1492          * block sizes may be in different regions).
1493          *
1494          * NOTE: Operation does not copy the data and may only be used
1495          *        to resize data blocks in-place, or directory entry blocks
1496          *        which are about to be modified in some manner.
1497          */
1498         hammer2_freemap_alloc(chain, nbytes);
1499         chain->bytes = nbytes;
1500
1501         /*
1502          * We don't want the followup chain_modify() to try to copy data
1503          * from the old (wrong-sized) buffer.  It won't know how much to
1504          * copy.  This case should only occur during writes when the
1505          * originator already has the data to write in-hand.
1506          */
1507         if (chain->dio) {
1508                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1509                          chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1510                 hammer2_io_brelse(&chain->dio);
1511                 chain->data = NULL;
1512         }
1513 }
1514
1515 /*
1516  * Set the chain modified so its data can be changed by the caller, or
1517  * install deduplicated data.  The caller must call this routine for each
1518  * set of modifications it makes, even if the chain is already flagged
1519  * MODIFIED.
1520  *
1521  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1522  * is a CLC (cluster level change) field and is not updated by parent
1523  * propagation during a flush.
1524  *
1525  *                               Dedup Handling
1526  *
1527  * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1528  * even if the chain is still flagged MODIFIED.  In this case the chain's
1529  * DEDUPABLE flag will be cleared once the new storage has been assigned.
1530  *
1531  * If the caller passes a non-zero dedup_off we will use it to assign the
1532  * new storage.  The MODIFIED flag will be *CLEARED* in this case, and
1533  * DEDUPABLE will be set (NOTE: the UPDATE flag is always set).  The caller
1534  * must not modify the data content upon return.
1535  */
1536 void
1537 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1538                      hammer2_off_t dedup_off, int flags)
1539 {
1540         hammer2_blockref_t obref;
1541         hammer2_dev_t *hmp;
1542         hammer2_io_t *dio;
1543         int error;
1544         int wasinitial;
1545         int newmod;
1546         char *bdata;
1547
1548         hmp = chain->hmp;
1549         obref = chain->bref;
1550         KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1551
1552         /*
1553          * Data is not optional for freemap chains (we must always be sure
1554          * to copy the data on COW storage allocations).
1555          */
1556         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1557             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1558                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1559                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1560         }
1561
1562         /*
1563          * Data must be resolved if already assigned, unless explicitly
1564          * flagged otherwise.
1565          */
1566         if (chain->data == NULL && chain->bytes != 0 &&
1567             (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1568             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1569                 hammer2_chain_load_data(chain);
1570         }
1571
1572         /*
1573          * Set MODIFIED to indicate that the chain has been modified.  A new
1574          * allocation is required when modifying a chain.
1575          *
1576          * Set UPDATE to ensure that the blockref is updated in the parent.
1577          *
1578          *
1579          * If MODIFIED is already set determine if we can reuse the assigned
1580          * data block or if we need a new data block.
1581          */
1582         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1583                 /*
1584                  * Must set modified bit.
1585                  */
1586                 atomic_add_long(&hammer2_count_modified_chains, 1);
1587                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1588                 hammer2_pfs_memory_inc(chain->pmp);  /* can be NULL */
1589
1590                 /*
1591                  * We may be able to avoid a copy-on-write if the chain's
1592                  * check mode is set to NONE and the chain's current
1593                  * modify_tid is beyond the last explicit snapshot tid.
1594                  *
1595                  * This implements HAMMER2's overwrite-in-place feature.
1596                  *
1597                  * NOTE! This data-block cannot be used as a de-duplication
1598                  *       source when the check mode is set to NONE.
1599                  */
1600                 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1601                      chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1602                     (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1603                     (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1604                     HAMMER2_DEC_CHECK(chain->bref.methods) ==
1605                      HAMMER2_CHECK_NONE &&
1606                     chain->pmp &&
1607                     chain->bref.modify_tid >
1608                      chain->pmp->iroot->meta.pfs_lsnap_tid) {
1609                         /*
1610                          * Sector overwrite allowed.
1611                          */
1612                         newmod = 0;
1613                 } else {
1614                         /*
1615                          * Sector overwrite not allowed, must copy-on-write.
1616                          */
1617                         newmod = 1;
1618                 }
1619         } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1620                 /*
1621                  * If the modified chain was registered for dedup we need
1622                  * a new allocation.  This only happens for delayed-flush
1623                  * chains (i.e. which run through the front-end buffer
1624                  * cache).
1625                  */
1626                 newmod = 1;
1627         } else {
1628                 /*
1629                  * Already flagged modified, no new allocation is needed.
1630                  */
1631                 newmod = 0;
1632         }
1633
1634         /*
1635          * Flag parent update required.
1636          */
1637         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1638                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1639
1640         /*
1641          * The modification or re-modification requires an allocation and
1642          * possible COW.
1643          *
1644          * If dedup_off is non-zero, caller already has a data offset
1645          * containing the caller's desired data.  The dedup offset is
1646          * allowed to be in a partially free state and we must be sure
1647          * to reset it to a fully allocated state to force two bulkfree
1648          * passes to free it again.  The chain will not be marked MODIFIED
1649          * in the dedup case, as the dedup data cannot be changed without
1650          * a new allocation.
1651          *
1652          * NOTE: Only applicable when chain->bytes != 0.
1653          *
1654          * XXX can a chain already be marked MODIFIED without a data
1655          * assignment?  If not, assert here instead of testing the case.
1656          */
1657         if (chain != &hmp->vchain && chain != &hmp->fchain &&
1658             chain->bytes) {
1659                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1660                      newmod
1661                 ) {
1662                         /*
1663                          * NOTE: We do not have to remove the dedup
1664                          *       registration because the area is still
1665                          *       allocated and the underlying DIO will
1666                          *       still be flushed.
1667                          */
1668                         if (dedup_off) {
1669                                 chain->bref.data_off = dedup_off;
1670                                 chain->bytes = 1 << (dedup_off &
1671                                                      HAMMER2_OFF_MASK_RADIX);
1672                                 atomic_clear_int(&chain->flags,
1673                                                  HAMMER2_CHAIN_MODIFIED);
1674                                 atomic_add_long(&hammer2_count_modified_chains,
1675                                                 -1);
1676                                 if (chain->pmp)
1677                                         hammer2_pfs_memory_wakeup(chain->pmp);
1678                                 hammer2_freemap_adjust(hmp, &chain->bref,
1679                                                 HAMMER2_FREEMAP_DORECOVER);
1680                                 atomic_set_int(&chain->flags,
1681                                                 HAMMER2_CHAIN_DEDUPABLE);
1682                         } else {
1683                                 hammer2_freemap_alloc(chain, chain->bytes);
1684                                 atomic_clear_int(&chain->flags,
1685                                                 HAMMER2_CHAIN_DEDUPABLE);
1686                         }
1687                         /* XXX failed allocation */
1688                 }
1689         }
1690
1691         /*
1692          * Update mirror_tid and modify_tid.  modify_tid is only updated
1693          * if not passed as zero (during flushes, parent propagation passes
1694          * the value 0).
1695          *
1696          * NOTE: chain->pmp could be the device spmp.
1697          */
1698         chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1699         if (mtid)
1700                 chain->bref.modify_tid = mtid;
1701
1702         /*
1703          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1704          * requires updating as well as to tell the delete code that the
1705          * chain's blockref might not exactly match (in terms of physical size
1706          * or block offset) the one in the parent's blocktable.  The base key
1707          * of course will still match.
1708          */
1709         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1710                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1711
1712         /*
1713          * Short-cut data blocks which the caller does not need an actual
1714          * data reference to (aka OPTDATA), as long as the chain does not
1715          * already have a data pointer to the data.  This generally means
1716          * that the modifications are being done via the logical buffer cache.
1717          * The INITIAL flag relates only to the device data buffer and thus
1718          * remains unchange in this situation.
1719          *
1720          * This code also handles bytes == 0 (most dirents).
1721          */
1722         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1723             (flags & HAMMER2_MODIFY_OPTDATA) &&
1724             chain->data == NULL) {
1725                 KKASSERT(chain->dio == NULL);
1726                 goto skip2;
1727         }
1728
1729         /*
1730          * Clearing the INITIAL flag (for indirect blocks) indicates that
1731          * we've processed the uninitialized storage allocation.
1732          *
1733          * If this flag is already clear we are likely in a copy-on-write
1734          * situation but we have to be sure NOT to bzero the storage if
1735          * no data is present.
1736          */
1737         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1738                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1739                 wasinitial = 1;
1740         } else {
1741                 wasinitial = 0;
1742         }
1743
1744         /*
1745          * Instantiate data buffer and possibly execute COW operation
1746          */
1747         switch(chain->bref.type) {
1748         case HAMMER2_BREF_TYPE_VOLUME:
1749         case HAMMER2_BREF_TYPE_FREEMAP:
1750                 /*
1751                  * The data is embedded, no copy-on-write operation is
1752                  * needed.
1753                  */
1754                 KKASSERT(chain->dio == NULL);
1755                 break;
1756         case HAMMER2_BREF_TYPE_DIRENT:
1757                 /*
1758                  * The data might be fully embedded.
1759                  */
1760                 if (chain->bytes == 0) {
1761                         KKASSERT(chain->dio == NULL);
1762                         break;
1763                 }
1764                 /* fall through */
1765         case HAMMER2_BREF_TYPE_INODE:
1766         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1767         case HAMMER2_BREF_TYPE_DATA:
1768         case HAMMER2_BREF_TYPE_INDIRECT:
1769         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1770                 /*
1771                  * Perform the copy-on-write operation
1772                  *
1773                  * zero-fill or copy-on-write depending on whether
1774                  * chain->data exists or not and set the dirty state for
1775                  * the new buffer.  hammer2_io_new() will handle the
1776                  * zero-fill.
1777                  *
1778                  * If a dedup_off was supplied this is an existing block
1779                  * and no COW, copy, or further modification is required.
1780                  */
1781                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1782
1783                 if (wasinitial && dedup_off == 0) {
1784                         error = hammer2_io_new(hmp, chain->bref.type,
1785                                                chain->bref.data_off,
1786                                                chain->bytes, &dio);
1787                 } else {
1788                         error = hammer2_io_bread(hmp, chain->bref.type,
1789                                                  chain->bref.data_off,
1790                                                  chain->bytes, &dio);
1791                 }
1792                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1793
1794                 /*
1795                  * If an I/O error occurs make sure callers cannot accidently
1796                  * modify the old buffer's contents and corrupt the filesystem.
1797                  */
1798                 if (error) {
1799                         kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1800                                 hmp);
1801                         chain->error = HAMMER2_ERROR_IO;
1802                         hammer2_io_brelse(&dio);
1803                         hammer2_io_brelse(&chain->dio);
1804                         chain->data = NULL;
1805                         break;
1806                 }
1807                 chain->error = 0;
1808                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1809
1810                 if (chain->data) {
1811                         /*
1812                          * COW (unless a dedup).
1813                          */
1814                         KKASSERT(chain->dio != NULL);
1815                         if (chain->data != (void *)bdata && dedup_off == 0) {
1816                                 bcopy(chain->data, bdata, chain->bytes);
1817                         }
1818                 } else if (wasinitial == 0) {
1819                         /*
1820                          * We have a problem.  We were asked to COW but
1821                          * we don't have any data to COW with!
1822                          */
1823                         panic("hammer2_chain_modify: having a COW %p\n",
1824                               chain);
1825                 }
1826
1827                 /*
1828                  * Retire the old buffer, replace with the new.  Dirty or
1829                  * redirty the new buffer.
1830                  *
1831                  * WARNING! The system buffer cache may have already flushed
1832                  *          the buffer, so we must be sure to [re]dirty it
1833                  *          for further modification.
1834                  *
1835                  *          If dedup_off was supplied, the caller is not
1836                  *          expected to make any further modification to the
1837                  *          buffer.
1838                  */
1839                 if (chain->dio)
1840                         hammer2_io_bqrelse(&chain->dio);
1841                 chain->data = (void *)bdata;
1842                 chain->dio = dio;
1843                 if (dedup_off == 0)
1844                         hammer2_io_setdirty(dio);
1845                 break;
1846         default:
1847                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1848                       chain->bref.type);
1849                 break;
1850
1851         }
1852 skip2:
1853         /*
1854          * setflush on parent indicating that the parent must recurse down
1855          * to us.  Do not call on chain itself which might already have it
1856          * set.
1857          */
1858         if (chain->parent)
1859                 hammer2_chain_setflush(chain->parent);
1860 }
1861
1862 /*
1863  * Modify the chain associated with an inode.
1864  */
1865 void
1866 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1867                         hammer2_tid_t mtid, int flags)
1868 {
1869         hammer2_inode_modify(ip);
1870         hammer2_chain_modify(chain, mtid, 0, flags);
1871 }
1872
1873 /*
1874  * Volume header data locks
1875  */
1876 void
1877 hammer2_voldata_lock(hammer2_dev_t *hmp)
1878 {
1879         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1880 }
1881
1882 void
1883 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1884 {
1885         lockmgr(&hmp->vollk, LK_RELEASE);
1886 }
1887
1888 void
1889 hammer2_voldata_modify(hammer2_dev_t *hmp)
1890 {
1891         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1892                 atomic_add_long(&hammer2_count_modified_chains, 1);
1893                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1894                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1895         }
1896 }
1897
1898 /*
1899  * This function returns the chain at the nearest key within the specified
1900  * range.  The returned chain will be referenced but not locked.
1901  *
1902  * This function will recurse through chain->rbtree as necessary and will
1903  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1904  * the iteration value is less than the current value of *key_nextp.
1905  *
1906  * The caller should use (*key_nextp) to calculate the actual range of
1907  * the returned element, which will be (key_beg to *key_nextp - 1), because
1908  * there might be another element which is superior to the returned element
1909  * and overlaps it.
1910  *
1911  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1912  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1913  * it will wind up being (key_end + 1).
1914  *
1915  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1916  *           held through the operation.
1917  */
1918 struct hammer2_chain_find_info {
1919         hammer2_chain_t         *best;
1920         hammer2_key_t           key_beg;
1921         hammer2_key_t           key_end;
1922         hammer2_key_t           key_next;
1923 };
1924
1925 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1926 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1927
1928 static
1929 hammer2_chain_t *
1930 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1931                           hammer2_key_t key_beg, hammer2_key_t key_end)
1932 {
1933         struct hammer2_chain_find_info info;
1934
1935         info.best = NULL;
1936         info.key_beg = key_beg;
1937         info.key_end = key_end;
1938         info.key_next = *key_nextp;
1939
1940         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1941                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1942                 &info);
1943         *key_nextp = info.key_next;
1944 #if 0
1945         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1946                 parent, key_beg, key_end, *key_nextp);
1947 #endif
1948
1949         return (info.best);
1950 }
1951
1952 static
1953 int
1954 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1955 {
1956         struct hammer2_chain_find_info *info = data;
1957         hammer2_key_t child_beg;
1958         hammer2_key_t child_end;
1959
1960         child_beg = child->bref.key;
1961         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1962
1963         if (child_end < info->key_beg)
1964                 return(-1);
1965         if (child_beg > info->key_end)
1966                 return(1);
1967         return(0);
1968 }
1969
1970 static
1971 int
1972 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1973 {
1974         struct hammer2_chain_find_info *info = data;
1975         hammer2_chain_t *best;
1976         hammer2_key_t child_end;
1977
1978         /*
1979          * WARNING! Layerq is scanned forwards, exact matches should keep
1980          *          the existing info->best.
1981          */
1982         if ((best = info->best) == NULL) {
1983                 /*
1984                  * No previous best.  Assign best
1985                  */
1986                 info->best = child;
1987         } else if (best->bref.key <= info->key_beg &&
1988                    child->bref.key <= info->key_beg) {
1989                 /*
1990                  * Illegal overlap.
1991                  */
1992                 KKASSERT(0);
1993                 /*info->best = child;*/
1994         } else if (child->bref.key < best->bref.key) {
1995                 /*
1996                  * Child has a nearer key and best is not flush with key_beg.
1997                  * Set best to child.  Truncate key_next to the old best key.
1998                  */
1999                 info->best = child;
2000                 if (info->key_next > best->bref.key || info->key_next == 0)
2001                         info->key_next = best->bref.key;
2002         } else if (child->bref.key == best->bref.key) {
2003                 /*
2004                  * If our current best is flush with the child then this
2005                  * is an illegal overlap.
2006                  *
2007                  * key_next will automatically be limited to the smaller of
2008                  * the two end-points.
2009                  */
2010                 KKASSERT(0);
2011                 info->best = child;
2012         } else {
2013                 /*
2014                  * Keep the current best but truncate key_next to the child's
2015                  * base.
2016                  *
2017                  * key_next will also automatically be limited to the smaller
2018                  * of the two end-points (probably not necessary for this case
2019                  * but we do it anyway).
2020                  */
2021                 if (info->key_next > child->bref.key || info->key_next == 0)
2022                         info->key_next = child->bref.key;
2023         }
2024
2025         /*
2026          * Always truncate key_next based on child's end-of-range.
2027          */
2028         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2029         if (child_end && (info->key_next > child_end || info->key_next == 0))
2030                 info->key_next = child_end;
2031
2032         return(0);
2033 }
2034
2035 /*
2036  * Retrieve the specified chain from a media blockref, creating the
2037  * in-memory chain structure which reflects it.  The returned chain is
2038  * held but not locked.  The caller must lock it to crc-check and
2039  * dereference its data, and should check chain->error after locking
2040  * before assuming that the data is good.
2041  *
2042  * To handle insertion races pass the INSERT_RACE flag along with the
2043  * generation number of the core.  NULL will be returned if the generation
2044  * number changes before we have a chance to insert the chain.  Insert
2045  * races can occur because the parent might be held shared.
2046  *
2047  * Caller must hold the parent locked shared or exclusive since we may
2048  * need the parent's bref array to find our block.
2049  *
2050  * WARNING! chain->pmp is always set to NULL for any chain representing
2051  *          part of the super-root topology.
2052  */
2053 hammer2_chain_t *
2054 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2055                   hammer2_blockref_t *bref)
2056 {
2057         hammer2_dev_t *hmp = parent->hmp;
2058         hammer2_chain_t *chain;
2059         int error;
2060
2061         /*
2062          * Allocate a chain structure representing the existing media
2063          * entry.  Resulting chain has one ref and is not locked.
2064          */
2065         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2066                 chain = hammer2_chain_alloc(hmp, NULL, bref);
2067         else
2068                 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2069         /* ref'd chain returned */
2070
2071         /*
2072          * Flag that the chain is in the parent's blockmap so delete/flush
2073          * knows what to do with it.
2074          */
2075         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2076
2077         /*
2078          * Link the chain into its parent.  A spinlock is required to safely
2079          * access the RBTREE, and it is possible to collide with another
2080          * hammer2_chain_get() operation because the caller might only hold
2081          * a shared lock on the parent.
2082          *
2083          * NOTE: Get races can occur quite often when we distribute
2084          *       asynchronous read-aheads across multiple threads.
2085          */
2086         KKASSERT(parent->refs > 0);
2087         error = hammer2_chain_insert(parent, chain,
2088                                      HAMMER2_CHAIN_INSERT_SPIN |
2089                                      HAMMER2_CHAIN_INSERT_RACE,
2090                                      generation);
2091         if (error) {
2092                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2093                 /*kprintf("chain %p get race\n", chain);*/
2094                 hammer2_chain_drop(chain);
2095                 chain = NULL;
2096         } else {
2097                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2098         }
2099
2100         /*
2101          * Return our new chain referenced but not locked, or NULL if
2102          * a race occurred.
2103          */
2104         return (chain);
2105 }
2106
2107 /*
2108  * Lookup initialization/completion API
2109  */
2110 hammer2_chain_t *
2111 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2112 {
2113         hammer2_chain_ref(parent);
2114         if (flags & HAMMER2_LOOKUP_SHARED) {
2115                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2116                                            HAMMER2_RESOLVE_SHARED);
2117         } else {
2118                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2119         }
2120         return (parent);
2121 }
2122
2123 void
2124 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2125 {
2126         if (parent) {
2127                 hammer2_chain_unlock(parent);
2128                 hammer2_chain_drop(parent);
2129         }
2130 }
2131
2132 /*
2133  * Take the locked chain and return a locked parent.  The chain remains
2134  * locked on return.
2135  *
2136  * This will work even if the chain is errored, and the caller can check
2137  * parent->error on return if desired since the parent will be locked.
2138  *
2139  * This function handles the lock order reversal.
2140  */
2141 hammer2_chain_t *
2142 hammer2_chain_getparent(hammer2_chain_t *chain, int how)
2143 {
2144         hammer2_chain_t *parent;
2145
2146         /*
2147          * Be careful of order, chain must be unlocked before parent
2148          * is locked below to avoid a deadlock.
2149          *
2150          * Safe access to fu->parent requires fu's core spinlock.
2151          */
2152 again:
2153         hammer2_spin_ex(&chain->core.spin);
2154         parent = chain->parent;
2155         if (parent == NULL) {
2156                 hammer2_spin_unex(&chain->core.spin);
2157                 panic("hammer2_chain_getparent: no parent");
2158         }
2159         hammer2_chain_ref(parent);
2160         hammer2_spin_unex(&chain->core.spin);
2161
2162         hammer2_chain_unlock(chain);
2163         hammer2_chain_lock(parent, how);
2164         hammer2_chain_lock(chain, how);
2165
2166         /*
2167          * Parent relinking races are quite common.  We have to get it right
2168          * or we will blow up the block table.
2169          */
2170         if (chain->parent != parent) {
2171                 hammer2_chain_unlock(parent);
2172                 hammer2_chain_drop(parent);
2173                 goto again;
2174         }
2175         return parent;
2176 }
2177
2178 /*
2179  * Take the locked chain and return a locked parent.  The chain is unlocked
2180  * and dropped.  *chainp is set to the returned parent as a convenience.
2181  *
2182  * This will work even if the chain is errored, and the caller can check
2183  * parent->error on return if desired since the parent will be locked.
2184  *
2185  * This function handles the lock order reversal.
2186  */
2187 hammer2_chain_t *
2188 hammer2_chain_repparent(hammer2_chain_t **chainp, int how)
2189 {
2190         hammer2_chain_t *chain;
2191         hammer2_chain_t *parent;
2192
2193         /*
2194          * Be careful of order, chain must be unlocked before parent
2195          * is locked below to avoid a deadlock.
2196          *
2197          * Safe access to fu->parent requires fu's core spinlock.
2198          */
2199         chain = *chainp;
2200 again:
2201         hammer2_spin_ex(&chain->core.spin);
2202         parent = chain->parent;
2203         if (parent == NULL) {
2204                 hammer2_spin_unex(&chain->core.spin);
2205                 panic("hammer2_chain_getparent: no parent");
2206         }
2207         hammer2_chain_ref(parent);
2208         hammer2_spin_unex(&chain->core.spin);
2209
2210         hammer2_chain_unlock(chain);
2211         hammer2_chain_lock(parent, how);
2212
2213         /*
2214          * Parent relinking races are quite common.  We have to get it right
2215          * or we will blow up the block table.
2216          */
2217         if (chain->parent != parent) {
2218                 hammer2_chain_lock(chain, how);
2219                 hammer2_chain_unlock(parent);
2220                 hammer2_chain_drop(parent);
2221                 goto again;
2222         }
2223         hammer2_chain_drop(chain);
2224         *chainp = parent;
2225
2226         return parent;
2227 }
2228
2229 /*
2230  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2231  * (*parentp) typically points to an inode but can also point to a related
2232  * indirect block and this function will recurse upwards and find the inode
2233  * again.
2234  *
2235  * This function unconditionally sets *errorp, replacing any previous value.
2236  *
2237  * (*parentp) must be exclusively locked and referenced and can be an inode
2238  * or an existing indirect block within the inode.  If (*parent) is errored
2239  * out, this function will not attempt to recurse the radix tree and
2240  * will return NULL along with an appropriate *errorp.  If NULL is returned
2241  * and *errorp is 0, the requested lookup could not be located.
2242  *
2243  * On return (*parentp) will be modified to point at the deepest parent chain
2244  * element encountered during the search, as a helper for an insertion or
2245  * deletion.   The new (*parentp) will be locked and referenced and the old
2246  * will be unlocked and dereferenced (no change if they are both the same).
2247  * This is particularly important if the caller wishes to insert a new chain,
2248  * (*parentp) will be set properly even if NULL is returned, as long as no
2249  * error occurred.
2250  *
2251  * The matching chain will be returned exclusively locked.  If NOLOCK is
2252  * requested the chain will be returned only referenced.  Note that the
2253  * parent chain must always be locked shared or exclusive, matching the
2254  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
2255  * when NOLOCK is specified but that complicates matters if *parentp must
2256  * inherit the chain.
2257  *
2258  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2259  * data pointer or can otherwise be in flux.
2260  *
2261  * NULL is returned if no match was found, but (*parentp) will still
2262  * potentially be adjusted.
2263  *
2264  * On return (*key_nextp) will point to an iterative value for key_beg.
2265  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2266  *
2267  * This function will also recurse up the chain if the key is not within the
2268  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
2269  * can simply allow (*parentp) to float inside the loop.
2270  *
2271  * NOTE!  chain->data is not always resolved.  By default it will not be
2272  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
2273  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2274  *        BREF_TYPE_DATA as the device buffer can alias the logical file
2275  *        buffer).
2276  */
2277
2278 hammer2_chain_t *
2279 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2280                      hammer2_key_t key_beg, hammer2_key_t key_end,
2281                      int flags)
2282 {
2283         hammer2_dev_t *hmp;
2284         hammer2_chain_t *parent;
2285         hammer2_chain_t *chain;
2286         hammer2_blockref_t *base;
2287         hammer2_blockref_t *bref;
2288         hammer2_blockref_t bcopy;
2289         hammer2_key_t scan_beg;
2290         hammer2_key_t scan_end;
2291         int count = 0;
2292         int how_always = HAMMER2_RESOLVE_ALWAYS;
2293         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2294         int how;
2295         int generation;
2296         int maxloops = 300000;
2297
2298         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2299                 how_maybe = how_always;
2300                 how = HAMMER2_RESOLVE_ALWAYS;
2301         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2302                 how = HAMMER2_RESOLVE_NEVER;
2303         } else {
2304                 how = HAMMER2_RESOLVE_MAYBE;
2305         }
2306         if (flags & HAMMER2_LOOKUP_SHARED) {
2307                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2308                 how_always |= HAMMER2_RESOLVE_SHARED;
2309                 how |= HAMMER2_RESOLVE_SHARED;
2310         }
2311
2312         /*
2313          * Recurse (*parentp) upward if necessary until the parent completely
2314          * encloses the key range or we hit the inode.
2315          *
2316          * Handle races against the flusher deleting indirect nodes on its
2317          * way back up by continuing to recurse upward past the deletion.
2318          */
2319         parent = *parentp;
2320         hmp = parent->hmp;
2321
2322         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2323                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2324                 scan_beg = parent->bref.key;
2325                 scan_end = scan_beg +
2326                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2327                 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2328                         if (key_beg >= scan_beg && key_end <= scan_end)
2329                                 break;
2330                 }
2331                 parent = hammer2_chain_repparent(parentp, how_maybe);
2332         }
2333 again:
2334
2335         if (--maxloops == 0)
2336                 panic("hammer2_chain_lookup: maxloops");
2337         /*
2338          * Locate the blockref array.  Currently we do a fully associative
2339          * search through the array.
2340          */
2341         switch(parent->bref.type) {
2342         case HAMMER2_BREF_TYPE_INODE:
2343                 /*
2344                  * Special shortcut for embedded data returns the inode
2345                  * itself.  Callers must detect this condition and access
2346                  * the embedded data (the strategy code does this for us).
2347                  *
2348                  * This is only applicable to regular files and softlinks.
2349                  *
2350                  * We need a second lock on parent.  Since we already have
2351                  * a lock we must pass LOCKAGAIN to prevent unexpected
2352                  * blocking (we don't want to block on a second shared
2353                  * ref if an exclusive lock is pending)
2354                  */
2355                 if (parent->data->ipdata.meta.op_flags &
2356                     HAMMER2_OPFLAG_DIRECTDATA) {
2357                         if (flags & HAMMER2_LOOKUP_NODIRECT) {
2358                                 chain = NULL;
2359                                 *key_nextp = key_end + 1;
2360                                 goto done;
2361                         }
2362                         hammer2_chain_ref(parent);
2363                         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2364                                 hammer2_chain_lock(parent,
2365                                                    how_always |
2366                                                     HAMMER2_RESOLVE_LOCKAGAIN);
2367                         *key_nextp = key_end + 1;
2368                         return (parent);
2369                 }
2370                 base = &parent->data->ipdata.u.blockset.blockref[0];
2371                 count = HAMMER2_SET_COUNT;
2372                 break;
2373         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2374         case HAMMER2_BREF_TYPE_INDIRECT:
2375                 /*
2376                  * Handle MATCHIND on the parent
2377                  */
2378                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2379                         scan_beg = parent->bref.key;
2380                         scan_end = scan_beg +
2381                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2382                         if (key_beg == scan_beg && key_end == scan_end) {
2383                                 chain = parent;
2384                                 hammer2_chain_ref(chain);
2385                                 hammer2_chain_lock(chain, how_maybe);
2386                                 *key_nextp = scan_end + 1;
2387                                 goto done;
2388                         }
2389                 }
2390
2391                 /*
2392                  * Optimize indirect blocks in the INITIAL state to avoid
2393                  * I/O.
2394                  */
2395                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2396                         base = NULL;
2397                 } else {
2398                         if (parent->data == NULL) {
2399                                 kprintf("parent->data is NULL %p\n", parent);
2400                                 while (1)
2401                                         tsleep(parent, 0, "xxx", 0);
2402                         }
2403                         base = &parent->data->npdata[0];
2404                 }
2405                 count = parent->bytes / sizeof(hammer2_blockref_t);
2406                 break;
2407         case HAMMER2_BREF_TYPE_VOLUME:
2408                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2409                 count = HAMMER2_SET_COUNT;
2410                 break;
2411         case HAMMER2_BREF_TYPE_FREEMAP:
2412                 base = &parent->data->blkset.blockref[0];
2413                 count = HAMMER2_SET_COUNT;
2414                 break;
2415         default:
2416                 kprintf("hammer2_chain_lookup: unrecognized "
2417                         "blockref(B) type: %d",
2418                         parent->bref.type);
2419                 while (1)
2420                         tsleep(&base, 0, "dead", 0);
2421                 panic("hammer2_chain_lookup: unrecognized "
2422                       "blockref(B) type: %d",
2423                       parent->bref.type);
2424                 base = NULL;    /* safety */
2425                 count = 0;      /* safety */
2426         }
2427
2428         /*
2429          * Merged scan to find next candidate.
2430          *
2431          * hammer2_base_*() functions require the parent->core.live_* fields
2432          * to be synchronized.
2433          *
2434          * We need to hold the spinlock to access the block array and RB tree
2435          * and to interlock chain creation.
2436          */
2437         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2438                 hammer2_chain_countbrefs(parent, base, count);
2439
2440         /*
2441          * Combined search
2442          */
2443         hammer2_spin_ex(&parent->core.spin);
2444         chain = hammer2_combined_find(parent, base, count,
2445                                       key_nextp,
2446                                       key_beg, key_end,
2447                                       &bref);
2448         generation = parent->core.generation;
2449
2450         /*
2451          * Exhausted parent chain, iterate.
2452          */
2453         if (bref == NULL) {
2454                 hammer2_spin_unex(&parent->core.spin);
2455                 if (key_beg == key_end) /* short cut single-key case */
2456                         return (NULL);
2457
2458                 /*
2459                  * Stop if we reached the end of the iteration.
2460                  */
2461                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2462                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2463                         return (NULL);
2464                 }
2465
2466                 /*
2467                  * Calculate next key, stop if we reached the end of the
2468                  * iteration, otherwise go up one level and loop.
2469                  */
2470                 key_beg = parent->bref.key +
2471                           ((hammer2_key_t)1 << parent->bref.keybits);
2472                 if (key_beg == 0 || key_beg > key_end)
2473                         return (NULL);
2474                 parent = hammer2_chain_repparent(parentp, how_maybe);
2475                 goto again;
2476         }
2477
2478         /*
2479          * Selected from blockref or in-memory chain.
2480          */
2481         if (chain == NULL) {
2482                 bcopy = *bref;
2483                 hammer2_spin_unex(&parent->core.spin);
2484                 chain = hammer2_chain_get(parent, generation,
2485                                           &bcopy);
2486                 if (chain == NULL) {
2487                         /*
2488                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2489                                 parent, key_beg, key_end);
2490                         */
2491                         goto again;
2492                 }
2493                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2494                         hammer2_chain_drop(chain);
2495                         goto again;
2496                 }
2497         } else {
2498                 hammer2_chain_ref(chain);
2499                 hammer2_spin_unex(&parent->core.spin);
2500         }
2501
2502         /*
2503          * chain is referenced but not locked.  We must lock the chain
2504          * to obtain definitive state.
2505          */
2506         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2507             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2508                 hammer2_chain_lock(chain, how_maybe);
2509         } else {
2510                 hammer2_chain_lock(chain, how);
2511         }
2512         KKASSERT(chain->parent == parent);
2513
2514         /*
2515          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2516          *
2517          * NOTE: Chain's key range is not relevant as there might be
2518          *       one-offs within the range that are not deleted.
2519          *
2520          * NOTE: Lookups can race delete-duplicate because
2521          *       delete-duplicate does not lock the parent's core
2522          *       (they just use the spinlock on the core).
2523          */
2524         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2525                 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2526                         chain->bref.data_off, chain->bref.type,
2527                         chain->bref.key);
2528                 hammer2_chain_unlock(chain);
2529                 hammer2_chain_drop(chain);
2530                 key_beg = *key_nextp;
2531                 if (key_beg == 0 || key_beg > key_end)
2532                         return(NULL);
2533                 goto again;
2534         }
2535
2536         /*
2537          * If the chain element is an indirect block it becomes the new
2538          * parent and we loop on it.  We must maintain our top-down locks
2539          * to prevent the flusher from interfering (i.e. doing a
2540          * delete-duplicate and leaving us recursing down a deleted chain).
2541          *
2542          * The parent always has to be locked with at least RESOLVE_MAYBE
2543          * so we can access its data.  It might need a fixup if the caller
2544          * passed incompatible flags.  Be careful not to cause a deadlock
2545          * as a data-load requires an exclusive lock.
2546          *
2547          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2548          * range is within the requested key range we return the indirect
2549          * block and do NOT loop.  This is usually only used to acquire
2550          * freemap nodes.
2551          */
2552         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2553             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2554                 hammer2_chain_unlock(parent);
2555                 hammer2_chain_drop(parent);
2556                 *parentp = parent = chain;
2557                 goto again;
2558         }
2559 done:
2560         /*
2561          * All done, return the chain.
2562          *
2563          * If the caller does not want a locked chain, replace the lock with
2564          * a ref.  Perhaps this can eventually be optimized to not obtain the
2565          * lock in the first place for situations where the data does not
2566          * need to be resolved.
2567          */
2568         if (chain) {
2569                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2570                         hammer2_chain_unlock(chain);
2571         }
2572         return (chain);
2573 }
2574
2575 /*
2576  * After having issued a lookup we can iterate all matching keys.
2577  *
2578  * If chain is non-NULL we continue the iteration from just after it's index.
2579  *
2580  * If chain is NULL we assume the parent was exhausted and continue the
2581  * iteration at the next parent.
2582  *
2583  * If a fatal error occurs (typically an I/O error), a dummy chain is
2584  * returned with chain->error and error-identifying information set.  This
2585  * chain will assert if you try to do anything fancy with it.
2586  *
2587  * XXX Depending on where the error occurs we should allow continued iteration.
2588  *
2589  * parent must be locked on entry and remains locked throughout.  chain's
2590  * lock status must match flags.  Chain is always at least referenced.
2591  *
2592  * WARNING!  The MATCHIND flag does not apply to this function.
2593  */
2594 hammer2_chain_t *
2595 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2596                    hammer2_key_t *key_nextp,
2597                    hammer2_key_t key_beg, hammer2_key_t key_end,
2598                    int flags)
2599 {
2600         hammer2_chain_t *parent;
2601         int how_maybe;
2602
2603         /*
2604          * Calculate locking flags for upward recursion.
2605          */
2606         how_maybe = HAMMER2_RESOLVE_MAYBE;
2607         if (flags & HAMMER2_LOOKUP_SHARED)
2608                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2609
2610         parent = *parentp;
2611
2612         /*
2613          * Calculate the next index and recalculate the parent if necessary.
2614          */
2615         if (chain) {
2616                 key_beg = chain->bref.key +
2617                           ((hammer2_key_t)1 << chain->bref.keybits);
2618                 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2619                               HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2620                         hammer2_chain_unlock(chain);
2621                 }
2622                 hammer2_chain_drop(chain);
2623
2624                 /*
2625                  * chain invalid past this point, but we can still do a
2626                  * pointer comparison w/parent.
2627                  *
2628                  * Any scan where the lookup returned degenerate data embedded
2629                  * in the inode has an invalid index and must terminate.
2630                  */
2631                 if (chain == parent)
2632                         return(NULL);
2633                 if (key_beg == 0 || key_beg > key_end)
2634                         return(NULL);
2635                 chain = NULL;
2636         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2637                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2638                 /*
2639                  * We reached the end of the iteration.
2640                  */
2641                 return (NULL);
2642         } else {
2643                 /*
2644                  * Continue iteration with next parent unless the current
2645                  * parent covers the range.
2646                  *
2647                  * (This also handles the case of a deleted, empty indirect
2648                  * node).
2649                  */
2650                 key_beg = parent->bref.key +
2651                           ((hammer2_key_t)1 << parent->bref.keybits);
2652                 if (key_beg == 0 || key_beg > key_end)
2653                         return (NULL);
2654                 parent = hammer2_chain_repparent(parentp, how_maybe);
2655         }
2656
2657         /*
2658          * And execute
2659          */
2660         return (hammer2_chain_lookup(parentp, key_nextp,
2661                                      key_beg, key_end,
2662                                      flags));
2663 }
2664
2665 /*
2666  * Caller wishes to iterate chains under parent, loading new chains into
2667  * chainp.  Caller must initialize *chainp to NULL and *firstp to 1, and
2668  * then call hammer2_chain_scan() repeatedly until a non-zero return.
2669  * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
2670  * with the returned chain for the scan.  The returned *chainp will be
2671  * locked and referenced.  Any prior contents will be unlocked and dropped.
2672  *
2673  * Caller should check the return value.  A normal scan EOF will return
2674  * exactly HAMMER2_ERRORF_EOF.  Any other non-zero value indicates an
2675  * error trying to access parent data.  Any error in the returned chain
2676  * must be tested separately by the caller.
2677  *
2678  * (*chainp) is dropped on each scan, but will only be set if the returned
2679  * element itself can recurse.  Leaf elements are NOT resolved, loaded, or
2680  * returned via *chainp.  The caller will get their bref only.
2681  *
2682  * The raw scan function is similar to lookup/next but does not seek to a key.
2683  * Blockrefs are iterated via first_bref = (parent, NULL) and
2684  * next_chain = (parent, bref).
2685  *
2686  * The passed-in parent must be locked and its data resolved.  The function
2687  * nominally returns a locked and referenced *chainp != NULL for chains
2688  * the caller might need to recurse on (and will dipose of any *chainp passed
2689  * in).  The caller must check the chain->bref.type either way.
2690  */
2691 int
2692 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2693                    hammer2_blockref_t *bref, int *firstp,
2694                    int flags)
2695 {
2696         hammer2_dev_t *hmp;
2697         hammer2_blockref_t *base;
2698         hammer2_blockref_t *bref_ptr;
2699         hammer2_key_t key;
2700         hammer2_key_t next_key;
2701         hammer2_chain_t *chain = NULL;
2702         int count = 0;
2703         int how_always = HAMMER2_RESOLVE_ALWAYS;
2704         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2705         int how;
2706         int generation;
2707         int maxloops = 300000;
2708         int error;
2709
2710         hmp = parent->hmp;
2711         error = 0;
2712
2713         /*
2714          * Scan flags borrowed from lookup.
2715          */
2716         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2717                 how_maybe = how_always;
2718                 how = HAMMER2_RESOLVE_ALWAYS;
2719         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2720                 how = HAMMER2_RESOLVE_NEVER;
2721         } else {
2722                 how = HAMMER2_RESOLVE_MAYBE;
2723         }
2724         if (flags & HAMMER2_LOOKUP_SHARED) {
2725                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2726                 how_always |= HAMMER2_RESOLVE_SHARED;
2727                 how |= HAMMER2_RESOLVE_SHARED;
2728         }
2729
2730         /*
2731          * Calculate key to locate first/next element, unlocking the previous
2732          * element as we go.  Be careful, the key calculation can overflow.
2733          *
2734          * (also reset bref to NULL)
2735          */
2736         if (*firstp) {
2737                 key = 0;
2738                 *firstp = 0;
2739         } else {
2740                 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2741                 if ((chain = *chainp) != NULL) {
2742                         *chainp = NULL;
2743                         hammer2_chain_unlock(chain);
2744                         hammer2_chain_drop(chain);
2745                         chain = NULL;
2746                 }
2747                 if (key == 0) {
2748                         error |= HAMMER2_ERROR_EOF;
2749                         goto done;
2750                 }
2751         }
2752
2753 again:
2754         if (parent->error) {
2755                 error = parent->error;
2756                 goto done;
2757         }
2758         if (--maxloops == 0)
2759                 panic("hammer2_chain_scan: maxloops");
2760
2761         /*
2762          * Locate the blockref array.  Currently we do a fully associative
2763          * search through the array.
2764          */
2765         switch(parent->bref.type) {
2766         case HAMMER2_BREF_TYPE_INODE:
2767                 /*
2768                  * An inode with embedded data has no sub-chains.
2769                  *
2770                  * WARNING! Bulk scan code may pass a static chain marked
2771                  *          as BREF_TYPE_INODE with a copy of the volume
2772                  *          root blockset to snapshot the volume.
2773                  */
2774                 if (parent->data->ipdata.meta.op_flags &
2775                     HAMMER2_OPFLAG_DIRECTDATA) {
2776                         error |= HAMMER2_ERROR_EOF;
2777                         goto done;
2778                 }
2779                 base = &parent->data->ipdata.u.blockset.blockref[0];
2780                 count = HAMMER2_SET_COUNT;
2781                 break;
2782         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2783         case HAMMER2_BREF_TYPE_INDIRECT:
2784                 /*
2785                  * Optimize indirect blocks in the INITIAL state to avoid
2786                  * I/O.
2787                  */
2788                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2789                         base = NULL;
2790                 } else {
2791                         if (parent->data == NULL)
2792                                 panic("parent->data is NULL");
2793                         base = &parent->data->npdata[0];
2794                 }
2795                 count = parent->bytes / sizeof(hammer2_blockref_t);
2796                 break;
2797         case HAMMER2_BREF_TYPE_VOLUME:
2798                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2799                 count = HAMMER2_SET_COUNT;
2800                 break;
2801         case HAMMER2_BREF_TYPE_FREEMAP:
2802                 base = &parent->data->blkset.blockref[0];
2803                 count = HAMMER2_SET_COUNT;
2804                 break;
2805         default:
2806                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2807                       parent->bref.type);
2808                 base = NULL;    /* safety */
2809                 count = 0;      /* safety */
2810         }
2811
2812         /*
2813          * Merged scan to find next candidate.
2814          *
2815          * hammer2_base_*() functions require the parent->core.live_* fields
2816          * to be synchronized.
2817          *
2818          * We need to hold the spinlock to access the block array and RB tree
2819          * and to interlock chain creation.
2820          */
2821         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2822                 hammer2_chain_countbrefs(parent, base, count);
2823
2824         next_key = 0;
2825         bref_ptr = NULL;
2826         hammer2_spin_ex(&parent->core.spin);
2827         chain = hammer2_combined_find(parent, base, count,
2828                                       &next_key,
2829                                       key, HAMMER2_KEY_MAX,
2830                                       &bref_ptr);
2831         generation = parent->core.generation;
2832
2833         /*
2834          * Exhausted parent chain, we're done.
2835          */
2836         if (bref_ptr == NULL) {
2837                 hammer2_spin_unex(&parent->core.spin);
2838                 KKASSERT(chain == NULL);
2839                 error |= HAMMER2_ERROR_EOF;
2840                 goto done;
2841         }
2842
2843         /*
2844          * Copy into the supplied stack-based blockref.
2845          */
2846         *bref = *bref_ptr;
2847
2848         /*
2849          * Selected from blockref or in-memory chain.
2850          */
2851         if (chain == NULL) {
2852                 switch(bref->type) {
2853                 case HAMMER2_BREF_TYPE_INODE:
2854                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2855                 case HAMMER2_BREF_TYPE_INDIRECT:
2856                 case HAMMER2_BREF_TYPE_VOLUME:
2857                 case HAMMER2_BREF_TYPE_FREEMAP:
2858                         /*
2859                          * Recursion, always get the chain
2860                          */
2861                         hammer2_spin_unex(&parent->core.spin);
2862                         chain = hammer2_chain_get(parent, generation, bref);
2863                         if (chain == NULL) {
2864                                 kprintf("retry scan parent %p keys %016jx\n",
2865                                         parent, key);
2866                                 goto again;
2867                         }
2868                         if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2869                                 hammer2_chain_drop(chain);
2870                                 chain = NULL;
2871                                 goto again;
2872                         }
2873                         break;
2874                 default:
2875                         /*
2876                          * No recursion, do not waste time instantiating
2877                          * a chain, just iterate using the bref.
2878                          */
2879                         hammer2_spin_unex(&parent->core.spin);
2880                         break;
2881                 }
2882         } else {
2883                 /*
2884                  * Recursion or not we need the chain in order to supply
2885                  * the bref.
2886                  */
2887                 hammer2_chain_ref(chain);
2888                 hammer2_spin_unex(&parent->core.spin);
2889         }
2890
2891         /*
2892          * chain is referenced but not locked.  We must lock the chain
2893          * to obtain definitive state.
2894          */
2895         if (chain)
2896                 hammer2_chain_lock(chain, how);
2897
2898         /*
2899          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2900          *
2901          * NOTE: chain's key range is not relevant as there might be
2902          *       one-offs within the range that are not deleted.
2903          *
2904          * NOTE: XXX this could create problems with scans used in
2905          *       situations other than mount-time recovery.
2906          *
2907          * NOTE: Lookups can race delete-duplicate because
2908          *       delete-duplicate does not lock the parent's core
2909          *       (they just use the spinlock on the core).
2910          */
2911         if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2912                 hammer2_chain_unlock(chain);
2913                 hammer2_chain_drop(chain);
2914                 chain = NULL;
2915
2916                 key = next_key;
2917                 if (key == 0) {
2918                         error |= HAMMER2_ERROR_EOF;
2919                         goto done;
2920                 }
2921                 goto again;
2922         }
2923
2924 done:
2925         /*
2926          * All done, return the bref or NULL, supply chain if necessary.
2927          */
2928         if (chain)
2929                 *chainp = chain;
2930         return (error);
2931 }
2932
2933 /*
2934  * Create and return a new hammer2 system memory structure of the specified
2935  * key, type and size and insert it under (*parentp).  This is a full
2936  * insertion, based on the supplied key/keybits, and may involve creating
2937  * indirect blocks and moving other chains around via delete/duplicate.
2938  *
2939  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2940  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2941  * FULL.  This typically means that the caller is creating the chain after
2942  * doing a hammer2_chain_lookup().
2943  *
2944  * (*parentp) must be exclusive locked and may be replaced on return
2945  * depending on how much work the function had to do.
2946  *
2947  * (*parentp) must not be errored or this function will assert.
2948  *
2949  * (*chainp) usually starts out NULL and returns the newly created chain,
2950  * but if the caller desires the caller may allocate a disconnected chain
2951  * and pass it in instead.
2952  *
2953  * This function should NOT be used to insert INDIRECT blocks.  It is
2954  * typically used to create/insert inodes and data blocks.
2955  *
2956  * Caller must pass-in an exclusively locked parent the new chain is to
2957  * be inserted under, and optionally pass-in a disconnected, exclusively
2958  * locked chain to insert (else we create a new chain).  The function will
2959  * adjust (*parentp) as necessary, create or connect the chain, and
2960  * return an exclusively locked chain in *chainp.
2961  *
2962  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2963  * and will be reassigned.
2964  */
2965 int
2966 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2967                      hammer2_pfs_t *pmp, int methods,
2968                      hammer2_key_t key, int keybits, int type, size_t bytes,
2969                      hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2970 {
2971         hammer2_dev_t *hmp;
2972         hammer2_chain_t *chain;
2973         hammer2_chain_t *parent;
2974         hammer2_blockref_t *base;
2975         hammer2_blockref_t dummy;
2976         int allocated = 0;
2977         int error = 0;
2978         int count;
2979         int maxloops = 300000;
2980
2981         /*
2982          * Topology may be crossing a PFS boundary.
2983          */
2984         parent = *parentp;
2985         KKASSERT(hammer2_mtx_owned(&parent->lock));
2986         KKASSERT(parent->error == 0);
2987         hmp = parent->hmp;
2988         chain = *chainp;
2989
2990         if (chain == NULL) {
2991                 /*
2992                  * First allocate media space and construct the dummy bref,
2993                  * then allocate the in-memory chain structure.  Set the
2994                  * INITIAL flag for fresh chains which do not have embedded
2995                  * data.
2996                  *
2997                  * XXX for now set the check mode of the child based on
2998                  *     the parent or, if the parent is an inode, the
2999                  *     specification in the inode.
3000                  */
3001                 bzero(&dummy, sizeof(dummy));
3002                 dummy.type = type;
3003                 dummy.key = key;
3004                 dummy.keybits = keybits;
3005                 dummy.data_off = hammer2_getradix(bytes);
3006
3007                 /*
3008                  * Inherit methods from parent by default.  Primarily used
3009                  * for BREF_TYPE_DATA.  Non-data types *must* be set to
3010                  * a non-NONE check algorithm.
3011                  */
3012                 if (methods == -1)
3013                         dummy.methods = parent->bref.methods;
3014                 else
3015                         dummy.methods = (uint8_t)methods;
3016
3017                 if (type != HAMMER2_BREF_TYPE_DATA &&
3018                     HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3019                         dummy.methods |=
3020                                 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3021                 }
3022
3023                 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3024
3025                 /*
3026                  * Lock the chain manually, chain_lock will load the chain
3027                  * which we do NOT want to do.  (note: chain->refs is set
3028                  * to 1 by chain_alloc() for us, but lockcnt is not).
3029                  */
3030                 chain->lockcnt = 1;
3031                 hammer2_mtx_ex(&chain->lock);
3032                 allocated = 1;
3033                 ++curthread->td_tracker;
3034
3035                 /*
3036                  * Set INITIAL to optimize I/O.  The flag will generally be
3037                  * processed when we call hammer2_chain_modify().
3038                  *
3039                  * Recalculate bytes to reflect the actual media block
3040                  * allocation.  Handle special case radix 0 == 0 bytes.
3041                  */
3042                 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3043                 if (bytes)
3044                         bytes = (hammer2_off_t)1 << bytes;
3045                 chain->bytes = bytes;
3046
3047                 switch(type) {
3048                 case HAMMER2_BREF_TYPE_VOLUME:
3049                 case HAMMER2_BREF_TYPE_FREEMAP:
3050                         panic("hammer2_chain_create: called with volume type");
3051                         break;
3052                 case HAMMER2_BREF_TYPE_INDIRECT:
3053                         panic("hammer2_chain_create: cannot be used to"
3054                               "create indirect block");
3055                         break;
3056                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3057                         panic("hammer2_chain_create: cannot be used to"
3058                               "create freemap root or node");
3059                         break;
3060                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3061                         KKASSERT(bytes == sizeof(chain->data->bmdata));
3062                         /* fall through */
3063                 case HAMMER2_BREF_TYPE_DIRENT:
3064                 case HAMMER2_BREF_TYPE_INODE:
3065                 case HAMMER2_BREF_TYPE_DATA:
3066                 default:
3067                         /*
3068                          * leave chain->data NULL, set INITIAL
3069                          */
3070                         KKASSERT(chain->data == NULL);
3071                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3072                         break;
3073                 }
3074         } else {
3075                 /*
3076                  * We are reattaching a previously deleted chain, possibly
3077                  * under a new parent and possibly with a new key/keybits.
3078                  * The chain does not have to be in a modified state.  The
3079                  * UPDATE flag will be set later on in this routine.
3080                  *
3081                  * Do NOT mess with the current state of the INITIAL flag.
3082                  */
3083                 chain->bref.key = key;
3084                 chain->bref.keybits = keybits;
3085                 if (chain->flags & HAMMER2_CHAIN_DELETED)
3086                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3087                 KKASSERT(chain->parent == NULL);
3088         }
3089         if (flags & HAMMER2_INSERT_PFSROOT)
3090                 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3091         else
3092                 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3093
3094         /*
3095          * Calculate how many entries we have in the blockref array and
3096          * determine if an indirect block is required.
3097          */
3098 again:
3099         if (--maxloops == 0)
3100                 panic("hammer2_chain_create: maxloops");
3101
3102         switch(parent->bref.type) {
3103         case HAMMER2_BREF_TYPE_INODE:
3104                 if ((parent->data->ipdata.meta.op_flags &
3105                      HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3106                         kprintf("hammer2: parent set for direct-data! "
3107                                 "pkey=%016jx ckey=%016jx\n",
3108                                 parent->bref.key,
3109                                 chain->bref.key);
3110                 }
3111                 KKASSERT((parent->data->ipdata.meta.op_flags &
3112                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
3113                 KKASSERT(parent->data != NULL);
3114                 base = &parent->data->ipdata.u.blockset.blockref[0];
3115                 count = HAMMER2_SET_COUNT;
3116                 break;
3117         case HAMMER2_BREF_TYPE_INDIRECT:
3118         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3119                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3120                         base = NULL;
3121                 else
3122                         base = &parent->data->npdata[0];
3123                 count = parent->bytes / sizeof(hammer2_blockref_t);
3124                 break;
3125         case HAMMER2_BREF_TYPE_VOLUME:
3126                 KKASSERT(parent->data != NULL);
3127                 base = &parent->data->voldata.sroot_blockset.blockref[0];
3128                 count = HAMMER2_SET_COUNT;
3129                 break;
3130         case HAMMER2_BREF_TYPE_FREEMAP:
3131                 KKASSERT(parent->data != NULL);
3132                 base = &parent->data->blkset.blockref[0];
3133                 count = HAMMER2_SET_COUNT;
3134                 break;
3135         default:
3136                 panic("hammer2_chain_create: unrecognized blockref type: %d",
3137                       parent->bref.type);
3138                 base = NULL;
3139                 count = 0;
3140                 break;
3141         }
3142
3143         /*
3144          * Make sure we've counted the brefs
3145          */
3146         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3147                 hammer2_chain_countbrefs(parent, base, count);
3148
3149         KASSERT(parent->core.live_count >= 0 &&
3150                 parent->core.live_count <= count,
3151                 ("bad live_count %d/%d (%02x, %d)",
3152                         parent->core.live_count, count,
3153                         parent->bref.type, parent->bytes));
3154
3155         /*
3156          * If no free blockref could be found we must create an indirect
3157          * block and move a number of blockrefs into it.  With the parent
3158          * locked we can safely lock each child in order to delete+duplicate
3159          * it without causing a deadlock.
3160          *
3161          * This may return the new indirect block or the old parent depending
3162          * on where the key falls.  NULL is returned on error.
3163          */
3164         if (parent->core.live_count == count) {
3165                 hammer2_chain_t *nparent;
3166
3167                 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3168                                                         mtid, type, &error);
3169                 if (nparent == NULL) {
3170                         if (allocated)
3171                                 hammer2_chain_drop(chain);
3172                         chain = NULL;
3173                         goto done;
3174                 }
3175                 if (parent != nparent) {
3176                         hammer2_chain_unlock(parent);
3177                         hammer2_chain_drop(parent);
3178                         parent = *parentp = nparent;
3179                 }
3180                 goto again;
3181         }
3182
3183         if (chain->flags & HAMMER2_CHAIN_DELETED)
3184                 kprintf("Inserting deleted chain @%016jx\n",
3185                         chain->bref.key);
3186
3187         /*
3188          * Link the chain into its parent.
3189          */
3190         if (chain->parent != NULL)
3191                 panic("hammer2: hammer2_chain_create: chain already connected");
3192         KKASSERT(chain->parent == NULL);
3193         hammer2_chain_insert(parent, chain,
3194                              HAMMER2_CHAIN_INSERT_SPIN |
3195                              HAMMER2_CHAIN_INSERT_LIVE,
3196                              0);
3197
3198         if (allocated) {
3199                 /*
3200                  * Mark the newly created chain modified.  This will cause
3201                  * UPDATE to be set and process the INITIAL flag.
3202                  *
3203                  * Device buffers are not instantiated for DATA elements
3204                  * as these are handled by logical buffers.
3205                  *
3206                  * Indirect and freemap node indirect blocks are handled
3207                  * by hammer2_chain_create_indirect() and not by this
3208                  * function.
3209                  *
3210                  * Data for all other bref types is expected to be
3211                  * instantiated (INODE, LEAF).
3212                  */
3213                 switch(chain->bref.type) {
3214                 case HAMMER2_BREF_TYPE_DATA:
3215                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3216                 case HAMMER2_BREF_TYPE_DIRENT:
3217                 case HAMMER2_BREF_TYPE_INODE:
3218                         hammer2_chain_modify(chain, mtid, dedup_off,
3219                                              HAMMER2_MODIFY_OPTDATA);
3220                         break;
3221                 default:
3222                         /*
3223                          * Remaining types are not supported by this function.
3224                          * In particular, INDIRECT and LEAF_NODE types are
3225                          * handled by create_indirect().
3226                          */
3227                         panic("hammer2_chain_create: bad type: %d",
3228                               chain->bref.type);
3229                         /* NOT REACHED */
3230                         break;
3231                 }
3232         } else {
3233                 /*
3234                  * When reconnecting a chain we must set UPDATE and
3235                  * setflush so the flush recognizes that it must update
3236                  * the bref in the parent.
3237                  */
3238                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3239                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3240         }
3241
3242         /*
3243          * We must setflush(parent) to ensure that it recurses through to
3244          * chain.  setflush(chain) might not work because ONFLUSH is possibly
3245          * already set in the chain (so it won't recurse up to set it in the
3246          * parent).
3247          */
3248         hammer2_chain_setflush(parent);
3249
3250 done:
3251         *chainp = chain;
3252
3253         return (error);
3254 }
3255
3256 /*
3257  * Move the chain from its old parent to a new parent.  The chain must have
3258  * already been deleted or already disconnected (or never associated) with
3259  * a parent.  The chain is reassociated with the new parent and the deleted
3260  * flag will be cleared (no longer deleted).  The chain's modification state
3261  * is not altered.
3262  *
3263  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3264  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3265  * FULL.  This typically means that the caller is creating the chain after
3266  * doing a hammer2_chain_lookup().
3267  *
3268  * A non-NULL bref is typically passed when key and keybits must be overridden.
3269  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3270  * from a passed-in bref and uses the old chain's bref for everything else.
3271  *
3272  * Neither (parent) or (chain) can be errored.
3273  *
3274  * If (parent) is non-NULL then the chain is inserted under the parent.
3275  *
3276  * If (parent) is NULL then the newly duplicated chain is not inserted
3277  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3278  * passing into hammer2_chain_create() after this function returns).
3279  *
3280  * WARNING! This function calls create which means it can insert indirect
3281  *          blocks.  This can cause other unrelated chains in the parent to
3282  *          be moved to a newly inserted indirect block in addition to the
3283  *          specific chain.
3284  */
3285 void
3286 hammer2_chain_rename(hammer2_blockref_t *bref,
3287                      hammer2_chain_t **parentp, hammer2_chain_t *chain,
3288                      hammer2_tid_t mtid, int flags)
3289 {
3290         hammer2_dev_t *hmp;
3291         hammer2_chain_t *parent;
3292         size_t bytes;
3293
3294         /*
3295          * WARNING!  We should never resolve DATA to device buffers
3296          *           (XXX allow it if the caller did?), and since
3297          *           we currently do not have the logical buffer cache
3298          *           buffer in-hand to fix its cached physical offset
3299          *           we also force the modify code to not COW it. XXX
3300          */
3301         hmp = chain->hmp;
3302         KKASSERT(chain->parent == NULL);
3303         KKASSERT(chain->error == 0);
3304
3305         /*
3306          * Now create a duplicate of the chain structure, associating
3307          * it with the same core, making it the same size, pointing it
3308          * to the same bref (the same media block).
3309          *
3310          * NOTE: Handle special radix == 0 case (means 0 bytes).
3311          */
3312         if (bref == NULL)
3313                 bref = &chain->bref;
3314         bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3315         if (bytes)
3316                 bytes = (hammer2_off_t)1 << bytes;
3317
3318         /*
3319          * If parent is not NULL the duplicated chain will be entered under
3320          * the parent and the UPDATE bit set to tell flush to update
3321          * the blockref.
3322          *
3323          * We must setflush(parent) to ensure that it recurses through to
3324          * chain.  setflush(chain) might not work because ONFLUSH is possibly
3325          * already set in the chain (so it won't recurse up to set it in the
3326          * parent).
3327          *
3328          * Having both chains locked is extremely important for atomicy.
3329          */
3330         if (parentp && (parent = *parentp) != NULL) {
3331                 KKASSERT(hammer2_mtx_owned(&parent->lock));
3332                 KKASSERT(parent->refs > 0);
3333                 KKASSERT(parent->error == 0);
3334
3335                 hammer2_chain_create(parentp, &chain,
3336                                      chain->pmp, HAMMER2_METH_DEFAULT,
3337                                      bref->key, bref->keybits, bref->type,
3338                                      chain->bytes, mtid, 0, flags);
3339                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3340                 hammer2_chain_setflush(*parentp);
3341         }
3342 }
3343
3344 /*
3345  * Helper function for deleting chains.
3346  *
3347  * The chain is removed from the live view (the RBTREE) as well as the parent's
3348  * blockmap.  Both chain and its parent must be locked.
3349  *
3350  * parent may not be errored.  chain can be errored.
3351  */
3352 static void
3353 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3354                              hammer2_tid_t mtid, int flags)
3355 {
3356         hammer2_dev_t *hmp;
3357
3358         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3359                                   HAMMER2_CHAIN_FICTITIOUS)) == 0);
3360         KKASSERT(chain->parent == parent);
3361         hmp = chain->hmp;
3362
3363         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3364                 /*
3365                  * Chain is blockmapped, so there must be a parent.
3366                  * Atomically remove the chain from the parent and remove
3367                  * the blockmap entry.  The parent must be set modified
3368                  * to remove the blockmap entry.
3369                  */
3370                 hammer2_blockref_t *base;
3371                 int count;
3372
3373                 KKASSERT(parent != NULL);
3374                 KKASSERT(parent->error == 0);
3375                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3376                 hammer2_chain_modify(parent, mtid, 0, 0);
3377
3378                 /*
3379                  * Calculate blockmap pointer
3380                  */
3381                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3382                 hammer2_spin_ex(&chain->core.spin);
3383                 hammer2_spin_ex(&parent->core.spin);
3384
3385                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3386                 atomic_add_int(&parent->core.live_count, -1);
3387                 ++parent->core.generation;
3388                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3389                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3390                 --parent->core.chain_count;
3391                 chain->parent = NULL;
3392
3393                 switch(parent->bref.type) {
3394                 case HAMMER2_BREF_TYPE_INODE:
3395                         /*
3396                          * Access the inode's block array.  However, there
3397                          * is no block array if the inode is flagged
3398                          * DIRECTDATA.
3399                          */
3400                         if (parent->data &&
3401                             (parent->data->ipdata.meta.op_flags &
3402                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3403                                 base =
3404                                    &parent->data->ipdata.u.blockset.blockref[0];
3405                         } else {
3406                                 base = NULL;
3407                         }
3408                         count = HAMMER2_SET_COUNT;
3409                         break;
3410                 case HAMMER2_BREF_TYPE_INDIRECT:
3411                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3412                         if (parent->data)
3413                                 base = &parent->data->npdata[0];
3414                         else
3415                                 base = NULL;
3416                         count = parent->bytes / sizeof(hammer2_blockref_t);
3417                         break;
3418                 case HAMMER2_BREF_TYPE_VOLUME:
3419                         base = &parent->data->voldata.
3420                                         sroot_blockset.blockref[0];
3421                         count = HAMMER2_SET_COUNT;
3422                         break;
3423                 case HAMMER2_BREF_TYPE_FREEMAP:
3424                         base = &parent->data->blkset.blockref[0];
3425                         count = HAMMER2_SET_COUNT;
3426                         break;
3427                 default:
3428                         base = NULL;
3429                         count = 0;
3430                         panic("hammer2_flush_pass2: "
3431                               "unrecognized blockref type: %d",
3432                               parent->bref.type);
3433                 }
3434
3435                 /*
3436                  * delete blockmapped chain from its parent.
3437                  *
3438                  * The parent is not affected by any statistics in chain
3439                  * which are pending synchronization.  That is, there is
3440                  * nothing to undo in the parent since they have not yet
3441                  * been incorporated into the parent.
3442                  *
3443                  * The parent is affected by statistics stored in inodes.
3444                  * Those have already been synchronized, so they must be
3445                  * undone.  XXX split update possible w/delete in middle?
3446                  */
3447                 if (base) {
3448                         hammer2_base_delete(parent, base, count, chain);
3449                 }
3450                 hammer2_spin_unex(&parent->core.spin);
3451                 hammer2_spin_unex(&chain->core.spin);
3452         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3453                 /*
3454                  * Chain is not blockmapped but a parent is present.
3455                  * Atomically remove the chain from the parent.  There is
3456                  * no blockmap entry to remove.
3457                  *
3458                  * Because chain was associated with a parent but not
3459                  * synchronized, the chain's *_count_up fields contain
3460                  * inode adjustment statistics which must be undone.
3461                  */
3462                 hammer2_spin_ex(&chain->core.spin);
3463                 hammer2_spin_ex(&parent->core.spin);
3464                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3465                 atomic_add_int(&parent->core.live_count, -1);
3466                 ++parent->core.generation;
3467                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3468                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3469                 --parent->core.chain_count;
3470                 chain->parent = NULL;
3471                 hammer2_spin_unex(&parent->core.spin);
3472                 hammer2_spin_unex(&chain->core.spin);
3473         } else {
3474                 /*
3475                  * Chain is not blockmapped and has no parent.  This
3476                  * is a degenerate case.
3477                  */
3478                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3479         }
3480 }
3481
3482 /*
3483  * Create an indirect block that covers one or more of the elements in the
3484  * current parent.  Either returns the existing parent with no locking or
3485  * ref changes or returns the new indirect block locked and referenced
3486  * and leaving the original parent lock/ref intact as well.
3487  *
3488  * If an error occurs, NULL is returned and *errorp is set to the error.
3489  *
3490  * The returned chain depends on where the specified key falls.
3491  *
3492  * The key/keybits for the indirect mode only needs to follow three rules:
3493  *
3494  * (1) That all elements underneath it fit within its key space and
3495  *
3496  * (2) That all elements outside it are outside its key space.
3497  *
3498  * (3) When creating the new indirect block any elements in the current
3499  *     parent that fit within the new indirect block's keyspace must be
3500  *     moved into the new indirect block.
3501  *
3502  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3503  *     keyspace the the current parent, but lookup/iteration rules will
3504  *     ensure (and must ensure) that rule (2) for all parents leading up
3505  *     to the nearest inode or the root volume header is adhered to.  This
3506  *     is accomplished by always recursing through matching keyspaces in
3507  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3508  *
3509  * The current implementation calculates the current worst-case keyspace by
3510  * iterating the current parent and then divides it into two halves, choosing
3511  * whichever half has the most elements (not necessarily the half containing
3512  * the requested key).
3513  *
3514  * We can also opt to use the half with the least number of elements.  This
3515  * causes lower-numbered keys (aka logical file offsets) to recurse through
3516  * fewer indirect blocks and higher-numbered keys to recurse through more.
3517  * This also has the risk of not moving enough elements to the new indirect
3518  * block and being forced to create several indirect blocks before the element
3519  * can be inserted.
3520  *
3521  * Must be called with an exclusively locked parent.
3522  */
3523 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3524                                 hammer2_key_t *keyp, int keybits,
3525                                 hammer2_blockref_t *base, int count);
3526 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3527                                 hammer2_key_t *keyp, int keybits,
3528                                 hammer2_blockref_t *base, int count,
3529                                 int ncount);
3530 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3531                                 hammer2_key_t *keyp, int keybits,
3532                                 hammer2_blockref_t *base, int count,
3533                                 int ncount);
3534 static
3535 hammer2_chain_t *
3536 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3537                               hammer2_key_t create_key, int create_bits,
3538                               hammer2_tid_t mtid, int for_type, int *errorp)
3539 {
3540         hammer2_dev_t *hmp;
3541         hammer2_blockref_t *base;
3542         hammer2_blockref_t *bref;
3543         hammer2_blockref_t bcopy;
3544         hammer2_chain_t *chain;
3545         hammer2_chain_t *ichain;
3546         hammer2_chain_t dummy;
3547         hammer2_key_t key = create_key;
3548         hammer2_key_t key_beg;
3549         hammer2_key_t key_end;
3550         hammer2_key_t key_next;
3551         int keybits = create_bits;
3552         int count;
3553         int ncount;
3554         int nbytes;
3555         int loops;
3556         int reason;
3557         int generation;
3558         int maxloops = 300000;
3559
3560         /*
3561          * Calculate the base blockref pointer or NULL if the chain
3562          * is known to be empty.  We need to calculate the array count
3563          * for RB lookups either way.
3564          */
3565         hmp = parent->hmp;
3566         *errorp = 0;
3567         KKASSERT(hammer2_mtx_owned(&parent->lock));
3568
3569         /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3570         base = hammer2_chain_base_and_count(parent, &count);
3571
3572         /*
3573          * dummy used in later chain allocation (no longer used for lookups).
3574          */
3575         bzero(&dummy, sizeof(dummy));
3576
3577         /*
3578          * How big should our new indirect block be?  It has to be at least
3579          * as large as its parent for splits to work properly.
3580          *
3581          * The freemap uses a specific indirect block size.  The number of
3582          * levels are built dynamically and ultimately depend on the size
3583          * volume.  Because freemap blocks are taken from the reserved areas
3584          * of the volume our goal is efficiency (fewer levels) and not so
3585          * much to save disk space.
3586          *
3587          * The first indirect block level for a directory usually uses
3588          * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries).  Due to
3589          * the hash mechanism, this typically gives us a nominal
3590          * 32 * 4 entries with one level of indirection.
3591          *
3592          * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3593          * indirect blocks.  The initial 4 entries in the inode gives us
3594          * 256KB.  Up to 4 indirect blocks gives us 32MB.  Three levels
3595          * of indirection gives us 137GB, and so forth.  H2 can support
3596          * huge file sizes but they are not typical, so we try to stick
3597          * with compactness and do not use a larger indirect block size.
3598          *
3599          * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3600          * due to the way indirect blocks are created this usually winds
3601          * up being extremely inefficient for small files.  Even though
3602          * 16KB requires more levels of indirection for very large files,
3603          * the 16KB records can be ganged together into 64KB DIOs.
3604          */
3605         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3606             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3607                 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3608         } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3609                 if (parent->data->ipdata.meta.type ==
3610                     HAMMER2_OBJTYPE_DIRECTORY)
3611                         nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3612                 else
3613                         nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3614
3615         } else {
3616                 nbytes = HAMMER2_IND_BYTES_NOM;
3617         }
3618         if (nbytes < count * sizeof(hammer2_blockref_t)) {
3619                 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3620                          for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3621                 nbytes = count * sizeof(hammer2_blockref_t);
3622         }
3623         ncount = nbytes / sizeof(hammer2_blockref_t);
3624
3625         /*
3626          * When creating an indirect block for a freemap node or leaf
3627          * the key/keybits must be fitted to static radix levels because
3628          * particular radix levels use particular reserved blocks in the
3629          * related zone.
3630          *
3631          * This routine calculates the key/radix of the indirect block
3632          * we need to create, and whether it is on the high-side or the
3633          * low-side.
3634          */
3635         switch(for_type) {
3636         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3637         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3638                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3639                                                        base, count);
3640                 break;
3641         case HAMMER2_BREF_TYPE_DATA:
3642                 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3643                                                     base, count, ncount);
3644                 break;
3645         case HAMMER2_BREF_TYPE_DIRENT:
3646         case HAMMER2_BREF_TYPE_INODE:
3647                 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3648                                                    base, count, ncount);
3649                 break;
3650         default:
3651                 panic("illegal indirect block for bref type %d", for_type);
3652                 break;
3653         }
3654
3655         /*
3656          * Normalize the key for the radix being represented, keeping the
3657          * high bits and throwing away the low bits.
3658          */
3659         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3660
3661         /*
3662          * Ok, create our new indirect block
3663          */
3664         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3665             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3666                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3667         } else {
3668                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3669         }
3670         dummy.bref.key = key;
3671         dummy.bref.keybits = keybits;
3672         dummy.bref.data_off = hammer2_getradix(nbytes);
3673         dummy.bref.methods =
3674                 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3675                 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3676
3677         ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3678         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3679         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3680         /* ichain has one ref at this point */
3681
3682         /*
3683          * We have to mark it modified to allocate its block, but use
3684          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3685          * it won't be acted upon by the flush code.
3686          */
3687         hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3688
3689         /*
3690          * Iterate the original parent and move the matching brefs into
3691          * the new indirect block.
3692          *
3693          * XXX handle flushes.
3694          */
3695         key_beg = 0;
3696         key_end = HAMMER2_KEY_MAX;
3697         key_next = 0;   /* avoid gcc warnings */
3698         hammer2_spin_ex(&parent->core.spin);
3699         loops = 0;
3700         reason = 0;
3701
3702         for (;;) {
3703                 /*
3704                  * Parent may have been modified, relocating its block array.
3705                  * Reload the base pointer.
3706                  */
3707                 base = hammer2_chain_base_and_count(parent, &count);
3708
3709                 if (++loops > 100000) {
3710                     hammer2_spin_unex(&parent->core.spin);
3711                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3712                           reason, parent, base, count, key_next);
3713                 }
3714
3715                 /*
3716                  * NOTE: spinlock stays intact, returned chain (if not NULL)
3717                  *       is not referenced or locked which means that we
3718                  *       cannot safely check its flagged / deletion status
3719                  *       until we lock it.
3720                  */
3721                 chain = hammer2_combined_find(parent, base, count,
3722                                               &key_next,
3723                                               key_beg, key_end,
3724                                               &bref);
3725                 generation = parent->core.generation;
3726                 if (bref == NULL)
3727                         break;
3728                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3729
3730                 /*
3731                  * Skip keys that are not within the key/radix of the new
3732                  * indirect block.  They stay in the parent.
3733                  */
3734                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3735                     (key ^ bref->key)) != 0) {
3736                         goto next_key_spinlocked;
3737                 }
3738
3739                 /*
3740                  * Load the new indirect block by acquiring the related
3741                  * chains (potentially from media as it might not be
3742                  * in-memory).  Then move it to the new parent (ichain).
3743                  *
3744                  * chain is referenced but not locked.  We must lock the
3745                  * chain to obtain definitive state.
3746                  */
3747                 if (chain) {
3748                         /*
3749                          * Use chain already present in the RBTREE
3750                          */
3751                         hammer2_chain_ref(chain);
3752                         hammer2_spin_unex(&parent->core.spin);
3753                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3754                 } else {
3755                         /*
3756                          * Get chain for blockref element.  _get returns NULL
3757                          * on insertion race.
3758                          */
3759                         bcopy = *bref;
3760                         hammer2_spin_unex(&parent->core.spin);
3761                         chain = hammer2_chain_get(parent, generation, &bcopy);
3762                         if (chain == NULL) {
3763                                 reason = 1;
3764                                 hammer2_spin_ex(&parent->core.spin);
3765                                 continue;
3766                         }
3767                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3768                                 kprintf("REASON 2\n");
3769                                 reason = 2;
3770                                 hammer2_chain_drop(chain);
3771                                 hammer2_spin_ex(&parent->core.spin);
3772                                 continue;
3773                         }
3774                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3775                 }
3776
3777                 /*
3778                  * This is always live so if the chain has been deleted
3779                  * we raced someone and we have to retry.
3780                  *
3781                  * NOTE: Lookups can race delete-duplicate because
3782                  *       delete-duplicate does not lock the parent's core
3783                  *       (they just use the spinlock on the core).
3784                  *
3785                  *       (note reversed logic for this one)
3786                  */
3787                 if (chain->parent != parent ||
3788                     (chain->flags & HAMMER2_CHAIN_DELETED)) {
3789                         hammer2_chain_unlock(chain);
3790                         hammer2_chain_drop(chain);
3791                         kprintf("hammer2_chain_create_indirect "
3792                                 "RETRY (%p,%p)->%p %08x\n",
3793                                 parent, chain->parent, chain, chain->flags);
3794                         hammer2_spin_ex(&parent->core.spin);
3795                         continue;
3796                 }
3797
3798                 /*
3799                  * Shift the chain to the indirect block.
3800                  *
3801                  * WARNING! No reason for us to load chain data, pass NOSTATS
3802                  *          to prevent delete/insert from trying to access
3803                  *          inode stats (and thus asserting if there is no
3804                  *          chain->data loaded).
3805                  *
3806                  * WARNING! The (parent, chain) deletion may modify the parent
3807                  *          and invalidate the base pointer.
3808                  */
3809                 hammer2_chain_delete(parent, chain, mtid, 0);
3810                 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3811                 hammer2_chain_unlock(chain);
3812                 hammer2_chain_drop(chain);
3813                 KKASSERT(parent->refs > 0);
3814                 chain = NULL;
3815                 base = NULL;    /* safety */
3816                 hammer2_spin_ex(&parent->core.spin);
3817 next_key_spinlocked:
3818                 if (--maxloops == 0)
3819                         panic("hammer2_chain_create_indirect: maxloops");
3820                 reason = 4;
3821                 if (key_next == 0 || key_next > key_end)
3822                         break;
3823                 key_beg = key_next;
3824                 /* loop */
3825         }
3826         hammer2_spin_unex(&parent->core.spin);
3827
3828         /*
3829          * Insert the new indirect block into the parent now that we've
3830          * cleared out some entries in the parent.  We calculated a good
3831          * insertion index in the loop above (ichain->index).
3832          *
3833          * We don't have to set UPDATE here because we mark ichain
3834          * modified down below (so the normal modified -> flush -> set-moved
3835          * sequence applies).
3836          *
3837          * The insertion shouldn't race as this is a completely new block
3838          * and the parent is locked.
3839          */
3840         base = NULL;    /* safety, parent modify may change address */
3841         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3842         hammer2_chain_insert(parent, ichain,
3843                              HAMMER2_CHAIN_INSERT_SPIN |
3844                              HAMMER2_CHAIN_INSERT_LIVE,
3845                              0);
3846
3847         /*
3848          * Make sure flushes propogate after our manual insertion.
3849          */
3850         hammer2_chain_setflush(ichain);
3851         hammer2_chain_setflush(parent);
3852
3853         /*
3854          * Figure out what to return.
3855          */
3856         if (~(((hammer2_key_t)1 << keybits) - 1) &
3857                    (create_key ^ key)) {
3858                 /*
3859                  * Key being created is outside the key range,
3860                  * return the original parent.
3861                  */
3862                 hammer2_chain_unlock(ichain);
3863                 hammer2_chain_drop(ichain);
3864         } else {
3865                 /*
3866                  * Otherwise its in the range, return the new parent.
3867                  * (leave both the new and old parent locked).
3868                  */
3869                 parent = ichain;
3870         }
3871
3872         return(parent);
3873 }
3874
3875 /*
3876  * Freemap indirect blocks
3877  *
3878  * Calculate the keybits and highside/lowside of the freemap node the
3879  * caller is creating.
3880  *
3881  * This routine will specify the next higher-level freemap key/radix
3882  * representing the lowest-ordered set.  By doing so, eventually all
3883  * low-ordered sets will be moved one level down.
3884  *
3885  * We have to be careful here because the freemap reserves a limited
3886  * number of blocks for a limited number of levels.  So we can't just
3887  * push indiscriminately.
3888  */
3889 int
3890 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3891                              int keybits, hammer2_blockref_t *base, int count)
3892 {
3893         hammer2_chain_t *chain;
3894         hammer2_blockref_t *bref;
3895         hammer2_key_t key;
3896         hammer2_key_t key_beg;
3897         hammer2_key_t key_end;
3898         hammer2_key_t key_next;
3899         int locount;
3900         int hicount;
3901         int maxloops = 300000;
3902
3903         key = *keyp;
3904         locount = 0;
3905         hicount = 0;
3906         keybits = 64;
3907
3908         /*
3909          * Calculate the range of keys in the array being careful to skip
3910          * slots which are overridden with a deletion.
3911          */
3912         key_beg = 0;
3913         key_end = HAMMER2_KEY_MAX;
3914         hammer2_spin_ex(&parent->core.spin);
3915
3916         for (;;) {
3917                 if (--maxloops == 0) {
3918                         panic("indkey_freemap shit %p %p:%d\n",
3919                               parent, base, count);
3920                 }
3921                 chain = hammer2_combined_find(parent, base, count,
3922                                               &key_next,
3923                                               key_beg, key_end,
3924                                               &bref);
3925
3926                 /*
3927                  * Exhausted search
3928                  */
3929                 if (bref == NULL)
3930                         break;
3931
3932                 /*
3933                  * Skip deleted chains.
3934                  */
3935                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3936                         if (key_next == 0 || key_next > key_end)
3937                                 break;
3938                         key_beg = key_next;
3939                         continue;
3940                 }
3941
3942                 /*
3943                  * Use the full live (not deleted) element for the scan
3944                  * iteration.  HAMMER2 does not allow partial replacements.
3945                  *
3946                  * XXX should be built into hammer2_combined_find().
3947                  */
3948                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3949
3950                 if (keybits > bref->keybits) {
3951                         key = bref->key;
3952                         keybits = bref->keybits;
3953                 } else if (keybits == bref->keybits && bref->key < key) {
3954                         key = bref->key;
3955                 }
3956                 if (key_next == 0)
3957                         break;
3958                 key_beg = key_next;
3959         }
3960         hammer2_spin_unex(&parent->core.spin);
3961
3962         /*
3963          * Return the keybits for a higher-level FREEMAP_NODE covering
3964          * this node.
3965          */
3966         switch(keybits) {
3967         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3968                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3969                 break;
3970         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3971                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3972                 break;
3973         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3974                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3975                 break;
3976         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3977                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3978                 break;
3979         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3980                 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3981                 break;
3982         case HAMMER2_FREEMAP_LEVEL5_RADIX:
3983                 panic("hammer2_chain_indkey_freemap: level too high");
3984                 break;
3985         default:
3986                 panic("hammer2_chain_indkey_freemap: bad radix");
3987                 break;
3988         }
3989         *keyp = key;
3990
3991         return (keybits);
3992 }
3993
3994 /*
3995  * File indirect blocks
3996  *
3997  * Calculate the key/keybits for the indirect block to create by scanning
3998  * existing keys.  The key being created is also passed in *keyp and can be
3999  * inside or outside the indirect block.  Regardless, the indirect block
4000  * must hold at least two keys in order to guarantee sufficient space.
4001  *
4002  * We use a modified version of the freemap's fixed radix tree, but taylored
4003  * for file data.  Basically we configure an indirect block encompassing the
4004  * smallest key.
4005  */
4006 static int
4007 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4008                             int keybits, hammer2_blockref_t *base, int count,
4009                             int ncount)
4010 {
4011         hammer2_chain_t *chain;
4012         hammer2_blockref_t *bref;
4013         hammer2_key_t key;
4014         hammer2_key_t key_beg;
4015         hammer2_key_t key_end;
4016         hammer2_key_t key_next;
4017         int nradix;
4018         int locount;
4019         int hicount;
4020         int maxloops = 300000;
4021
4022         key = *keyp;
4023         locount = 0;
4024         hicount = 0;
4025         keybits = 64;
4026
4027         /*
4028          * Calculate the range of keys in the array being careful to skip
4029          * slots which are overridden with a deletion.
4030          *
4031          * Locate the smallest key.
4032          */
4033         key_beg = 0;
4034         key_end = HAMMER2_KEY_MAX;
4035         hammer2_spin_ex(&parent->core.spin);
4036
4037         for (;;) {
4038                 if (--maxloops == 0) {
4039                         panic("indkey_freemap shit %p %p:%d\n",
4040                               parent, base, count);
4041                 }
4042                 chain = hammer2_combined_find(parent, base, count,
4043                                               &key_next,
4044                                               key_beg, key_end,
4045                                               &bref);
4046
4047                 /*
4048                  * Exhausted search
4049                  */
4050                 if (bref == NULL)
4051                         break;
4052
4053                 /*
4054                  * Skip deleted chains.
4055                  */
4056                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4057                         if (key_next == 0 || key_next > key_end)
4058                                 break;
4059                         key_beg = key_next;
4060                         continue;
4061                 }
4062
4063                 /*
4064                  * Use the full live (not deleted) element for the scan
4065                  * iteration.  HAMMER2 does not allow partial replacements.
4066                  *
4067                  * XXX should be built into hammer2_combined_find().
4068                  */
4069                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4070
4071                 if (keybits > bref->keybits) {
4072                         key = bref->key;
4073                         keybits = bref->keybits;
4074                 } else if (keybits == bref->keybits && bref->key < key) {
4075                         key = bref->key;
4076                 }
4077                 if (key_next == 0)
4078                         break;
4079                 key_beg = key_next;
4080         }
4081         hammer2_spin_unex(&parent->core.spin);
4082
4083         /*
4084          * Calculate the static keybits for a higher-level indirect block
4085          * that contains the key.
4086          */
4087         *keyp = key;
4088
4089         switch(ncount) {
4090         case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4091                 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4092                 break;
4093         case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4094                 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4095                 break;
4096         case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4097                 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4098                 break;
4099         default:
4100                 panic("bad ncount %d\n", ncount);
4101                 nradix = 0;
4102                 break;
4103         }
4104
4105         /*
4106          * The largest radix that can be returned for an indirect block is
4107          * 63 bits.  (The largest practical indirect block radix is actually
4108          * 62 bits because the top-level inode or volume root contains four
4109          * entries, but allow 63 to be returned).
4110          */
4111         if (nradix >= 64)
4112                 nradix = 63;
4113
4114         return keybits + nradix;
4115 }
4116
4117 #if 1
4118
4119 /*
4120  * Directory indirect blocks.
4121  *
4122  * Covers both the inode index (directory of inodes), and directory contents
4123  * (filenames hardlinked to inodes).
4124  *
4125  * Because directory keys are hashed we generally try to cut the space in
4126  * half.  We accomodate the inode index (which tends to have linearly
4127  * increasing inode numbers) by ensuring that the keyspace is at least large
4128  * enough to fill up the indirect block being created.
4129  */
4130 static int
4131 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4132                          int keybits, hammer2_blockref_t *base, int count,
4133                          int ncount)
4134 {
4135         hammer2_blockref_t *bref;
4136         hammer2_chain_t *chain;
4137         hammer2_key_t key_beg;
4138         hammer2_key_t key_end;
4139         hammer2_key_t key_next;
4140         hammer2_key_t key;
4141         int nkeybits;
4142         int locount;
4143         int hicount;
4144         int maxloops = 300000;
4145
4146         /*
4147          * Shortcut if the parent is the inode.  In this situation the
4148          * parent has 4+1 directory entries and we are creating an indirect
4149          * block capable of holding many more.
4150          */
4151         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4152                 return 63;
4153         }
4154
4155         key = *keyp;
4156         locount = 0;
4157         hicount = 0;
4158
4159         /*
4160          * Calculate the range of keys in the array being careful to skip
4161          * slots which are overridden with a deletion.
4162          */
4163         key_beg = 0;
4164         key_end = HAMMER2_KEY_MAX;
4165         hammer2_spin_ex(&parent->core.spin);
4166
4167         for (;;) {
4168                 if (--maxloops == 0) {
4169                         panic("indkey_freemap shit %p %p:%d\n",
4170                               parent, base, count);
4171                 }
4172                 chain = hammer2_combined_find(parent, base, count,
4173                                               &key_next,
4174                                               key_beg, key_end,
4175                                               &bref);
4176
4177                 /*
4178                  * Exhausted search
4179                  */
4180                 if (bref == NULL)
4181                         break;
4182
4183                 /*
4184                  * Deleted object
4185                  */
4186                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4187                         if (key_next == 0 || key_next > key_end)
4188                                 break;
4189                         key_beg = key_next;
4190                         continue;
4191                 }
4192
4193                 /*
4194                  * Use the full live (not deleted) element for the scan
4195                  * iteration.  HAMMER2 does not allow partial replacements.
4196                  *
4197                  * XXX should be built into hammer2_combined_find().
4198                  */
4199                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4200
4201                 /*
4202                  * Expand our calculated key range (key, keybits) to fit
4203                  * the scanned key.  nkeybits represents the full range
4204                  * that we will later cut in half (two halves @ nkeybits - 1).
4205                  */
4206                 nkeybits = keybits;
4207                 if (nkeybits < bref->keybits) {
4208                         if (bref->keybits > 64) {
4209                                 kprintf("bad bref chain %p bref %p\n",
4210                                         chain, bref);
4211                                 Debugger("fubar");
4212                         }
4213                         nkeybits = bref->keybits;
4214                 }
4215                 while (nkeybits < 64 &&
4216                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
4217                         (key ^ bref->key)) != 0) {
4218                         ++nkeybits;
4219                 }
4220
4221                 /*
4222                  * If the new key range is larger we have to determine
4223                  * which side of the new key range the existing keys fall
4224                  * under by checking the high bit, then collapsing the
4225                  * locount into the hicount or vise-versa.
4226                  */
4227                 if (keybits != nkeybits) {
4228                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4229                                 hicount += locount;
4230                                 locount = 0;
4231                         } else {
4232                                 locount += hicount;
4233                                 hicount = 0;
4234                         }
4235                         keybits = nkeybits;
4236                 }
4237
4238                 /*
4239                  * The newly scanned key will be in the lower half or the
4240                  * upper half of the (new) key range.
4241                  */
4242                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4243                         ++hicount;
4244                 else
4245                         ++locount;
4246
4247                 if (key_next == 0)
4248                         break;
4249                 key_beg = key_next;
4250         }
4251         hammer2_spin_unex(&parent->core.spin);
4252         bref = NULL;    /* now invalid (safety) */
4253
4254         /*
4255          * Adjust keybits to represent half of the full range calculated
4256          * above (radix 63 max) for our new indirect block.
4257          */
4258         --keybits;
4259
4260         /*
4261          * Expand keybits to hold at least ncount elements.  ncount will be
4262          * a power of 2.  This is to try to completely fill leaf nodes (at
4263          * least for keys which are not hashes).
4264          *
4265          * We aren't counting 'in' or 'out', we are counting 'high side'
4266          * and 'low side' based on the bit at (1LL << keybits).  We want
4267          * everything to be inside in these cases so shift it all to
4268          * the low or high side depending on the new high bit.
4269          */
4270         while (((hammer2_key_t)1 << keybits) < ncount) {
4271                 ++keybits;
4272                 if (key & ((hammer2_key_t)1 << keybits)) {
4273                         hicount += locount;
4274                         locount = 0;
4275                 } else {
4276                         locount += hicount;
4277                         hicount = 0;
4278                 }
4279         }
4280
4281         if (hicount > locount)
4282                 key |= (hammer2_key_t)1 << keybits;
4283         else
4284                 key &= ~(hammer2_key_t)1 << keybits;
4285
4286         *keyp = key;
4287
4288         return (keybits);
4289 }
4290
4291 #else
4292
4293 /*
4294  * Directory indirect blocks.
4295  *
4296  * Covers both the inode index (directory of inodes), and directory contents
4297  * (filenames hardlinked to inodes).
4298  *
4299  * Because directory keys are hashed we generally try to cut the space in
4300  * half.  We accomodate the inode index (which tends to have linearly
4301  * increasing inode numbers) by ensuring that the keyspace is at least large
4302  * enough to fill up the indirect block being created.
4303  */
4304 static int
4305 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4306                          int keybits, hammer2_blockref_t *base, int count,
4307                          int ncount)
4308 {
4309         hammer2_blockref_t *bref;
4310         hammer2_chain_t *chain;
4311         hammer2_key_t key_beg;
4312         hammer2_key_t key_end;
4313         hammer2_key_t key_next;
4314         hammer2_key_t key;
4315         int nkeybits;
4316         int locount;
4317         int hicount;
4318         int maxloops = 300000;
4319
4320         /*
4321          * Shortcut if the parent is the inode.  In this situation the
4322          * parent has 4+1 directory entries and we are creating an indirect
4323          * block capable of holding many more.
4324          */
4325         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4326                 return 63;
4327         }
4328
4329         key = *keyp;
4330         locount = 0;
4331         hicount = 0;
4332
4333         /*
4334          * Calculate the range of keys in the array being careful to skip
4335          * slots which are overridden with a deletion.
4336          */
4337         key_beg = 0;
4338         key_end = HAMMER2_KEY_MAX;
4339         hammer2_spin_ex(&parent->core.spin);
4340
4341         for (;;) {
4342                 if (--maxloops == 0) {
4343                         panic("indkey_freemap shit %p %p:%d\n",
4344                               parent, base, count);
4345                 }
4346                 chain = hammer2_combined_find(parent, base, count,
4347                                               &key_next,
4348                                               key_beg, key_end,
4349                                               &bref);
4350
4351                 /*
4352                  * Exhausted search
4353                  */
4354                 if (bref == NULL)
4355                         break;
4356
4357                 /*
4358                  * Deleted object
4359                  */
4360                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4361                         if (key_next == 0 || key_next > key_end)
4362                                 break;
4363                         key_beg = key_next;
4364                         continue;
4365                 }
4366
4367                 /*
4368                  * Use the full live (not deleted) element for the scan
4369                  * iteration.  HAMMER2 does not allow partial replacements.
4370                  *
4371                  * XXX should be built into hammer2_combined_find().
4372                  */
4373                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4374
4375                 /*
4376                  * Expand our calculated key range (key, keybits) to fit
4377                  * the scanned key.  nkeybits represents the full range
4378                  * that we will later cut in half (two halves @ nkeybits - 1).
4379                  */
4380                 nkeybits = keybits;
4381                 if (nkeybits < bref->keybits) {
4382                         if (bref->keybits > 64) {
4383                                 kprintf("bad bref chain %p bref %p\n",
4384                                         chain, bref);
4385                                 Debugger("fubar");
4386                         }
4387                         nkeybits = bref->keybits;
4388                 }
4389                 while (nkeybits < 64 &&
4390                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
4391                         (key ^ bref->key)) != 0) {
4392                         ++nkeybits;
4393                 }
4394
4395                 /*
4396                  * If the new key range is larger we have to determine
4397                  * which side of the new key range the existing keys fall
4398                  * under by checking the high bit, then collapsing the
4399                  * locount into the hicount or vise-versa.
4400                  */
4401                 if (keybits != nkeybits) {
4402                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4403                                 hicount += locount;
4404                                 locount = 0;
4405                         } else {
4406                                 locount += hicount;
4407                                 hicount = 0;
4408                         }
4409                         keybits = nkeybits;
4410                 }
4411
4412                 /*
4413                  * The newly scanned key will be in the lower half or the
4414                  * upper half of the (new) key range.
4415                  */
4416                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4417                         ++hicount;
4418                 else
4419                         ++locount;
4420
4421                 if (key_next == 0)
4422                         break;
4423                 key_beg = key_next;
4424         }
4425         hammer2_spin_unex(&parent->core.spin);
4426         bref = NULL;    /* now invalid (safety) */
4427
4428         /*
4429          * Adjust keybits to represent half of the full range calculated
4430          * above (radix 63 max) for our new indirect block.
4431          */
4432         --keybits;
4433
4434         /*
4435          * Expand keybits to hold at least ncount elements.  ncount will be
4436          * a power of 2.  This is to try to completely fill leaf nodes (at
4437          * least for keys which are not hashes).
4438          *
4439          * We aren't counting 'in' or 'out', we are counting 'high side'
4440          * and 'low side' based on the bit at (1LL << keybits).  We want
4441          * everything to be inside in these cases so shift it all to
4442          * the low or high side depending on the new high bit.
4443          */
4444         while (((hammer2_key_t)1 << keybits) < ncount) {
4445                 ++keybits;
4446                 if (key & ((hammer2_key_t)1 << keybits)) {
4447                         hicount += locount;
4448                         locount = 0;
4449                 } else {
4450                         locount += hicount;
4451                         hicount = 0;
4452                 }
4453         }
4454
4455         if (hicount > locount)
4456                 key |= (hammer2_key_t)1 << keybits;
4457         else
4458                 key &= ~(hammer2_key_t)1 << keybits;
4459
4460         *keyp = key;
4461
4462         return (keybits);
4463 }
4464
4465 #endif
4466
4467 /*
4468  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4469  * it exists.
4470  *
4471  * Both parent and chain must be locked exclusively.
4472  *
4473  * This function will modify the parent if the blockref requires removal
4474  * from the parent's block table.
4475  *
4476  * This function is NOT recursive.  Any entity already pushed into the
4477  * chain (such as an inode) may still need visibility into its contents,
4478  * as well as the ability to read and modify the contents.  For example,
4479  * for an unlinked file which is still open.
4480  *
4481  * Also note that the flusher is responsible for cleaning up empty
4482  * indirect blocks.
4483  */
4484 void
4485 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4486                      hammer2_tid_t mtid, int flags)
4487 {
4488         KKASSERT(hammer2_mtx_owned(&chain->lock));
4489
4490         /*
4491          * Nothing to do if already marked.
4492          *
4493          * We need the spinlock on the core whos RBTREE contains chain
4494          * to protect against races.
4495          */
4496         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4497                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4498                          chain->parent == parent);
4499                 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4500         }
4501
4502         /*
4503          * Permanent deletions mark the chain as destroyed.
4504          */
4505         if (flags & HAMMER2_DELETE_PERMANENT)
4506                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4507         hammer2_chain_setflush(chain);
4508 }
4509
4510 /*
4511  * Returns the index of the nearest element in the blockref array >= elm.
4512  * Returns (count) if no element could be found.
4513  *
4514  * Sets *key_nextp to the next key for loop purposes but does not modify
4515  * it if the next key would be higher than the current value of *key_nextp.
4516  * Note that *key_nexp can overflow to 0, which should be tested by the
4517  * caller.
4518  *
4519  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
4520  *           held through the operation.
4521  */
4522 static int
4523 hammer2_base_find(hammer2_chain_t *parent,
4524                   hammer2_blockref_t *base, int count,
4525                   hammer2_key_t *key_nextp,
4526                   hammer2_key_t key_beg, hammer2_key_t key_end)
4527 {
4528         hammer2_blockref_t *scan;
4529         hammer2_key_t scan_end;
4530         int i;
4531         int limit;
4532
4533         /*
4534          * Require the live chain's already have their core's counted
4535          * so we can optimize operations.
4536          */
4537         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4538
4539         /*
4540          * Degenerate case
4541          */
4542         if (count == 0 || base == NULL)
4543                 return(count);
4544
4545         /*
4546          * Sequential optimization using parent->cache_index.  This is
4547          * the most likely scenario.
4548          *
4549          * We can avoid trailing empty entries on live chains, otherwise
4550          * we might have to check the whole block array.
4551          */
4552         i = parent->cache_index;        /* SMP RACE OK */
4553         cpu_ccfence();
4554         limit = parent->core.live_zero;
4555         if (i >= limit)
4556                 i = limit - 1;
4557         if (i < 0)
4558                 i = 0;
4559         KKASSERT(i < count);
4560
4561         /*
4562          * Search backwards
4563          */
4564         scan = &base[i];
4565         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4566                 --scan;
4567                 --i;
4568         }
4569         parent->cache_index = i;
4570
4571         /*
4572          * Search forwards, stop when we find a scan element which
4573          * encloses the key or until we know that there are no further
4574          * elements.
4575          */
4576         while (i < count) {
4577                 if (scan->type != 0) {
4578                         scan_end = scan->key +
4579                                    ((hammer2_key_t)1 << scan->keybits) - 1;
4580                         if (scan->key > key_beg || scan_end >= key_beg)
4581                                 break;
4582                 }
4583                 if (i >= limit)
4584                         return (count);
4585                 ++scan;
4586                 ++i;
4587         }
4588         if (i != count) {
4589                 parent->cache_index = i;
4590                 if (i >= limit) {
4591                         i = count;
4592                 } else {
4593                         scan_end = scan->key +
4594                                    ((hammer2_key_t)1 << scan->keybits);
4595                         if (scan_end && (*key_nextp > scan_end ||
4596                                          *key_nextp == 0)) {
4597                                 *key_nextp = scan_end;
4598                         }
4599                 }
4600         }
4601         return (i);
4602 }
4603
4604 /*
4605  * Do a combined search and return the next match either from the blockref
4606  * array or from the in-memory chain.  Sets *bresp to the returned bref in
4607  * both cases, or sets it to NULL if the search exhausted.  Only returns
4608  * a non-NULL chain if the search matched from the in-memory chain.
4609  *
4610  * When no in-memory chain has been found and a non-NULL bref is returned
4611  * in *bresp.
4612  *
4613  *
4614  * The returned chain is not locked or referenced.  Use the returned bref
4615  * to determine if the search exhausted or not.  Iterate if the base find
4616  * is chosen but matches a deleted chain.
4617  *
4618  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
4619  *           held through the operation.
4620  */
4621 static hammer2_chain_t *
4622 hammer2_combined_find(hammer2_chain_t *parent,
4623                       hammer2_blockref_t *base, int count,
4624                       hammer2_key_t *key_nextp,
4625                       hammer2_key_t key_beg, hammer2_key_t key_end,
4626                       hammer2_blockref_t **bresp)
4627 {
4628         hammer2_blockref_t *bref;
4629         hammer2_chain_t *chain;
4630         int i;
4631
4632         /*
4633          * Lookup in block array and in rbtree.
4634          */
4635         *key_nextp = key_end + 1;
4636         i = hammer2_base_find(parent, base, count, key_nextp,
4637                               key_beg, key_end);
4638         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4639
4640         /*
4641          * Neither matched
4642          */
4643         if (i == count && chain == NULL) {
4644                 *bresp = NULL;
4645                 return(NULL);
4646         }
4647
4648         /*
4649          * Only chain matched.
4650          */
4651         if (i == count) {
4652                 bref = &chain->bref;
4653                 goto found;
4654         }
4655
4656         /*
4657          * Only blockref matched.
4658          */
4659         if (chain == NULL) {
4660                 bref = &base[i];
4661                 goto found;
4662         }
4663
4664         /*
4665          * Both in-memory and blockref matched, select the nearer element.
4666          *
4667          * If both are flush with the left-hand side or both are the
4668          * same distance away, select the chain.  In this situation the
4669          * chain must have been loaded from the matching blockmap.
4670          */
4671         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4672             chain->bref.key == base[i].key) {
4673                 KKASSERT(chain->bref.key == base[i].key);
4674                 bref = &chain->bref;
4675                 goto found;
4676         }
4677
4678         /*
4679          * Select the nearer key
4680          */
4681         if (chain->bref.key < base[i].key) {
4682                 bref = &chain->bref;
4683         } else {
4684                 bref = &base[i];
4685                 chain = NULL;
4686         }
4687
4688         /*
4689          * If the bref is out of bounds we've exhausted our search.
4690          */
4691 found:
4692         if (bref->key > key_end) {
4693                 *bresp = NULL;
4694                 chain = NULL;
4695         } else {
4696                 *bresp = bref;
4697         }
4698         return(chain);
4699 }
4700
4701 /*
4702  * Locate the specified block array element and delete it.  The element
4703  * must exist.
4704  *
4705  * The spin lock on the related chain must be held.
4706  *
4707  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4708  *       need to be adjusted when we commit the media change.
4709  */
4710 void
4711 hammer2_base_delete(hammer2_chain_t *parent,
4712                     hammer2_blockref_t *base, int count,
4713                     hammer2_chain_t *chain)
4714 {
4715         hammer2_blockref_t *elm = &chain->bref;
4716         hammer2_blockref_t *scan;
4717         hammer2_key_t key_next;
4718         int i;
4719
4720         /*
4721          * Delete element.  Expect the element to exist.
4722          *
4723          * XXX see caller, flush code not yet sophisticated enough to prevent
4724          *     re-flushed in some cases.
4725          */
4726         key_next = 0; /* max range */
4727         i = hammer2_base_find(parent, base, count, &key_next,
4728                               elm->key, elm->key);
4729         scan = &base[i];
4730         if (i == count || scan->type == 0 ||
4731             scan->key != elm->key ||
4732             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4733              scan->keybits != elm->keybits)) {
4734                 hammer2_spin_unex(&parent->core.spin);
4735                 panic("delete base %p element not found at %d/%d elm %p\n",
4736                       base, i, count, elm);
4737                 return;
4738         }
4739
4740         /*
4741          * Update stats and zero the entry.
4742          *
4743          * NOTE: Handle radix == 0 (0 bytes) case.
4744          */
4745         if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4746                 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4747                                 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4748         }
4749         switch(scan->type) {
4750         case HAMMER2_BREF_TYPE_INODE:
4751                 parent->bref.embed.stats.inode_count -= 1;
4752                 /* fall through */
4753         case HAMMER2_BREF_TYPE_DATA:
4754         case HAMMER2_BREF_TYPE_INDIRECT:
4755                 parent->bref.embed.stats.data_count -=
4756                         scan->embed.stats.data_count;
4757                 parent->bref.embed.stats.inode_count -=
4758                         scan->embed.stats.inode_count;
4759                 break;
4760         default:
4761                 break;
4762         }
4763
4764         bzero(scan, sizeof(*scan));
4765
4766         /*
4767          * We can only optimize parent->core.live_zero for live chains.
4768          */
4769         if (parent->core.live_zero == i + 1) {
4770                 while (--i >= 0 && base[i].type == 0)
4771                         ;
4772                 parent->core.live_zero = i + 1;
4773         }
4774
4775         /*
4776          * Clear appropriate blockmap flags in chain.
4777          */
4778         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4779                                         HAMMER2_CHAIN_BMAPUPD);
4780 }
4781
4782 /*
4783  * Insert the specified element.  The block array must not already have the
4784  * element and must have space available for the insertion.
4785  *
4786  * The spin lock on the related chain must be held.
4787  *
4788  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4789  *       need to be adjusted when we commit the media change.
4790  */
4791 void
4792 hammer2_base_insert(hammer2_chain_t *parent,
4793                     hammer2_blockref_t *base, int count,
4794                     hammer2_chain_t *chain)
4795 {
4796         hammer2_blockref_t *elm = &chain->bref;
4797         hammer2_key_t key_next;
4798         hammer2_key_t xkey;
4799         int i;
4800         int j;
4801         int k;
4802         int l;
4803         int u = 1;
4804
4805         /*
4806          * Insert new element.  Expect the element to not already exist
4807          * unless we are replacing it.
4808          *
4809          * XXX see caller, flush code not yet sophisticated enough to prevent
4810          *     re-flushed in some cases.
4811          */
4812         key_next = 0; /* max range */
4813         i = hammer2_base_find(parent, base, count, &key_next,
4814                               elm->key, elm->key);
4815
4816         /*
4817          * Shortcut fill optimization, typical ordered insertion(s) may not
4818          * require a search.
4819          */
4820         KKASSERT(i >= 0 && i <= count);
4821
4822         /*
4823          * Set appropriate blockmap flags in chain.
4824          */
4825         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4826
4827         /*
4828          * Update stats and zero the entry
4829          */
4830         if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4831                 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4832                                 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4833         }
4834         switch(elm->type) {
4835         case HAMMER2_BREF_TYPE_INODE:
4836                 parent->bref.embed.stats.inode_count += 1;
4837                 /* fall through */
4838         case HAMMER2_BREF_TYPE_DATA:
4839         case HAMMER2_BREF_TYPE_INDIRECT:
4840                 parent->bref.embed.stats.data_count +=
4841                         elm->embed.stats.data_count;
4842                 parent->bref.embed.stats.inode_count +=
4843                         elm->embed.stats.inode_count;
4844                 break;
4845         default:
4846                 break;
4847         }
4848
4849
4850         /*
4851          * We can only optimize parent->core.live_zero for live chains.
4852          */
4853         if (i == count && parent->core.live_zero < count) {
4854                 i = parent->core.live_zero++;
4855                 base[i] = *elm;
4856                 return;
4857         }
4858
4859         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4860         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4861                 hammer2_spin_unex(&parent->core.spin);
4862                 panic("insert base %p overlapping elements at %d elm %p\n",
4863                       base, i, elm);
4864         }
4865
4866         /*
4867          * Try to find an empty slot before or after.
4868          */
4869         j = i;
4870         k = i;
4871         while (j > 0 || k < count) {
4872                 --j;
4873                 if (j >= 0 && base[j].type == 0) {
4874                         if (j == i - 1) {
4875                                 base[j] = *elm;
4876                         } else {
4877                                 bcopy(&base[j+1], &base[j],
4878                                       (i - j - 1) * sizeof(*base));
4879                                 base[i - 1] = *elm;
4880                         }
4881                         goto validate;
4882                 }
4883                 ++k;
4884                 if (k < count && base[k].type == 0) {
4885                         bcopy(&base[i], &base[i+1],
4886                               (k - i) * sizeof(hammer2_blockref_t));
4887                         base[i] = *elm;
4888
4889                         /*
4890                          * We can only update parent->core.live_zero for live
4891                          * chains.
4892                          */
4893                         if (parent->core.live_zero <= k)
4894                                 parent->core.live_zero = k + 1;
4895                         u = 2;
4896                         goto validate;
4897                 }
4898         }
4899         panic("hammer2_base_insert: no room!");
4900
4901         /*
4902          * Debugging
4903          */
4904 validate:
4905         key_next = 0;
4906         for (l = 0; l < count; ++l) {
4907                 if (base[l].type) {
4908                         key_next = base[l].key +
4909                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4910                         break;
4911                 }
4912         }
4913         while (++l < count) {
4914                 if (base[l].type) {
4915                         if (base[l].key <= key_next)
4916                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4917                         key_next = base[l].key +
4918                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4919
4920                 }
4921         }
4922
4923 }
4924
4925 #if 0
4926
4927 /*
4928  * Sort the blockref array for the chain.  Used by the flush code to
4929  * sort the blockref[] array.
4930  *
4931  * The chain must be exclusively locked AND spin-locked.
4932  */
4933 typedef hammer2_blockref_t *hammer2_blockref_p;
4934
4935 static
4936 int
4937 hammer2_base_sort_callback(const void *v1, const void *v2)
4938 {
4939         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4940         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4941
4942         /*
4943          * Make sure empty elements are placed at the end of the array
4944          */
4945         if (bref1->type == 0) {
4946                 if (bref2->type == 0)
4947                         return(0);
4948                 return(1);
4949         } else if (bref2->type == 0) {
4950                 return(-1);
4951         }
4952
4953         /*
4954          * Sort by key
4955          */
4956         if (bref1->key < bref2->key)
4957                 return(-1);
4958         if (bref1->key > bref2->key)
4959                 return(1);
4960         return(0);
4961 }
4962
4963 void
4964 hammer2_base_sort(hammer2_chain_t *chain)
4965 {
4966         hammer2_blockref_t *base;
4967         int count;
4968
4969         switch(chain->bref.type) {
4970         case HAMMER2_BREF_TYPE_INODE:
4971                 /*
4972                  * Special shortcut for embedded data returns the inode
4973                  * itself.  Callers must detect this condition and access
4974                  * the embedded data (the strategy code does this for us).
4975                  *
4976                  * This is only applicable to regular files and softlinks.
4977                  */
4978                 if (chain->data->ipdata.meta.op_flags &
4979                     HAMMER2_OPFLAG_DIRECTDATA) {
4980                         return;
4981                 }
4982                 base = &chain->data->ipdata.u.blockset.blockref[0];
4983                 count = HAMMER2_SET_COUNT;
4984                 break;
4985         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4986         case HAMMER2_BREF_TYPE_INDIRECT:
4987                 /*
4988                  * Optimize indirect blocks in the INITIAL state to avoid
4989                  * I/O.
4990                  */
4991                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4992                 base = &chain->data->npdata[0];
4993                 count = chain->bytes / sizeof(hammer2_blockref_t);
4994                 break;
4995         case HAMMER2_BREF_TYPE_VOLUME:
4996                 base = &chain->data->voldata.sroot_blockset.blockref[0];
4997                 count = HAMMER2_SET_COUNT;
4998                 break;
4999         case HAMMER2_BREF_TYPE_FREEMAP:
5000                 base = &chain->data->blkset.blockref[0];
5001                 count = HAMMER2_SET_COUNT;
5002                 break;
5003         default:
5004                 kprintf("hammer2_chain_lookup: unrecognized "
5005                         "blockref(A) type: %d",
5006                         chain->bref.type);
5007                 while (1)
5008                         tsleep(&base, 0, "dead", 0);
5009                 panic("hammer2_chain_lookup: unrecognized "
5010                       "blockref(A) type: %d",
5011                       chain->bref.type);
5012                 base = NULL;    /* safety */
5013                 count = 0;      /* safety */
5014         }
5015         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5016 }
5017
5018 #endif
5019
5020 /*
5021  * Chain memory management
5022  */
5023 void
5024 hammer2_chain_wait(hammer2_chain_t *chain)
5025 {
5026         tsleep(chain, 0, "chnflw", 1);
5027 }
5028
5029 const hammer2_media_data_t *
5030 hammer2_chain_rdata(hammer2_chain_t *chain)
5031 {
5032         KKASSERT(chain->data != NULL);
5033         return (chain->data);
5034 }
5035
5036 hammer2_media_data_t *
5037 hammer2_chain_wdata(hammer2_chain_t *chain)
5038 {
5039         KKASSERT(chain->data != NULL);
5040         return (chain->data);
5041 }
5042
5043 /*
5044  * Set the check data for a chain.  This can be a heavy-weight operation
5045  * and typically only runs on-flush.  For file data check data is calculated
5046  * when the logical buffers are flushed.
5047  */
5048 void
5049 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5050 {
5051         chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5052
5053         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5054         case HAMMER2_CHECK_NONE:
5055                 break;
5056         case HAMMER2_CHECK_DISABLED:
5057                 break;
5058         case HAMMER2_CHECK_ISCSI32:
5059                 chain->bref.check.iscsi32.value =
5060                         hammer2_icrc32(bdata, chain->bytes);
5061                 break;
5062         case HAMMER2_CHECK_XXHASH64:
5063                 chain->bref.check.xxhash64.value =
5064                         XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5065                 break;
5066         case HAMMER2_CHECK_SHA192:
5067                 {
5068                         SHA256_CTX hash_ctx;
5069                         union {
5070                                 uint8_t digest[SHA256_DIGEST_LENGTH];
5071                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5072                         } u;
5073
5074                         SHA256_Init(&hash_ctx);
5075                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
5076                         SHA256_Final(u.digest, &hash_ctx);
5077                         u.digest64[2] ^= u.digest64[3];
5078                         bcopy(u.digest,
5079                               chain->bref.check.sha192.data,
5080                               sizeof(chain->bref.check.sha192.data));
5081                 }
5082                 break;
5083         case HAMMER2_CHECK_FREEMAP:
5084                 chain->bref.check.freemap.icrc32 =
5085                         hammer2_icrc32(bdata, chain->bytes);
5086                 break;
5087         default:
5088                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5089                         chain->bref.methods);
5090                 break;
5091         }
5092 }
5093
5094 int
5095 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5096 {
5097         uint32_t check32;
5098         uint64_t check64;
5099         int r;
5100
5101         if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5102                 return 1;
5103
5104         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5105         case HAMMER2_CHECK_NONE:
5106                 r = 1;
5107                 break;
5108         case HAMMER2_CHECK_DISABLED:
5109                 r = 1;
5110                 break;
5111         case HAMMER2_CHECK_ISCSI32:
5112                 check32 = hammer2_icrc32(bdata, chain->bytes);
5113                 r = (chain->bref.check.iscsi32.value == check32);
5114                 if (r == 0) {
5115                         kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5116                                 "(flags=%08x, bref/data %08x/%08x)\n",
5117                                 chain->bref.data_off,
5118                                 chain->bref.type,
5119                                 chain->bref.methods,
5120                                 chain->flags,
5121                                 chain->bref.check.iscsi32.value,
5122                                 check32);
5123                 }
5124                 hammer2_check_icrc32 += chain->bytes;
5125                 break;
5126         case HAMMER2_CHECK_XXHASH64:
5127                 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5128                 r = (chain->bref.check.xxhash64.value == check64);
5129                 if (r == 0) {
5130                         kprintf("chain %016jx.%02x key=%016jx "
5131                                 "meth=%02x CHECK FAIL "
5132                                 "(flags=%08x, bref/data %016jx/%016jx)\n",
5133                                 chain->bref.data_off,
5134                                 chain->bref.type,
5135                                 chain->bref.key,
5136                                 chain->bref.methods,
5137                                 chain->flags,
5138                                 chain->bref.check.xxhash64.value,
5139                                 check64);
5140                 }
5141                 hammer2_check_xxhash64 += chain->bytes;
5142                 break;
5143         case HAMMER2_CHECK_SHA192:
5144                 {
5145                         SHA256_CTX hash_ctx;
5146                         union {
5147                                 uint8_t digest[SHA256_DIGEST_LENGTH];
5148                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5149                         } u;
5150
5151                         SHA256_Init(&hash_ctx);
5152                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
5153                         SHA256_Final(u.digest, &hash_ctx);
5154                         u.digest64[2] ^= u.digest64[3];
5155                         if (bcmp(u.digest,
5156                                  chain->bref.check.sha192.data,
5157                                  sizeof(chain->bref.check.sha192.data)) == 0) {
5158                                 r = 1;
5159                         } else {
5160                                 r = 0;
5161                                 kprintf("chain %016jx.%02x meth=%02x "
5162                                         "CHECK FAIL\n",
5163                                         chain->bref.data_off,
5164                                         chain->bref.type,
5165                                         chain->bref.methods);
5166                         }
5167                 }
5168                 break;
5169         case HAMMER2_CHECK_FREEMAP:
5170                 r = (chain->bref.check.freemap.icrc32 ==
5171                      hammer2_icrc32(bdata, chain->bytes));
5172                 if (r == 0) {
5173                         kprintf("chain %016jx.%02x meth=%02x "
5174                                 "CHECK FAIL\n",
5175                                 chain->bref.data_off,
5176                                 chain->bref.type,
5177                                 chain->bref.methods);
5178                         kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5179                                 chain->bref.check.freemap.icrc32,
5180                                 hammer2_icrc32(bdata, chain->bytes),
5181                                                chain->bytes);
5182                         if (chain->dio)
5183                                 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5184                                         chain->dio, chain->dio->bp->b_loffset,
5185                                         chain->dio->bp->b_bufsize, bdata,
5186                                         chain->dio->bp->b_data);
5187                 }
5188
5189                 break;
5190         default:
5191                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5192                         chain->bref.methods);
5193                 r = 1;
5194                 break;
5195         }
5196         return r;
5197 }
5198
5199 /*
5200  * Acquire the chain and parent representing the specified inode for the
5201  * device at the specified cluster index.
5202  *
5203  * The flags passed in are LOOKUP flags, not RESOLVE flags.
5204  *
5205  * If we are unable to locate the hardlink, INVAL is returned and *chainp
5206  * will be NULL.  *parentp may still be set error or not, or NULL if the
5207  * parent itself could not be resolved.
5208  *
5209  * Caller must pass-in a valid or NULL *parentp or *chainp.  The passed-in
5210  * *parentp and *chainp will be unlocked if not NULL.
5211  */
5212 int
5213 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5214                          int clindex, int flags,
5215                          hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5216 {
5217         hammer2_chain_t *parent;
5218         hammer2_chain_t *rchain;
5219         hammer2_key_t key_dummy;
5220         int resolve_flags;
5221
5222         resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5223                         HAMMER2_RESOLVE_SHARED : 0;
5224
5225         /*
5226          * Caller expects us to replace these.
5227          */
5228         if (*chainp) {
5229                 hammer2_chain_unlock(*chainp);
5230                 hammer2_chain_drop(*chainp);
5231                 *chainp = NULL;
5232         }
5233         if (*parentp) {
5234                 hammer2_chain_unlock(*parentp);
5235                 hammer2_chain_drop(*parentp);
5236                 *parentp = NULL;
5237         }
5238
5239         /*
5240          * Inodes hang off of the iroot (bit 63 is clear, differentiating
5241          * inodes from root directory entries in the key lookup).
5242          */
5243         parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5244         rchain = NULL;
5245         if (parent) {
5246                 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5247                                               inum, inum,
5248                                               flags);
5249         }
5250         *parentp = parent;
5251         *chainp = rchain;
5252
5253         return (rchain ? 0 : EINVAL);
5254 }
5255
5256 /*
5257  * Used by the bulkscan code to snapshot the synchronized storage for
5258  * a volume, allowing it to be scanned concurrently against normal
5259  * operation.
5260  */
5261 hammer2_chain_t *
5262 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5263 {
5264         hammer2_chain_t *copy;
5265
5266         copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5267         copy->data = kmalloc(sizeof(copy->data->voldata),
5268                              hmp->mchain,
5269                              M_WAITOK | M_ZERO);
5270         hammer2_voldata_lock(hmp);
5271         copy->data->voldata = hmp->volsync;
5272         hammer2_voldata_unlock(hmp);
5273
5274         return copy;
5275 }
5276
5277 void
5278 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5279 {
5280         KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5281         KKASSERT(copy->data);
5282         kfree(copy->data, copy->hmp->mchain);
5283         copy->data = NULL;
5284         atomic_add_long(&hammer2_chain_allocs, -1);
5285         hammer2_chain_drop(copy);
5286 }
5287
5288 /*
5289  * Create a snapshot of the specified (chain) with the specified label.
5290  * The originating hammer2_inode must be exclusively locked for
5291  * safety.  The device's bulklk should be held by the caller.  The caller
5292  * is responsible for synchronizing the filesystem to storage before
5293  * taking the snapshot.
5294  */
5295 int
5296 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5297                        hammer2_tid_t mtid)
5298 {
5299         hammer2_dev_t *hmp;
5300         const hammer2_inode_data_t *ripdata;
5301         hammer2_inode_data_t *wipdata;
5302         hammer2_chain_t *nchain;
5303         hammer2_inode_t *nip;
5304         size_t name_len;
5305         hammer2_key_t lhc;
5306         struct vattr vat;
5307 #if 0
5308         uuid_t opfs_clid;
5309 #endif
5310         int error;
5311
5312         kprintf("snapshot %s\n", pmp->name);
5313
5314         name_len = strlen(pmp->name);
5315         lhc = hammer2_dirhash(pmp->name, name_len);
5316
5317         /*
5318          * Get the clid
5319          */
5320         ripdata = &chain->data->ipdata;
5321 #if 0
5322         opfs_clid = ripdata->meta.pfs_clid;
5323 #endif
5324         hmp = chain->hmp;
5325
5326         /*
5327          * Create the snapshot directory under the super-root
5328          *
5329          * Set PFS type, generate a unique filesystem id, and generate
5330          * a cluster id.  Use the same clid when snapshotting a PFS root,
5331          * which theoretically allows the snapshot to be used as part of
5332          * the same cluster (perhaps as a cache).
5333          *
5334          * Copy the (flushed) blockref array.  Theoretically we could use
5335          * chain_duplicate() but it becomes difficult to disentangle
5336          * the shared core so for now just brute-force it.
5337          */
5338         VATTR_NULL(&vat);
5339         vat.va_type = VDIR;
5340         vat.va_mode = 0755;
5341         hammer2_chain_unlock(chain);
5342         nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5343                                    &vat, proc0.p_ucred,
5344                                    pmp->name, name_len, 0,
5345                                    1, 0, 0,
5346                                    HAMMER2_INSERT_PFSROOT, &error);
5347         hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5348
5349         if (nip) {
5350                 hammer2_inode_modify(nip);
5351                 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5352                 hammer2_chain_modify(nchain, mtid, 0, 0);
5353                 wipdata = &nchain->data->ipdata;
5354
5355                 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5356                 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5357                 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5358                 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5359
5360                 /*
5361                  * Give the snapshot its own private cluster id.  As a
5362                  * snapshot no further synchronization with the original
5363                  * cluster will be done.
5364                  */
5365 #if 0
5366                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5367                         nip->meta.pfs_clid = opfs_clid;
5368                 else
5369                         kern_uuidgen(&nip->meta.pfs_clid, 1);
5370 #endif
5371                 kern_uuidgen(&nip->meta.pfs_clid, 1);
5372                 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5373
5374                 /* XXX hack blockset copy */
5375                 /* XXX doesn't work with real cluster */
5376                 wipdata->meta = nip->meta;
5377                 wipdata->u.blockset = ripdata->u.blockset;
5378
5379                 hammer2_flush(nchain, 1);
5380                 KKASSERT(wipdata == &nchain->data->ipdata);
5381                 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5382
5383                 hammer2_chain_unlock(nchain);
5384                 hammer2_chain_drop(nchain);
5385                 hammer2_inode_chain_sync(nip);
5386                 hammer2_inode_unlock(nip);
5387                 hammer2_inode_run_sideq(hmp->spmp);
5388         }
5389         return (error);
5390 }
5391
5392 /*
5393  * Returns non-zero if the chain (INODE or DIRENT) matches the
5394  * filename.
5395  */
5396 int
5397 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5398                           size_t name_len)
5399 {
5400         const hammer2_inode_data_t *ripdata;
5401         const hammer2_dirent_head_t *den;
5402
5403         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5404                 ripdata = &chain->data->ipdata;
5405                 if (ripdata->meta.name_len == name_len &&
5406                     bcmp(ripdata->filename, name, name_len) == 0) {
5407                         return 1;
5408                 }
5409         }
5410         if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5411            chain->bref.embed.dirent.namlen == name_len) {
5412                 den = &chain->bref.embed.dirent;
5413                 if (name_len > sizeof(chain->bref.check.buf) &&
5414                     bcmp(chain->data->buf, name, name_len) == 0) {
5415                         return 1;
5416                 }
5417                 if (name_len <= sizeof(chain->bref.check.buf) &&
5418                     bcmp(chain->bref.check.buf, name, name_len) == 0) {
5419                         return 1;
5420                 }
5421         }
5422         return 0;
5423 }