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