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