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