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