33a6396ea8cb234b1694d30076398ee175bbdf29
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2015 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  * and Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  * 3. Neither the name of The DragonFly Project nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific, prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
26  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 /*
36  * This subsystem implements most of the core support functions for
37  * the hammer2_chain structure.
38  *
39  * Chains are the in-memory version on media objects (volume header, inodes,
40  * indirect blocks, data blocks, etc).  Chains represent a portion of the
41  * HAMMER2 topology.
42  *
43  * Chains are no-longer delete-duplicated.  Instead, the original in-memory
44  * chain will be moved along with its block reference (e.g. for things like
45  * renames, hardlink operations, modifications, etc), and will be indexed
46  * on a secondary list for flush handling instead of propagating a flag
47  * upward to the root.
48  *
49  * Concurrent front-end operations can still run against backend flushes
50  * as long as they do not cross the current flush boundary.  An operation
51  * running above the current flush (in areas not yet flushed) can become
52  * part of the current flush while ano peration running below the current
53  * flush can become part of the next flush.
54  */
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
59 #include <sys/lock.h>
60 #include <sys/kern_syscall.h>
61 #include <sys/uuid.h>
62
63 #include <crypto/sha2/sha2.h>
64
65 #include "hammer2.h"
66
67 static int hammer2_indirect_optimize;   /* XXX SYSCTL */
68
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70                 hammer2_chain_t *parent,
71                 hammer2_key_t key, int keybits,
72                 hammer2_tid_t mtid, int for_type, int *errorp);
73 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
74 static hammer2_chain_t *hammer2_combined_find(
75                 hammer2_chain_t *parent,
76                 hammer2_blockref_t *base, int count,
77                 int *cache_indexp, hammer2_key_t *key_nextp,
78                 hammer2_key_t key_beg, hammer2_key_t key_end,
79                 hammer2_blockref_t **bresp);
80
81 /*
82  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
83  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
84  * dbtree or to dbq.
85  *
86  * Chains in delete-duplicate sequences can always iterate through core_entry
87  * to locate the live version of the chain.
88  */
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
90
91 int
92 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
93 {
94         hammer2_key_t c1_beg;
95         hammer2_key_t c1_end;
96         hammer2_key_t c2_beg;
97         hammer2_key_t c2_end;
98
99         /*
100          * Compare chains.  Overlaps are not supposed to happen and catch
101          * any software issues early we count overlaps as a match.
102          */
103         c1_beg = chain1->bref.key;
104         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
105         c2_beg = chain2->bref.key;
106         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
107
108         if (c1_end < c2_beg)    /* fully to the left */
109                 return(-1);
110         if (c1_beg > c2_end)    /* fully to the right */
111                 return(1);
112         return(0);              /* overlap (must not cross edge boundary) */
113 }
114
115 static __inline
116 int
117 hammer2_isclusterable(hammer2_chain_t *chain)
118 {
119         if (hammer2_cluster_enable) {
120                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
121                     chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
122                     chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
123                         return(1);
124                 }
125         }
126         return(0);
127 }
128
129 /*
130  * Make a chain visible to the flusher.  The flusher needs to be able to
131  * do flushes of subdirectory chains or single files so it does a top-down
132  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
133  * or UPDATE chains and flushes back up the chain to the volume root.
134  *
135  * This routine sets ONFLUSH upward until it hits the volume root.  For
136  * simplicity we ignore PFSROOT boundaries whos rules can be complex.
137  * Extra ONFLUSH flagging doesn't hurt the filesystem.
138  */
139 void
140 hammer2_chain_setflush(hammer2_chain_t *chain)
141 {
142         hammer2_chain_t *parent;
143
144         if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145                 hammer2_spin_sh(&chain->core.spin);
146                 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
147                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
148                         if ((parent = chain->parent) == NULL)
149                                 break;
150                         hammer2_spin_sh(&parent->core.spin);
151                         hammer2_spin_unsh(&chain->core.spin);
152                         chain = parent;
153                 }
154                 hammer2_spin_unsh(&chain->core.spin);
155         }
156 }
157
158 /*
159  * Allocate a new disconnected chain element representing the specified
160  * bref.  chain->refs is set to 1 and the passed bref is copied to
161  * chain->bref.  chain->bytes is derived from the bref.
162  *
163  * chain->pmp inherits pmp unless the chain is an inode (other than the
164  * super-root inode).
165  *
166  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
167  */
168 hammer2_chain_t *
169 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
170                     hammer2_blockref_t *bref)
171 {
172         hammer2_chain_t *chain;
173         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
174
175         /*
176          * Construct the appropriate system structure.
177          */
178         switch(bref->type) {
179         case HAMMER2_BREF_TYPE_INODE:
180         case HAMMER2_BREF_TYPE_INDIRECT:
181         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
182         case HAMMER2_BREF_TYPE_DATA:
183         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
184                 /*
185                  * Chain's are really only associated with the hmp but we
186                  * maintain a pmp association for per-mount memory tracking
187                  * purposes.  The pmp can be NULL.
188                  */
189                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
190                 break;
191         case HAMMER2_BREF_TYPE_VOLUME:
192         case HAMMER2_BREF_TYPE_FREEMAP:
193                 /*
194                  * Only hammer2_chain_bulksnap() calls this function with these
195                  * types.
196                  */
197                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
198                 break;
199         default:
200                 chain = NULL;
201                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
202                       bref->type);
203         }
204
205         /*
206          * Initialize the new chain structure.  pmp must be set to NULL for
207          * chains belonging to the super-root topology of a device mount.
208          */
209         if (pmp == hmp->spmp)
210                 chain->pmp = NULL;
211         else
212                 chain->pmp = pmp;
213         chain->hmp = hmp;
214         chain->bref = *bref;
215         chain->bytes = bytes;
216         chain->refs = 1;
217         chain->flags = HAMMER2_CHAIN_ALLOCATED;
218
219         /*
220          * Set the PFS boundary flag if this chain represents a PFS root.
221          */
222         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
223                 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
224         hammer2_chain_core_init(chain);
225
226         return (chain);
227 }
228
229 /*
230  * Initialize a chain's core structure.  This structure used to be allocated
231  * but is now embedded.
232  *
233  * The core is not locked.  No additional refs on the chain are made.
234  * (trans) must not be NULL if (core) is not NULL.
235  */
236 void
237 hammer2_chain_core_init(hammer2_chain_t *chain)
238 {
239         /*
240          * Fresh core under nchain (no multi-homing of ochain's
241          * sub-tree).
242          */
243         RB_INIT(&chain->core.rbtree);   /* live chains */
244         hammer2_mtx_init(&chain->lock, "h2chain");
245 }
246
247 /*
248  * Add a reference to a chain element, preventing its destruction.
249  *
250  * (can be called with spinlock held)
251  */
252 void
253 hammer2_chain_ref(hammer2_chain_t *chain)
254 {
255         atomic_add_int(&chain->refs, 1);
256 #if 0
257         kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
258         print_backtrace(8);
259 #endif
260 }
261
262 /*
263  * Insert the chain in the core rbtree.
264  *
265  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
266  * chain is a special case used by the flush code that is placed on the
267  * unstaged deleted list to avoid confusing the live view.
268  */
269 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
270 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
271 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
272
273 static
274 int
275 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
276                      int flags, int generation)
277 {
278         hammer2_chain_t *xchain;
279         int error = 0;
280
281         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
282                 hammer2_spin_ex(&parent->core.spin);
283
284         /*
285          * Interlocked by spinlock, check for race
286          */
287         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
288             parent->core.generation != generation) {
289                 error = EAGAIN;
290                 goto failed;
291         }
292
293         /*
294          * Insert chain
295          */
296         xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
297         KASSERT(xchain == NULL,
298                 ("hammer2_chain_insert: collision %p %p", chain, xchain));
299         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
300         chain->parent = parent;
301         ++parent->core.chain_count;
302         ++parent->core.generation;      /* XXX incs for _get() too, XXX */
303
304         /*
305          * We have to keep track of the effective live-view blockref count
306          * so the create code knows when to push an indirect block.
307          */
308         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
309                 atomic_add_int(&parent->core.live_count, 1);
310 failed:
311         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
312                 hammer2_spin_unex(&parent->core.spin);
313         return error;
314 }
315
316 /*
317  * Drop the caller's reference to the chain.  When the ref count drops to
318  * zero this function will try to disassociate the chain from its parent and
319  * deallocate it, then recursely drop the parent using the implied ref
320  * from the chain's chain->parent.
321  */
322 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
323
324 void
325 hammer2_chain_drop(hammer2_chain_t *chain)
326 {
327         u_int refs;
328         u_int need = 0;
329
330         if (hammer2_debug & 0x200000)
331                 Debugger("drop");
332 #if 0
333         kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
334         print_backtrace(8);
335 #endif
336
337         if (chain->flags & HAMMER2_CHAIN_UPDATE)
338                 ++need;
339         if (chain->flags & HAMMER2_CHAIN_MODIFIED)
340                 ++need;
341         KKASSERT(chain->refs > need);
342
343         while (chain) {
344                 refs = chain->refs;
345                 cpu_ccfence();
346                 KKASSERT(refs > 0);
347
348                 if (refs == 1) {
349                         chain = hammer2_chain_lastdrop(chain);
350                 } else {
351                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
352                                 break;
353                         /* retry the same chain */
354                 }
355         }
356 }
357
358 /*
359  * Safe handling of the 1->0 transition on chain.  Returns a chain for
360  * recursive drop or NULL, possibly returning the same chain if the atomic
361  * op fails.
362  *
363  * Whem two chains need to be recursively dropped we use the chain
364  * we would otherwise free to placehold the additional chain.  It's a bit
365  * convoluted but we can't just recurse without potentially blowing out
366  * the kernel stack.
367  *
368  * The chain cannot be freed if it has any children.
369  *
370  * The core spinlock is allowed nest child-to-parent (not parent-to-child).
371  */
372 static
373 hammer2_chain_t *
374 hammer2_chain_lastdrop(hammer2_chain_t *chain)
375 {
376         hammer2_pfs_t *pmp;
377         hammer2_dev_t *hmp;
378         hammer2_chain_t *parent;
379         hammer2_chain_t *rdrop;
380
381         /*
382          * Spinlock the core and check to see if it is empty.  If it is
383          * not empty we leave chain intact with refs == 0.  The elements
384          * in core->rbtree are associated with other chains contemporary
385          * with ours but not with our chain directly.
386          */
387         hammer2_spin_ex(&chain->core.spin);
388
389         /*
390          * We can't free non-stale chains with children until we are
391          * able to free the children because there might be a flush
392          * dependency.  Flushes of stale children (which should also
393          * have their deleted flag set) short-cut recursive flush
394          * dependencies and can be freed here.  Any flushes which run
395          * through stale children due to the flush synchronization
396          * point should have a FLUSH_* bit set in the chain and not
397          * reach lastdrop at this time.
398          *
399          * NOTE: We return (chain) on failure to retry.
400          */
401         if (chain->core.chain_count) {
402                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
403                         hammer2_spin_unex(&chain->core.spin);
404                         chain = NULL;   /* success */
405                 } else {
406                         hammer2_spin_unex(&chain->core.spin);
407                 }
408                 return(chain);
409         }
410         /* no chains left under us */
411
412         /*
413          * chain->core has no children left so no accessors can get to our
414          * chain from there.  Now we have to lock the parent core to interlock
415          * remaining possible accessors that might bump chain's refs before
416          * we can safely drop chain's refs with intent to free the chain.
417          */
418         hmp = chain->hmp;
419         pmp = chain->pmp;       /* can be NULL */
420         rdrop = NULL;
421
422         /*
423          * Spinlock the parent and try to drop the last ref on chain.
424          * On success remove chain from its parent, otherwise return NULL.
425          *
426          * (normal core locks are top-down recursive but we define core
427          *  spinlocks as bottom-up recursive, so this is safe).
428          */
429         if ((parent = chain->parent) != NULL) {
430                 hammer2_spin_ex(&parent->core.spin);
431                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
432                         /* 1->0 transition failed */
433                         hammer2_spin_unex(&parent->core.spin);
434                         hammer2_spin_unex(&chain->core.spin);
435                         return(chain);  /* retry */
436                 }
437
438                 /*
439                  * 1->0 transition successful, remove chain from its
440                  * above core.
441                  */
442                 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
443                         RB_REMOVE(hammer2_chain_tree,
444                                   &parent->core.rbtree, chain);
445                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
446                         --parent->core.chain_count;
447                         chain->parent = NULL;
448                 }
449
450                 /*
451                  * If our chain was the last chain in the parent's core the
452                  * core is now empty and its parent might have to be
453                  * re-dropped if it has 0 refs.
454                  */
455                 if (parent->core.chain_count == 0) {
456                         rdrop = parent;
457                         if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
458                                 rdrop = NULL;
459                         }
460                 }
461                 hammer2_spin_unex(&parent->core.spin);
462                 parent = NULL;  /* safety */
463         }
464
465         /*
466          * Successful 1->0 transition and the chain can be destroyed now.
467          *
468          * We still have the core spinlock, and core's chain_count is 0.
469          * Any parent spinlock is gone.
470          */
471         hammer2_spin_unex(&chain->core.spin);
472         KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
473                  chain->core.chain_count == 0);
474
475         /*
476          * All spin locks are gone, finish freeing stuff.
477          */
478         KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
479                                   HAMMER2_CHAIN_MODIFIED)) == 0);
480         hammer2_chain_drop_data(chain, 1);
481
482         KKASSERT(chain->dio == NULL);
483
484         /*
485          * Once chain resources are gone we can use the now dead chain
486          * structure to placehold what might otherwise require a recursive
487          * drop, because we have potentially two things to drop and can only
488          * return one directly.
489          */
490         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
491                 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
492                 chain->hmp = NULL;
493                 kfree(chain, hmp->mchain);
494         }
495
496         /*
497          * Possible chaining loop when parent re-drop needed.
498          */
499         return(rdrop);
500 }
501
502 /*
503  * On either last lock release or last drop
504  */
505 static void
506 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
507 {
508         /*hammer2_dev_t *hmp = chain->hmp;*/
509
510         switch(chain->bref.type) {
511         case HAMMER2_BREF_TYPE_VOLUME:
512         case HAMMER2_BREF_TYPE_FREEMAP:
513                 if (lastdrop)
514                         chain->data = NULL;
515                 break;
516         default:
517                 KKASSERT(chain->data == NULL);
518                 break;
519         }
520 }
521
522 /*
523  * Lock a referenced chain element, acquiring its data with I/O if necessary,
524  * and specify how you would like the data to be resolved.
525  *
526  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
527  *
528  * The lock is allowed to recurse, multiple locking ops will aggregate
529  * the requested resolve types.  Once data is assigned it will not be
530  * removed until the last unlock.
531  *
532  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
533  *                         (typically used to avoid device/logical buffer
534  *                          aliasing for data)
535  *
536  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
537  *                         the INITIAL-create state (indirect blocks only).
538  *
539  *                         Do not resolve data elements for DATA chains.
540  *                         (typically used to avoid device/logical buffer
541  *                          aliasing for data)
542  *
543  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
544  *
545  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
546  *                         it will be locked exclusive.
547  *
548  * NOTE: Embedded elements (volume header, inodes) are always resolved
549  *       regardless.
550  *
551  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
552  *       element will instantiate and zero its buffer, and flush it on
553  *       release.
554  *
555  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
556  *       so as not to instantiate a device buffer, which could alias against
557  *       a logical file buffer.  However, if ALWAYS is specified the
558  *       device buffer will be instantiated anyway.
559  *
560  * WARNING! This function blocks on I/O if data needs to be fetched.  This
561  *          blocking can run concurrent with other compatible lock holders
562  *          who do not need data returning.  The lock is not upgraded to
563  *          exclusive during a data fetch, a separate bit is used to
564  *          interlock I/O.  However, an exclusive lock holder can still count
565  *          on being interlocked against an I/O fetch managed by a shared
566  *          lock holder.
567  */
568 void
569 hammer2_chain_lock(hammer2_chain_t *chain, int how)
570 {
571         /*
572          * Ref and lock the element.  Recursive locks are allowed.
573          */
574         KKASSERT(chain->refs > 0);
575         atomic_add_int(&chain->lockcnt, 1);
576
577         /*
578          * Get the appropriate lock.
579          */
580         if (how & HAMMER2_RESOLVE_SHARED)
581                 hammer2_mtx_sh(&chain->lock);
582         else
583                 hammer2_mtx_ex(&chain->lock);
584         ++curthread->td_tracker;
585
586         /*
587          * If we already have a valid data pointer no further action is
588          * necessary.
589          */
590         if (chain->data)
591                 return;
592
593         /*
594          * Do we have to resolve the data?
595          */
596         switch(how & HAMMER2_RESOLVE_MASK) {
597         case HAMMER2_RESOLVE_NEVER:
598                 return;
599         case HAMMER2_RESOLVE_MAYBE:
600                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
601                         return;
602                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
603                         return;
604 #if 0
605                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
606                         return;
607                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
608                         return;
609 #endif
610                 /* fall through */
611         case HAMMER2_RESOLVE_ALWAYS:
612         default:
613                 break;
614         }
615
616         /*
617          * Caller requires data
618          */
619         hammer2_chain_load_data(chain);
620 }
621
622 /*
623  * Obtains a second shared lock on the chain, does not account the second
624  * shared lock as being owned by the current thread.
625  *
626  * Caller must already own a shared lock on this chain.
627  */
628 void
629 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
630 {
631         hammer2_mtx_sh(&chain->lock);
632         atomic_add_int(&chain->lockcnt, 1);
633         /* do not count in td_tracker for this thread */
634 }
635
636 /*
637  * Accounts for a shared lock that was pushed to us as being owned by our
638  * thread.
639  */
640 void
641 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
642 {
643         ++curthread->td_tracker;
644 }
645
646 /*
647  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
648  * may be of any type.
649  *
650  * Once chain->data is set it cannot be disposed of until all locks are
651  * released.
652  */
653 void
654 hammer2_chain_load_data(hammer2_chain_t *chain)
655 {
656         hammer2_blockref_t *bref;
657         hammer2_dev_t *hmp;
658         char *bdata;
659         int error;
660
661         /*
662          * Degenerate case, data already present.
663          */
664         if (chain->data)
665                 return;
666
667         hmp = chain->hmp;
668         KKASSERT(hmp != NULL);
669
670         /*
671          * Gain the IOINPROG bit, interlocked block.
672          */
673         for (;;) {
674                 u_int oflags;
675                 u_int nflags;
676
677                 oflags = chain->flags;
678                 cpu_ccfence();
679                 if (oflags & HAMMER2_CHAIN_IOINPROG) {
680                         nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
681                         tsleep_interlock(&chain->flags, 0);
682                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
683                                 tsleep(&chain->flags, PINTERLOCKED,
684                                         "h2iocw", 0);
685                         }
686                         /* retry */
687                 } else {
688                         nflags = oflags | HAMMER2_CHAIN_IOINPROG;
689                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
690                                 break;
691                         }
692                         /* retry */
693                 }
694         }
695
696         /*
697          * We own CHAIN_IOINPROG
698          *
699          * Degenerate case if we raced another load.
700          */
701         if (chain->data)
702                 goto done;
703
704         /*
705          * We must resolve to a device buffer, either by issuing I/O or
706          * by creating a zero-fill element.  We do not mark the buffer
707          * dirty when creating a zero-fill element (the hammer2_chain_modify()
708          * API must still be used to do that).
709          *
710          * The device buffer is variable-sized in powers of 2 down
711          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
712          * chunk always contains buffers of the same size. (XXX)
713          *
714          * The minimum physical IO size may be larger than the variable
715          * block size.
716          */
717         bref = &chain->bref;
718
719         /*
720          * The getblk() optimization can only be used on newly created
721          * elements if the physical block size matches the request.
722          */
723         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
724                 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
725                                         &chain->dio);
726         } else {
727                 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
728                                          &chain->dio);
729                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
730         }
731         if (error) {
732                 chain->error = HAMMER2_ERROR_IO;
733                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
734                         (intmax_t)bref->data_off, error);
735                 hammer2_io_bqrelse(&chain->dio);
736                 goto done;
737         }
738         chain->error = 0;
739
740         /*
741          * NOTE: A locked chain's data cannot be modified without first
742          *       calling hammer2_chain_modify().
743          */
744
745         /*
746          * Clear INITIAL.  In this case we used io_new() and the buffer has
747          * been zero'd and marked dirty.
748          */
749         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
750         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
751                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
752                 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
753         } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
754                 /*
755                  * check data not currently synchronized due to
756                  * modification.  XXX assumes data stays in the buffer
757                  * cache, which might not be true (need biodep on flush
758                  * to calculate crc?  or simple crc?).
759                  */
760         } else {
761                 if (hammer2_chain_testcheck(chain, bdata) == 0) {
762                         kprintf("chain %016jx.%02x meth=%02x "
763                                 "CHECK FAIL %08x (flags=%08x)\n",
764                                 chain->bref.data_off,
765                                 chain->bref.type,
766                                 chain->bref.methods,
767                                 hammer2_icrc32(bdata, chain->bytes),
768                                 chain->flags);
769                         chain->error = HAMMER2_ERROR_CHECK;
770                 }
771         }
772
773         /*
774          * Setup the data pointer, either pointing it to an embedded data
775          * structure and copying the data from the buffer, or pointing it
776          * into the buffer.
777          *
778          * The buffer is not retained when copying to an embedded data
779          * structure in order to avoid potential deadlocks or recursions
780          * on the same physical buffer.
781          *
782          * WARNING! Other threads can start using the data the instant we
783          *          set chain->data non-NULL.
784          */
785         switch (bref->type) {
786         case HAMMER2_BREF_TYPE_VOLUME:
787         case HAMMER2_BREF_TYPE_FREEMAP:
788                 /*
789                  * Copy data from bp to embedded buffer
790                  */
791                 panic("hammer2_chain_lock: called on unresolved volume header");
792                 break;
793         case HAMMER2_BREF_TYPE_INODE:
794         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
795         case HAMMER2_BREF_TYPE_INDIRECT:
796         case HAMMER2_BREF_TYPE_DATA:
797         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
798         default:
799                 /*
800                  * Point data at the device buffer and leave dio intact.
801                  */
802                 chain->data = (void *)bdata;
803                 break;
804         }
805
806         /*
807          * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
808          */
809 done:
810         for (;;) {
811                 u_int oflags;
812                 u_int nflags;
813
814                 oflags = chain->flags;
815                 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
816                                     HAMMER2_CHAIN_IOSIGNAL);
817                 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
818                 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
819                         if (oflags & HAMMER2_CHAIN_IOSIGNAL)
820                                 wakeup(&chain->flags);
821                         break;
822                 }
823         }
824 }
825
826 /*
827  * Unlock and deref a chain element.
828  *
829  * On the last lock release any non-embedded data (chain->dio) will be
830  * retired.
831  */
832 void
833 hammer2_chain_unlock(hammer2_chain_t *chain)
834 {
835         hammer2_mtx_state_t ostate;
836         long *counterp;
837         u_int lockcnt;
838
839         --curthread->td_tracker;
840         /*
841          * If multiple locks are present (or being attempted) on this
842          * particular chain we can just unlock, drop refs, and return.
843          *
844          * Otherwise fall-through on the 1->0 transition.
845          */
846         for (;;) {
847                 lockcnt = chain->lockcnt;
848                 KKASSERT(lockcnt > 0);
849                 cpu_ccfence();
850                 if (lockcnt > 1) {
851                         if (atomic_cmpset_int(&chain->lockcnt,
852                                               lockcnt, lockcnt - 1)) {
853                                 hammer2_mtx_unlock(&chain->lock);
854                                 return;
855                         }
856                 } else {
857                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
858                                 break;
859                 }
860                 /* retry */
861         }
862
863         /*
864          * On the 1->0 transition we upgrade the core lock (if necessary)
865          * to exclusive for terminal processing.  If after upgrading we find
866          * that lockcnt is non-zero, another thread is racing us and will
867          * handle the unload for us later on, so just cleanup and return
868          * leaving the data/io intact
869          *
870          * Otherwise if lockcnt is still 0 it is possible for it to become
871          * non-zero and race, but since we hold the core->lock exclusively
872          * all that will happen is that the chain will be reloaded after we
873          * unload it.
874          */
875         ostate = hammer2_mtx_upgrade(&chain->lock);
876         if (chain->lockcnt) {
877                 hammer2_mtx_unlock(&chain->lock);
878                 return;
879         }
880
881         /*
882          * Shortcut the case if the data is embedded or not resolved.
883          *
884          * Do NOT NULL out chain->data (e.g. inode data), it might be
885          * dirty.
886          */
887         if (chain->dio == NULL) {
888                 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
889                         hammer2_chain_drop_data(chain, 0);
890                 hammer2_mtx_unlock(&chain->lock);
891                 return;
892         }
893
894         /*
895          * Statistics
896          */
897         if (hammer2_io_isdirty(chain->dio)) {
898                 switch(chain->bref.type) {
899                 case HAMMER2_BREF_TYPE_DATA:
900                         counterp = &hammer2_iod_file_write;
901                         break;
902                 case HAMMER2_BREF_TYPE_INODE:
903                         counterp = &hammer2_iod_meta_write;
904                         break;
905                 case HAMMER2_BREF_TYPE_INDIRECT:
906                         counterp = &hammer2_iod_indr_write;
907                         break;
908                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
909                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
910                         counterp = &hammer2_iod_fmap_write;
911                         break;
912                 default:
913                         counterp = &hammer2_iod_volu_write;
914                         break;
915                 }
916                 *counterp += chain->bytes;
917         }
918
919         /*
920          * Clean out the dio.
921          *
922          * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
923          *       is possible.
924          */
925         chain->data = NULL;
926         hammer2_io_bqrelse(&chain->dio);
927         hammer2_mtx_unlock(&chain->lock);
928 }
929
930 /*
931  * Helper to obtain the blockref[] array base and count for a chain.
932  *
933  * XXX Not widely used yet, various use cases need to be validated and
934  *     converted to use this function.
935  */
936 static
937 hammer2_blockref_t *
938 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
939 {
940         hammer2_blockref_t *base;
941         int count;
942
943         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
944                 base = NULL;
945
946                 switch(parent->bref.type) {
947                 case HAMMER2_BREF_TYPE_INODE:
948                         count = HAMMER2_SET_COUNT;
949                         break;
950                 case HAMMER2_BREF_TYPE_INDIRECT:
951                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
952                         count = parent->bytes / sizeof(hammer2_blockref_t);
953                         break;
954                 case HAMMER2_BREF_TYPE_VOLUME:
955                         count = HAMMER2_SET_COUNT;
956                         break;
957                 case HAMMER2_BREF_TYPE_FREEMAP:
958                         count = HAMMER2_SET_COUNT;
959                         break;
960                 default:
961                         panic("hammer2_chain_create_indirect: "
962                               "unrecognized blockref type: %d",
963                               parent->bref.type);
964                         count = 0;
965                         break;
966                 }
967         } else {
968                 switch(parent->bref.type) {
969                 case HAMMER2_BREF_TYPE_INODE:
970                         base = &parent->data->ipdata.u.blockset.blockref[0];
971                         count = HAMMER2_SET_COUNT;
972                         break;
973                 case HAMMER2_BREF_TYPE_INDIRECT:
974                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
975                         base = &parent->data->npdata[0];
976                         count = parent->bytes / sizeof(hammer2_blockref_t);
977                         break;
978                 case HAMMER2_BREF_TYPE_VOLUME:
979                         base = &parent->data->voldata.
980                                         sroot_blockset.blockref[0];
981                         count = HAMMER2_SET_COUNT;
982                         break;
983                 case HAMMER2_BREF_TYPE_FREEMAP:
984                         base = &parent->data->blkset.blockref[0];
985                         count = HAMMER2_SET_COUNT;
986                         break;
987                 default:
988                         panic("hammer2_chain_create_indirect: "
989                               "unrecognized blockref type: %d",
990                               parent->bref.type);
991                         count = 0;
992                         break;
993                 }
994         }
995         *countp = count;
996
997         return base;
998 }
999
1000 /*
1001  * This counts the number of live blockrefs in a block array and
1002  * also calculates the point at which all remaining blockrefs are empty.
1003  * This routine can only be called on a live chain (DUPLICATED flag not set).
1004  *
1005  * NOTE: Flag is not set until after the count is complete, allowing
1006  *       callers to test the flag without holding the spinlock.
1007  *
1008  * NOTE: If base is NULL the related chain is still in the INITIAL
1009  *       state and there are no blockrefs to count.
1010  *
1011  * NOTE: live_count may already have some counts accumulated due to
1012  *       creation and deletion and could even be initially negative.
1013  */
1014 void
1015 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1016                          hammer2_blockref_t *base, int count)
1017 {
1018         hammer2_spin_ex(&chain->core.spin);
1019         if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1020                 if (base) {
1021                         while (--count >= 0) {
1022                                 if (base[count].type)
1023                                         break;
1024                         }
1025                         chain->core.live_zero = count + 1;
1026                         while (count >= 0) {
1027                                 if (base[count].type)
1028                                         atomic_add_int(&chain->core.live_count,
1029                                                        1);
1030                                 --count;
1031                         }
1032                 } else {
1033                         chain->core.live_zero = 0;
1034                 }
1035                 /* else do not modify live_count */
1036                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1037         }
1038         hammer2_spin_unex(&chain->core.spin);
1039 }
1040
1041 /*
1042  * Resize the chain's physical storage allocation in-place.  This function does
1043  * not adjust the data pointer and must be followed by (typically) a
1044  * hammer2_chain_modify() call to copy any old data over and adjust the
1045  * data pointer.
1046  *
1047  * Chains can be resized smaller without reallocating the storage.  Resizing
1048  * larger will reallocate the storage.  Excess or prior storage is reclaimed
1049  * asynchronously at a later time.
1050  *
1051  * Must be passed an exclusively locked parent and chain.
1052  *
1053  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1054  * to avoid instantiating a device buffer that conflicts with the vnode data
1055  * buffer.  However, because H2 can compress or encrypt data, the chain may
1056  * have a dio assigned to it in those situations, and they do not conflict.
1057  *
1058  * XXX return error if cannot resize.
1059  */
1060 void
1061 hammer2_chain_resize(hammer2_inode_t *ip,
1062                      hammer2_chain_t *parent, hammer2_chain_t *chain,
1063                      hammer2_tid_t mtid, hammer2_off_t dedup_off,
1064                      int nradix, int flags)
1065 {
1066         hammer2_dev_t *hmp;
1067         size_t obytes;
1068         size_t nbytes;
1069
1070         hmp = chain->hmp;
1071
1072         /*
1073          * Only data and indirect blocks can be resized for now.
1074          * (The volu root, inodes, and freemap elements use a fixed size).
1075          */
1076         KKASSERT(chain != &hmp->vchain);
1077         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1078                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1079         KKASSERT(chain->parent == parent);
1080
1081         /*
1082          * Nothing to do if the element is already the proper size
1083          */
1084         obytes = chain->bytes;
1085         nbytes = 1U << nradix;
1086         if (obytes == nbytes)
1087                 return;
1088
1089         /*
1090          * Make sure the old data is instantiated so we can copy it.  If this
1091          * is a data block, the device data may be superfluous since the data
1092          * might be in a logical block, but compressed or encrypted data is
1093          * another matter.
1094          *
1095          * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1096          */
1097         hammer2_chain_modify(chain, mtid, dedup_off, 0);
1098
1099         /*
1100          * Relocate the block, even if making it smaller (because different
1101          * block sizes may be in different regions).
1102          *
1103          * (data blocks only, we aren't copying the storage here).
1104          */
1105         hammer2_freemap_alloc(chain, nbytes);
1106         chain->bytes = nbytes;
1107         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1108
1109         /*
1110          * We don't want the followup chain_modify() to try to copy data
1111          * from the old (wrong-sized) buffer.  It won't know how much to
1112          * copy.  This case should only occur during writes when the
1113          * originator already has the data to write in-hand.
1114          */
1115         if (chain->dio) {
1116                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1117                 hammer2_io_brelse(&chain->dio);
1118                 chain->data = NULL;
1119         }
1120 }
1121
1122 /*
1123  * Set the chain modified so its data can be changed by the caller.
1124  *
1125  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1126  * is a CLC (cluster level change) field and is not updated by parent
1127  * propagation during a flush.
1128  *
1129  * If the caller passes a non-zero dedup_off we assign data_off to that
1130  * instead of allocating a ne block.  Caller must not modify the data already
1131  * present at the target offset.
1132  */
1133 void
1134 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1135                      hammer2_off_t dedup_off, int flags)
1136 {
1137         hammer2_blockref_t obref;
1138         hammer2_dev_t *hmp;
1139         hammer2_io_t *dio;
1140         int error;
1141         int wasinitial;
1142         int newmod;
1143         char *bdata;
1144
1145         hmp = chain->hmp;
1146         obref = chain->bref;
1147         KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1148
1149         /*
1150          * Data is not optional for freemap chains (we must always be sure
1151          * to copy the data on COW storage allocations).
1152          */
1153         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1154             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1155                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1156                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1157         }
1158
1159         /*
1160          * Data must be resolved if already assigned, unless explicitly
1161          * flagged otherwise.
1162          */
1163         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1164             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1165                 hammer2_chain_load_data(chain);
1166         }
1167
1168         /*
1169          * Set MODIFIED to indicate that the chain has been modified.
1170          * Set UPDATE to ensure that the blockref is updated in the parent.
1171          */
1172         if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1173             (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1174                 /*
1175                  * Modified already set but a new allocation is needed
1176                  * anyway because we recorded this data_off for possible
1177                  * dedup operation.
1178                  */
1179                 newmod = 1;
1180         } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1181                 /*
1182                  * Must set modified bit.  If the chain has been deleted
1183                  * it must be placed on the delayed-flush queue to prevent
1184                  * it from possibly being lost (a normal flush of the topology
1185                  * will no longer see it).
1186                  */
1187                 atomic_add_long(&hammer2_count_modified_chains, 1);
1188                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1189                 hammer2_chain_ref(chain);
1190                 hammer2_pfs_memory_inc(chain->pmp);     /* can be NULL */
1191                 if ((chain->flags & HAMMER2_CHAIN_DELETED) &&
1192                     (chain->flags & HAMMER2_CHAIN_DELAYED) == 0) {
1193                         hammer2_delayed_flush(chain);
1194                 }
1195                 newmod = 1;
1196         } else {
1197                 /*
1198                  * Already flagged modified, no new allocation is needed.
1199                  */
1200                 newmod = 0;
1201         }
1202         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1203                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1204                 hammer2_chain_ref(chain);
1205         }
1206         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1207
1208         /*
1209          * The modification or re-modification requires an allocation and
1210          * possible COW.
1211          *
1212          * If dedup_off is non-zero, caller already has a data offset
1213          * containing the caller's desired data.  The dedup offset is
1214          * allowed to be in a partially free state and we must be sure
1215          * to reset it to a fully allocated state to force two bulkfree
1216          * passes to free it again.
1217          *
1218          * XXX can a chain already be marked MODIFIED without a data
1219          * assignment?  If not, assert here instead of testing the case.
1220          */
1221         if (chain != &hmp->vchain && chain != &hmp->fchain) {
1222                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1223                      newmod
1224                 ) {
1225                         if (dedup_off) {
1226                                 chain->bref.data_off = dedup_off;
1227                                 chain->bytes = 1 << (dedup_off &
1228                                                      HAMMER2_OFF_MASK_RADIX);
1229                                 atomic_set_int(&chain->flags,
1230                                                HAMMER2_CHAIN_DEDUP);
1231                                 hammer2_freemap_adjust(hmp, &chain->bref,
1232                                                 HAMMER2_FREEMAP_DORECOVER);
1233                         } else {
1234                                 hammer2_freemap_alloc(chain, chain->bytes);
1235                         }
1236                         /* XXX failed allocation */
1237                 }
1238         }
1239
1240         /*
1241          * Update mirror_tid and modify_tid.  modify_tid is only updated
1242          * if not passed as zero (during flushes, parent propagation passes
1243          * the value 0).
1244          *
1245          * NOTE: chain->pmp could be the device spmp.
1246          */
1247         chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1248         if (mtid)
1249                 chain->bref.modify_tid = mtid;
1250
1251         /*
1252          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1253          * requires updating as well as to tell the delete code that the
1254          * chain's blockref might not exactly match (in terms of physical size
1255          * or block offset) the one in the parent's blocktable.  The base key
1256          * of course will still match.
1257          */
1258         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1259                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1260
1261         /*
1262          * Short-cut data blocks which the caller does not need an actual
1263          * data reference to (aka OPTDATA), as long as the chain does not
1264          * already have a data pointer to the data.  This generally means
1265          * that the modifications are being done via the logical buffer cache.
1266          * The INITIAL flag relates only to the device data buffer and thus
1267          * remains unchange in this situation.
1268          */
1269         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1270             (flags & HAMMER2_MODIFY_OPTDATA) &&
1271             chain->data == NULL) {
1272                 goto skip2;
1273         }
1274
1275         /*
1276          * Clearing the INITIAL flag (for indirect blocks) indicates that
1277          * we've processed the uninitialized storage allocation.
1278          *
1279          * If this flag is already clear we are likely in a copy-on-write
1280          * situation but we have to be sure NOT to bzero the storage if
1281          * no data is present.
1282          */
1283         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1284                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1285                 wasinitial = 1;
1286         } else {
1287                 wasinitial = 0;
1288         }
1289
1290         /*
1291          * Instantiate data buffer and possibly execute COW operation
1292          */
1293         switch(chain->bref.type) {
1294         case HAMMER2_BREF_TYPE_VOLUME:
1295         case HAMMER2_BREF_TYPE_FREEMAP:
1296                 /*
1297                  * The data is embedded, no copy-on-write operation is
1298                  * needed.
1299                  */
1300                 KKASSERT(chain->dio == NULL);
1301                 break;
1302         case HAMMER2_BREF_TYPE_INODE:
1303         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1304         case HAMMER2_BREF_TYPE_DATA:
1305         case HAMMER2_BREF_TYPE_INDIRECT:
1306         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1307                 /*
1308                  * Perform the copy-on-write operation
1309                  *
1310                  * zero-fill or copy-on-write depending on whether
1311                  * chain->data exists or not and set the dirty state for
1312                  * the new buffer.  hammer2_io_new() will handle the
1313                  * zero-fill.
1314                  *
1315                  * If a dedup_off was supplied this is an existing block
1316                  * and no COW, copy, or further modification is required.
1317                  */
1318                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1319
1320                 if (wasinitial && dedup_off == 0) {
1321                         error = hammer2_io_new(hmp, chain->bref.data_off,
1322                                                chain->bytes, &dio);
1323                 } else {
1324                         error = hammer2_io_bread(hmp, chain->bref.data_off,
1325                                                  chain->bytes, &dio);
1326                 }
1327                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1328
1329                 /*
1330                  * If an I/O error occurs make sure callers cannot accidently
1331                  * modify the old buffer's contents and corrupt the filesystem.
1332                  */
1333                 if (error) {
1334                         kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1335                                 hmp);
1336                         chain->error = HAMMER2_ERROR_IO;
1337                         hammer2_io_brelse(&dio);
1338                         hammer2_io_brelse(&chain->dio);
1339                         chain->data = NULL;
1340                         break;
1341                 }
1342                 chain->error = 0;
1343                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1344
1345                 if (chain->data) {
1346                         /*
1347                          * COW (unless a dedup).
1348                          */
1349                         KKASSERT(chain->dio != NULL);
1350                         if (chain->data != (void *)bdata && dedup_off == 0) {
1351                                 bcopy(chain->data, bdata, chain->bytes);
1352                         }
1353                 } else if (wasinitial == 0) {
1354                         /*
1355                          * We have a problem.  We were asked to COW but
1356                          * we don't have any data to COW with!
1357                          */
1358                         panic("hammer2_chain_modify: having a COW %p\n",
1359                               chain);
1360                 }
1361
1362                 /*
1363                  * Retire the old buffer, replace with the new.  Dirty or
1364                  * redirty the new buffer.
1365                  *
1366                  * WARNING! The system buffer cache may have already flushed
1367                  *          the buffer, so we must be sure to [re]dirty it
1368                  *          for further modification.
1369                  *
1370                  *          If dedup_off was supplied, the caller is not
1371                  *          expected to make any further modification to the
1372                  *          buffer.
1373                  */
1374                 if (chain->dio)
1375                         hammer2_io_bqrelse(&chain->dio);
1376                 chain->data = (void *)bdata;
1377                 chain->dio = dio;
1378                 if (dedup_off == 0)
1379                         hammer2_io_setdirty(dio);
1380                 break;
1381         default:
1382                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1383                       chain->bref.type);
1384                 break;
1385
1386         }
1387 skip2:
1388         /*
1389          * setflush on parent indicating that the parent must recurse down
1390          * to us.  Do not call on chain itself which might already have it
1391          * set.
1392          */
1393         if (chain->parent)
1394                 hammer2_chain_setflush(chain->parent);
1395 }
1396
1397 /*
1398  * Modify the chain associated with an inode.
1399  */
1400 void
1401 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1402                         hammer2_tid_t mtid, int flags)
1403 {
1404         hammer2_inode_modify(ip);
1405         hammer2_chain_modify(chain, mtid, 0, flags);
1406 }
1407
1408 /*
1409  * Volume header data locks
1410  */
1411 void
1412 hammer2_voldata_lock(hammer2_dev_t *hmp)
1413 {
1414         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1415 }
1416
1417 void
1418 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1419 {
1420         lockmgr(&hmp->vollk, LK_RELEASE);
1421 }
1422
1423 void
1424 hammer2_voldata_modify(hammer2_dev_t *hmp)
1425 {
1426         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1427                 atomic_add_long(&hammer2_count_modified_chains, 1);
1428                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1429                 hammer2_chain_ref(&hmp->vchain);
1430                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1431         }
1432 }
1433
1434 /*
1435  * This function returns the chain at the nearest key within the specified
1436  * range.  The returned chain will be referenced but not locked.
1437  *
1438  * This function will recurse through chain->rbtree as necessary and will
1439  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1440  * the iteration value is less than the current value of *key_nextp.
1441  *
1442  * The caller should use (*key_nextp) to calculate the actual range of
1443  * the returned element, which will be (key_beg to *key_nextp - 1), because
1444  * there might be another element which is superior to the returned element
1445  * and overlaps it.
1446  *
1447  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1448  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1449  * it will wind up being (key_end + 1).
1450  *
1451  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1452  *           held through the operation.
1453  */
1454 struct hammer2_chain_find_info {
1455         hammer2_chain_t         *best;
1456         hammer2_key_t           key_beg;
1457         hammer2_key_t           key_end;
1458         hammer2_key_t           key_next;
1459 };
1460
1461 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1462 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1463
1464 static
1465 hammer2_chain_t *
1466 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1467                           hammer2_key_t key_beg, hammer2_key_t key_end)
1468 {
1469         struct hammer2_chain_find_info info;
1470
1471         info.best = NULL;
1472         info.key_beg = key_beg;
1473         info.key_end = key_end;
1474         info.key_next = *key_nextp;
1475
1476         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1477                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1478                 &info);
1479         *key_nextp = info.key_next;
1480 #if 0
1481         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1482                 parent, key_beg, key_end, *key_nextp);
1483 #endif
1484
1485         return (info.best);
1486 }
1487
1488 static
1489 int
1490 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1491 {
1492         struct hammer2_chain_find_info *info = data;
1493         hammer2_key_t child_beg;
1494         hammer2_key_t child_end;
1495
1496         child_beg = child->bref.key;
1497         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1498
1499         if (child_end < info->key_beg)
1500                 return(-1);
1501         if (child_beg > info->key_end)
1502                 return(1);
1503         return(0);
1504 }
1505
1506 static
1507 int
1508 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1509 {
1510         struct hammer2_chain_find_info *info = data;
1511         hammer2_chain_t *best;
1512         hammer2_key_t child_end;
1513
1514         /*
1515          * WARNING! Do not discard DUPLICATED chains, it is possible that
1516          *          we are catching an insertion half-way done.  If a
1517          *          duplicated chain turns out to be the best choice the
1518          *          caller will re-check its flags after locking it.
1519          *
1520          * WARNING! Layerq is scanned forwards, exact matches should keep
1521          *          the existing info->best.
1522          */
1523         if ((best = info->best) == NULL) {
1524                 /*
1525                  * No previous best.  Assign best
1526                  */
1527                 info->best = child;
1528         } else if (best->bref.key <= info->key_beg &&
1529                    child->bref.key <= info->key_beg) {
1530                 /*
1531                  * Illegal overlap.
1532                  */
1533                 KKASSERT(0);
1534                 /*info->best = child;*/
1535         } else if (child->bref.key < best->bref.key) {
1536                 /*
1537                  * Child has a nearer key and best is not flush with key_beg.
1538                  * Set best to child.  Truncate key_next to the old best key.
1539                  */
1540                 info->best = child;
1541                 if (info->key_next > best->bref.key || info->key_next == 0)
1542                         info->key_next = best->bref.key;
1543         } else if (child->bref.key == best->bref.key) {
1544                 /*
1545                  * If our current best is flush with the child then this
1546                  * is an illegal overlap.
1547                  *
1548                  * key_next will automatically be limited to the smaller of
1549                  * the two end-points.
1550                  */
1551                 KKASSERT(0);
1552                 info->best = child;
1553         } else {
1554                 /*
1555                  * Keep the current best but truncate key_next to the child's
1556                  * base.
1557                  *
1558                  * key_next will also automatically be limited to the smaller
1559                  * of the two end-points (probably not necessary for this case
1560                  * but we do it anyway).
1561                  */
1562                 if (info->key_next > child->bref.key || info->key_next == 0)
1563                         info->key_next = child->bref.key;
1564         }
1565
1566         /*
1567          * Always truncate key_next based on child's end-of-range.
1568          */
1569         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1570         if (child_end && (info->key_next > child_end || info->key_next == 0))
1571                 info->key_next = child_end;
1572
1573         return(0);
1574 }
1575
1576 /*
1577  * Retrieve the specified chain from a media blockref, creating the
1578  * in-memory chain structure which reflects it.
1579  *
1580  * To handle insertion races pass the INSERT_RACE flag along with the
1581  * generation number of the core.  NULL will be returned if the generation
1582  * number changes before we have a chance to insert the chain.  Insert
1583  * races can occur because the parent might be held shared.
1584  *
1585  * Caller must hold the parent locked shared or exclusive since we may
1586  * need the parent's bref array to find our block.
1587  *
1588  * WARNING! chain->pmp is always set to NULL for any chain representing
1589  *          part of the super-root topology.
1590  */
1591 hammer2_chain_t *
1592 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1593                   hammer2_blockref_t *bref)
1594 {
1595         hammer2_dev_t *hmp = parent->hmp;
1596         hammer2_chain_t *chain;
1597         int error;
1598
1599         /*
1600          * Allocate a chain structure representing the existing media
1601          * entry.  Resulting chain has one ref and is not locked.
1602          */
1603         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1604                 chain = hammer2_chain_alloc(hmp, NULL, bref);
1605         else
1606                 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1607         /* ref'd chain returned */
1608
1609         /*
1610          * Flag that the chain is in the parent's blockmap so delete/flush
1611          * knows what to do with it.
1612          */
1613         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1614
1615         /*
1616          * Link the chain into its parent.  A spinlock is required to safely
1617          * access the RBTREE, and it is possible to collide with another
1618          * hammer2_chain_get() operation because the caller might only hold
1619          * a shared lock on the parent.
1620          */
1621         KKASSERT(parent->refs > 0);
1622         error = hammer2_chain_insert(parent, chain,
1623                                      HAMMER2_CHAIN_INSERT_SPIN |
1624                                      HAMMER2_CHAIN_INSERT_RACE,
1625                                      generation);
1626         if (error) {
1627                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1628                 kprintf("chain %p get race\n", chain);
1629                 hammer2_chain_drop(chain);
1630                 chain = NULL;
1631         } else {
1632                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1633         }
1634
1635         /*
1636          * Return our new chain referenced but not locked, or NULL if
1637          * a race occurred.
1638          */
1639         return (chain);
1640 }
1641
1642 /*
1643  * Lookup initialization/completion API
1644  */
1645 hammer2_chain_t *
1646 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1647 {
1648         hammer2_chain_ref(parent);
1649         if (flags & HAMMER2_LOOKUP_SHARED) {
1650                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1651                                            HAMMER2_RESOLVE_SHARED);
1652         } else {
1653                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1654         }
1655         return (parent);
1656 }
1657
1658 void
1659 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1660 {
1661         if (parent) {
1662                 hammer2_chain_unlock(parent);
1663                 hammer2_chain_drop(parent);
1664         }
1665 }
1666
1667 hammer2_chain_t *
1668 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1669 {
1670         hammer2_chain_t *oparent;
1671         hammer2_chain_t *nparent;
1672
1673         /*
1674          * Be careful of order, oparent must be unlocked before nparent
1675          * is locked below to avoid a deadlock.
1676          */
1677         oparent = *parentp;
1678         hammer2_spin_ex(&oparent->core.spin);
1679         nparent = oparent->parent;
1680         hammer2_chain_ref(nparent);
1681         hammer2_spin_unex(&oparent->core.spin);
1682         if (oparent) {
1683                 hammer2_chain_unlock(oparent);
1684                 hammer2_chain_drop(oparent);
1685                 oparent = NULL;
1686         }
1687
1688         hammer2_chain_lock(nparent, how);
1689         *parentp = nparent;
1690
1691         return (nparent);
1692 }
1693
1694 /*
1695  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1696  * (*parentp) typically points to an inode but can also point to a related
1697  * indirect block and this function will recurse upwards and find the inode
1698  * again.
1699  *
1700  * (*parentp) must be exclusively locked and referenced and can be an inode
1701  * or an existing indirect block within the inode.
1702  *
1703  * On return (*parentp) will be modified to point at the deepest parent chain
1704  * element encountered during the search, as a helper for an insertion or
1705  * deletion.   The new (*parentp) will be locked and referenced and the old
1706  * will be unlocked and dereferenced (no change if they are both the same).
1707  *
1708  * The matching chain will be returned exclusively locked.  If NOLOCK is
1709  * requested the chain will be returned only referenced.  Note that the
1710  * parent chain must always be locked shared or exclusive, matching the
1711  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
1712  * when NOLOCK is specified but that complicates matters if *parentp must
1713  * inherit the chain.
1714  *
1715  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1716  * data pointer or can otherwise be in flux.
1717  *
1718  * NULL is returned if no match was found, but (*parentp) will still
1719  * potentially be adjusted.
1720  *
1721  * If a fatal error occurs (typically an I/O error), a dummy chain is
1722  * returned with chain->error and error-identifying information set.  This
1723  * chain will assert if you try to do anything fancy with it.
1724  *
1725  * XXX Depending on where the error occurs we should allow continued iteration.
1726  *
1727  * On return (*key_nextp) will point to an iterative value for key_beg.
1728  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1729  *
1730  * This function will also recurse up the chain if the key is not within the
1731  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1732  * can simply allow (*parentp) to float inside the loop.
1733  *
1734  * NOTE!  chain->data is not always resolved.  By default it will not be
1735  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1736  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1737  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1738  *        buffer).
1739  */
1740 hammer2_chain_t *
1741 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1742                      hammer2_key_t key_beg, hammer2_key_t key_end,
1743                      int *cache_indexp, int flags)
1744 {
1745         hammer2_dev_t *hmp;
1746         hammer2_chain_t *parent;
1747         hammer2_chain_t *chain;
1748         hammer2_blockref_t *base;
1749         hammer2_blockref_t *bref;
1750         hammer2_blockref_t bcopy;
1751         hammer2_key_t scan_beg;
1752         hammer2_key_t scan_end;
1753         int count = 0;
1754         int how_always = HAMMER2_RESOLVE_ALWAYS;
1755         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1756         int how;
1757         int generation;
1758         int maxloops = 300000;
1759
1760         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1761                 how_maybe = how_always;
1762                 how = HAMMER2_RESOLVE_ALWAYS;
1763         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1764                 how = HAMMER2_RESOLVE_NEVER;
1765         } else {
1766                 how = HAMMER2_RESOLVE_MAYBE;
1767         }
1768         if (flags & HAMMER2_LOOKUP_SHARED) {
1769                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1770                 how_always |= HAMMER2_RESOLVE_SHARED;
1771                 how |= HAMMER2_RESOLVE_SHARED;
1772         }
1773
1774         /*
1775          * Recurse (*parentp) upward if necessary until the parent completely
1776          * encloses the key range or we hit the inode.
1777          *
1778          * This function handles races against the flusher doing a delete-
1779          * duplicate above us and re-homes the parent to the duplicate in
1780          * that case, otherwise we'd wind up recursing down a stale chain.
1781          */
1782         parent = *parentp;
1783         hmp = parent->hmp;
1784
1785         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1786                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1787                 scan_beg = parent->bref.key;
1788                 scan_end = scan_beg +
1789                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1790                 if (key_beg >= scan_beg && key_end <= scan_end)
1791                         break;
1792                 parent = hammer2_chain_getparent(parentp, how_maybe);
1793         }
1794
1795 again:
1796         if (--maxloops == 0)
1797                 panic("hammer2_chain_lookup: maxloops");
1798         /*
1799          * Locate the blockref array.  Currently we do a fully associative
1800          * search through the array.
1801          */
1802         switch(parent->bref.type) {
1803         case HAMMER2_BREF_TYPE_INODE:
1804                 /*
1805                  * Special shortcut for embedded data returns the inode
1806                  * itself.  Callers must detect this condition and access
1807                  * the embedded data (the strategy code does this for us).
1808                  *
1809                  * This is only applicable to regular files and softlinks.
1810                  */
1811                 if (parent->data->ipdata.meta.op_flags &
1812                     HAMMER2_OPFLAG_DIRECTDATA) {
1813                         if (flags & HAMMER2_LOOKUP_NODIRECT) {
1814                                 chain = NULL;
1815                                 *key_nextp = key_end + 1;
1816                                 goto done;
1817                         }
1818                         hammer2_chain_ref(parent);
1819                         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1820                                 hammer2_chain_lock(parent, how_always);
1821                         *key_nextp = key_end + 1;
1822                         return (parent);
1823                 }
1824                 base = &parent->data->ipdata.u.blockset.blockref[0];
1825                 count = HAMMER2_SET_COUNT;
1826                 break;
1827         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1828         case HAMMER2_BREF_TYPE_INDIRECT:
1829                 /*
1830                  * Handle MATCHIND on the parent
1831                  */
1832                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1833                         scan_beg = parent->bref.key;
1834                         scan_end = scan_beg +
1835                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1836                         if (key_beg == scan_beg && key_end == scan_end) {
1837                                 chain = parent;
1838                                 hammer2_chain_ref(chain);
1839                                 hammer2_chain_lock(chain, how_maybe);
1840                                 *key_nextp = scan_end + 1;
1841                                 goto done;
1842                         }
1843                 }
1844                 /*
1845                  * Optimize indirect blocks in the INITIAL state to avoid
1846                  * I/O.
1847                  */
1848                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1849                         base = NULL;
1850                 } else {
1851                         if (parent->data == NULL)
1852                                 panic("parent->data is NULL");
1853                         base = &parent->data->npdata[0];
1854                 }
1855                 count = parent->bytes / sizeof(hammer2_blockref_t);
1856                 break;
1857         case HAMMER2_BREF_TYPE_VOLUME:
1858                 base = &parent->data->voldata.sroot_blockset.blockref[0];
1859                 count = HAMMER2_SET_COUNT;
1860                 break;
1861         case HAMMER2_BREF_TYPE_FREEMAP:
1862                 base = &parent->data->blkset.blockref[0];
1863                 count = HAMMER2_SET_COUNT;
1864                 break;
1865         default:
1866                 kprintf("hammer2_chain_lookup: unrecognized "
1867                         "blockref(B) type: %d",
1868                         parent->bref.type);
1869                 while (1)
1870                         tsleep(&base, 0, "dead", 0);
1871                 panic("hammer2_chain_lookup: unrecognized "
1872                       "blockref(B) type: %d",
1873                       parent->bref.type);
1874                 base = NULL;    /* safety */
1875                 count = 0;      /* safety */
1876         }
1877
1878         /*
1879          * Merged scan to find next candidate.
1880          *
1881          * hammer2_base_*() functions require the parent->core.live_* fields
1882          * to be synchronized.
1883          *
1884          * We need to hold the spinlock to access the block array and RB tree
1885          * and to interlock chain creation.
1886          */
1887         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1888                 hammer2_chain_countbrefs(parent, base, count);
1889
1890         /*
1891          * Combined search
1892          */
1893         hammer2_spin_ex(&parent->core.spin);
1894         chain = hammer2_combined_find(parent, base, count,
1895                                       cache_indexp, key_nextp,
1896                                       key_beg, key_end,
1897                                       &bref);
1898         generation = parent->core.generation;
1899
1900         /*
1901          * Exhausted parent chain, iterate.
1902          */
1903         if (bref == NULL) {
1904                 hammer2_spin_unex(&parent->core.spin);
1905                 if (key_beg == key_end) /* short cut single-key case */
1906                         return (NULL);
1907
1908                 /*
1909                  * Stop if we reached the end of the iteration.
1910                  */
1911                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1912                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1913                         return (NULL);
1914                 }
1915
1916                 /*
1917                  * Calculate next key, stop if we reached the end of the
1918                  * iteration, otherwise go up one level and loop.
1919                  */
1920                 key_beg = parent->bref.key +
1921                           ((hammer2_key_t)1 << parent->bref.keybits);
1922                 if (key_beg == 0 || key_beg > key_end)
1923                         return (NULL);
1924                 parent = hammer2_chain_getparent(parentp, how_maybe);
1925                 goto again;
1926         }
1927
1928         /*
1929          * Selected from blockref or in-memory chain.
1930          */
1931         if (chain == NULL) {
1932                 bcopy = *bref;
1933                 hammer2_spin_unex(&parent->core.spin);
1934                 chain = hammer2_chain_get(parent, generation,
1935                                           &bcopy);
1936                 if (chain == NULL) {
1937                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1938                                 parent, key_beg, key_end);
1939                         goto again;
1940                 }
1941                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1942                         hammer2_chain_drop(chain);
1943                         goto again;
1944                 }
1945         } else {
1946                 hammer2_chain_ref(chain);
1947                 hammer2_spin_unex(&parent->core.spin);
1948         }
1949
1950         /*
1951          * chain is referenced but not locked.  We must lock the chain
1952          * to obtain definitive DUPLICATED/DELETED state
1953          */
1954         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1955             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1956                 hammer2_chain_lock(chain, how_maybe);
1957         } else {
1958                 hammer2_chain_lock(chain, how);
1959         }
1960
1961         /*
1962          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1963          *
1964          * NOTE: Chain's key range is not relevant as there might be
1965          *       one-offs within the range that are not deleted.
1966          *
1967          * NOTE: Lookups can race delete-duplicate because
1968          *       delete-duplicate does not lock the parent's core
1969          *       (they just use the spinlock on the core).  We must
1970          *       check for races by comparing the DUPLICATED flag before
1971          *       releasing the spinlock with the flag after locking the
1972          *       chain.
1973          */
1974         if (chain->flags & HAMMER2_CHAIN_DELETED) {
1975                 hammer2_chain_unlock(chain);
1976                 hammer2_chain_drop(chain);
1977                 key_beg = *key_nextp;
1978                 if (key_beg == 0 || key_beg > key_end)
1979                         return(NULL);
1980                 goto again;
1981         }
1982
1983         /*
1984          * If the chain element is an indirect block it becomes the new
1985          * parent and we loop on it.  We must maintain our top-down locks
1986          * to prevent the flusher from interfering (i.e. doing a
1987          * delete-duplicate and leaving us recursing down a deleted chain).
1988          *
1989          * The parent always has to be locked with at least RESOLVE_MAYBE
1990          * so we can access its data.  It might need a fixup if the caller
1991          * passed incompatible flags.  Be careful not to cause a deadlock
1992          * as a data-load requires an exclusive lock.
1993          *
1994          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1995          * range is within the requested key range we return the indirect
1996          * block and do NOT loop.  This is usually only used to acquire
1997          * freemap nodes.
1998          */
1999         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2000             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2001                 hammer2_chain_unlock(parent);
2002                 hammer2_chain_drop(parent);
2003                 *parentp = parent = chain;
2004                 goto again;
2005         }
2006 done:
2007         /*
2008          * All done, return the chain.
2009          *
2010          * If the caller does not want a locked chain, replace the lock with
2011          * a ref.  Perhaps this can eventually be optimized to not obtain the
2012          * lock in the first place for situations where the data does not
2013          * need to be resolved.
2014          */
2015         if (chain) {
2016                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2017                         hammer2_chain_unlock(chain);
2018         }
2019
2020         return (chain);
2021 }
2022
2023 /*
2024  * After having issued a lookup we can iterate all matching keys.
2025  *
2026  * If chain is non-NULL we continue the iteration from just after it's index.
2027  *
2028  * If chain is NULL we assume the parent was exhausted and continue the
2029  * iteration at the next parent.
2030  *
2031  * If a fatal error occurs (typically an I/O error), a dummy chain is
2032  * returned with chain->error and error-identifying information set.  This
2033  * chain will assert if you try to do anything fancy with it.
2034  *
2035  * XXX Depending on where the error occurs we should allow continued iteration.
2036  *
2037  * parent must be locked on entry and remains locked throughout.  chain's
2038  * lock status must match flags.  Chain is always at least referenced.
2039  *
2040  * WARNING!  The MATCHIND flag does not apply to this function.
2041  */
2042 hammer2_chain_t *
2043 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2044                    hammer2_key_t *key_nextp,
2045                    hammer2_key_t key_beg, hammer2_key_t key_end,
2046                    int *cache_indexp, int flags)
2047 {
2048         hammer2_chain_t *parent;
2049         int how_maybe;
2050
2051         /*
2052          * Calculate locking flags for upward recursion.
2053          */
2054         how_maybe = HAMMER2_RESOLVE_MAYBE;
2055         if (flags & HAMMER2_LOOKUP_SHARED)
2056                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2057
2058         parent = *parentp;
2059
2060         /*
2061          * Calculate the next index and recalculate the parent if necessary.
2062          */
2063         if (chain) {
2064                 key_beg = chain->bref.key +
2065                           ((hammer2_key_t)1 << chain->bref.keybits);
2066                 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2067                               HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2068                         hammer2_chain_unlock(chain);
2069                 }
2070                 hammer2_chain_drop(chain);
2071
2072                 /*
2073                  * chain invalid past this point, but we can still do a
2074                  * pointer comparison w/parent.
2075                  *
2076                  * Any scan where the lookup returned degenerate data embedded
2077                  * in the inode has an invalid index and must terminate.
2078                  */
2079                 if (chain == parent)
2080                         return(NULL);
2081                 if (key_beg == 0 || key_beg > key_end)
2082                         return(NULL);
2083                 chain = NULL;
2084         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2085                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2086                 /*
2087                  * We reached the end of the iteration.
2088                  */
2089                 return (NULL);
2090         } else {
2091                 /*
2092                  * Continue iteration with next parent unless the current
2093                  * parent covers the range.
2094                  */
2095                 key_beg = parent->bref.key +
2096                           ((hammer2_key_t)1 << parent->bref.keybits);
2097                 if (key_beg == 0 || key_beg > key_end)
2098                         return (NULL);
2099                 parent = hammer2_chain_getparent(parentp, how_maybe);
2100         }
2101
2102         /*
2103          * And execute
2104          */
2105         return (hammer2_chain_lookup(parentp, key_nextp,
2106                                      key_beg, key_end,
2107                                      cache_indexp, flags));
2108 }
2109
2110 /*
2111  * The raw scan function is similar to lookup/next but does not seek to a key.
2112  * Blockrefs are iterated via first_bref = (parent, NULL) and
2113  * next_chain = (parent, bref).
2114  *
2115  * The passed-in parent must be locked and its data resolved.  The function
2116  * nominally returns a locked and referenced *chainp != NULL for chains
2117  * the caller might need to recurse on (and will dipose of any *chainp passed
2118  * in).  The caller must check the chain->bref.type either way.
2119  *
2120  * *chainp is not set for leaf elements.
2121  *
2122  * This function takes a pointer to a stack-based bref structure whos
2123  * contents is updated for each iteration.  The same pointer is returned,
2124  * or NULL when the iteration is complete.  *firstp must be set to 1 for
2125  * the first ieration.  This function will set it to 0.
2126  */
2127 hammer2_blockref_t *
2128 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2129                    hammer2_blockref_t *bref, int *firstp,
2130                    int *cache_indexp, int flags)
2131 {
2132         hammer2_dev_t *hmp;
2133         hammer2_blockref_t *base;
2134         hammer2_blockref_t *bref_ptr;
2135         hammer2_key_t key;
2136         hammer2_key_t next_key;
2137         hammer2_chain_t *chain = NULL;
2138         int count = 0;
2139         int how_always = HAMMER2_RESOLVE_ALWAYS;
2140         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2141         int how;
2142         int generation;
2143         int maxloops = 300000;
2144
2145         hmp = parent->hmp;
2146
2147         /*
2148          * Scan flags borrowed from lookup.
2149          */
2150         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2151                 how_maybe = how_always;
2152                 how = HAMMER2_RESOLVE_ALWAYS;
2153         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2154                 how = HAMMER2_RESOLVE_NEVER;
2155         } else {
2156                 how = HAMMER2_RESOLVE_MAYBE;
2157         }
2158         if (flags & HAMMER2_LOOKUP_SHARED) {
2159                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2160                 how_always |= HAMMER2_RESOLVE_SHARED;
2161                 how |= HAMMER2_RESOLVE_SHARED;
2162         }
2163
2164         /*
2165          * Calculate key to locate first/next element, unlocking the previous
2166          * element as we go.  Be careful, the key calculation can overflow.
2167          *
2168          * (also reset bref to NULL)
2169          */
2170         if (*firstp) {
2171                 key = 0;
2172                 *firstp = 0;
2173         } else {
2174                 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2175                 if ((chain = *chainp) != NULL) {
2176                         *chainp = NULL;
2177                         hammer2_chain_unlock(chain);
2178                         hammer2_chain_drop(chain);
2179                         chain = NULL;
2180                 }
2181                 if (key == 0) {
2182                         bref = NULL;
2183                         goto done;
2184                 }
2185         }
2186
2187 again:
2188         KKASSERT(parent->error == 0);   /* XXX case not handled yet */
2189         if (--maxloops == 0)
2190                 panic("hammer2_chain_scan: maxloops");
2191         /*
2192          * Locate the blockref array.  Currently we do a fully associative
2193          * search through the array.
2194          */
2195         switch(parent->bref.type) {
2196         case HAMMER2_BREF_TYPE_INODE:
2197                 /*
2198                  * An inode with embedded data has no sub-chains.
2199                  *
2200                  * WARNING! Bulk scan code may pass a static chain marked
2201                  *          as BREF_TYPE_INODE with a copy of the volume
2202                  *          root blockset to snapshot the volume.
2203                  */
2204                 if (parent->data->ipdata.meta.op_flags &
2205                     HAMMER2_OPFLAG_DIRECTDATA) {
2206                         bref = NULL;
2207                         goto done;
2208                 }
2209                 base = &parent->data->ipdata.u.blockset.blockref[0];
2210                 count = HAMMER2_SET_COUNT;
2211                 break;
2212         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2213         case HAMMER2_BREF_TYPE_INDIRECT:
2214                 /*
2215                  * Optimize indirect blocks in the INITIAL state to avoid
2216                  * I/O.
2217                  */
2218                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2219                         base = NULL;
2220                 } else {
2221                         if (parent->data == NULL)
2222                                 panic("parent->data is NULL");
2223                         base = &parent->data->npdata[0];
2224                 }
2225                 count = parent->bytes / sizeof(hammer2_blockref_t);
2226                 break;
2227         case HAMMER2_BREF_TYPE_VOLUME:
2228                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2229                 count = HAMMER2_SET_COUNT;
2230                 break;
2231         case HAMMER2_BREF_TYPE_FREEMAP:
2232                 base = &parent->data->blkset.blockref[0];
2233                 count = HAMMER2_SET_COUNT;
2234                 break;
2235         default:
2236                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2237                       parent->bref.type);
2238                 base = NULL;    /* safety */
2239                 count = 0;      /* safety */
2240         }
2241
2242         /*
2243          * Merged scan to find next candidate.
2244          *
2245          * hammer2_base_*() functions require the parent->core.live_* fields
2246          * to be synchronized.
2247          *
2248          * We need to hold the spinlock to access the block array and RB tree
2249          * and to interlock chain creation.
2250          */
2251         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2252                 hammer2_chain_countbrefs(parent, base, count);
2253
2254         next_key = 0;
2255         bref_ptr = NULL;
2256         hammer2_spin_ex(&parent->core.spin);
2257         chain = hammer2_combined_find(parent, base, count,
2258                                       cache_indexp, &next_key,
2259                                       key, HAMMER2_KEY_MAX,
2260                                       &bref_ptr);
2261         generation = parent->core.generation;
2262
2263         /*
2264          * Exhausted parent chain, we're done.
2265          */
2266         if (bref_ptr == NULL) {
2267                 hammer2_spin_unex(&parent->core.spin);
2268                 KKASSERT(chain == NULL);
2269                 bref = NULL;
2270                 goto done;
2271         }
2272
2273         /*
2274          * Copy into the supplied stack-based blockref.
2275          */
2276         *bref = *bref_ptr;
2277
2278         /*
2279          * Selected from blockref or in-memory chain.
2280          */
2281         if (chain == NULL) {
2282                 switch(bref->type) {
2283                 case HAMMER2_BREF_TYPE_INODE:
2284                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2285                 case HAMMER2_BREF_TYPE_INDIRECT:
2286                 case HAMMER2_BREF_TYPE_VOLUME:
2287                 case HAMMER2_BREF_TYPE_FREEMAP:
2288                         /*
2289                          * Recursion, always get the chain
2290                          */
2291                         hammer2_spin_unex(&parent->core.spin);
2292                         chain = hammer2_chain_get(parent, generation, bref);
2293                         if (chain == NULL) {
2294                                 kprintf("retry scan parent %p keys %016jx\n",
2295                                         parent, key);
2296                                 goto again;
2297                         }
2298                         if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2299                                 hammer2_chain_drop(chain);
2300                                 chain = NULL;
2301                                 goto again;
2302                         }
2303                         break;
2304                 default:
2305                         /*
2306                          * No recursion, do not waste time instantiating
2307                          * a chain, just iterate using the bref.
2308                          */
2309                         hammer2_spin_unex(&parent->core.spin);
2310                         break;
2311                 }
2312         } else {
2313                 /*
2314                  * Recursion or not we need the chain in order to supply
2315                  * the bref.
2316                  */
2317                 hammer2_chain_ref(chain);
2318                 hammer2_spin_unex(&parent->core.spin);
2319         }
2320
2321         /*
2322          * chain is referenced but not locked.  We must lock the chain
2323          * to obtain definitive DUPLICATED/DELETED state
2324          */
2325         if (chain)
2326                 hammer2_chain_lock(chain, how);
2327
2328         /*
2329          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2330          *
2331          * NOTE: chain's key range is not relevant as there might be
2332          *       one-offs within the range that are not deleted.
2333          *
2334          * NOTE: XXX this could create problems with scans used in
2335          *       situations other than mount-time recovery.
2336          *
2337          * NOTE: Lookups can race delete-duplicate because
2338          *       delete-duplicate does not lock the parent's core
2339          *       (they just use the spinlock on the core).  We must
2340          *       check for races by comparing the DUPLICATED flag before
2341          *       releasing the spinlock with the flag after locking the
2342          *       chain.
2343          */
2344         if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2345                 hammer2_chain_unlock(chain);
2346                 hammer2_chain_drop(chain);
2347                 chain = NULL;
2348
2349                 key = next_key;
2350                 if (key == 0) {
2351                         bref = NULL;
2352                         goto done;
2353                 }
2354                 goto again;
2355         }
2356
2357 done:
2358         /*
2359          * All done, return the bref or NULL, supply chain if necessary.
2360          */
2361         if (chain)
2362                 *chainp = chain;
2363         return (bref);
2364 }
2365
2366 /*
2367  * Create and return a new hammer2 system memory structure of the specified
2368  * key, type and size and insert it under (*parentp).  This is a full
2369  * insertion, based on the supplied key/keybits, and may involve creating
2370  * indirect blocks and moving other chains around via delete/duplicate.
2371  *
2372  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2373  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2374  * FULL.  This typically means that the caller is creating the chain after
2375  * doing a hammer2_chain_lookup().
2376  *
2377  * (*parentp) must be exclusive locked and may be replaced on return
2378  * depending on how much work the function had to do.
2379  *
2380  * (*parentp) must not be errored or this function will assert.
2381  *
2382  * (*chainp) usually starts out NULL and returns the newly created chain,
2383  * but if the caller desires the caller may allocate a disconnected chain
2384  * and pass it in instead.
2385  *
2386  * This function should NOT be used to insert INDIRECT blocks.  It is
2387  * typically used to create/insert inodes and data blocks.
2388  *
2389  * Caller must pass-in an exclusively locked parent the new chain is to
2390  * be inserted under, and optionally pass-in a disconnected, exclusively
2391  * locked chain to insert (else we create a new chain).  The function will
2392  * adjust (*parentp) as necessary, create or connect the chain, and
2393  * return an exclusively locked chain in *chainp.
2394  *
2395  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2396  * and will be reassigned.
2397  */
2398 int
2399 hammer2_chain_create(hammer2_chain_t **parentp,
2400                      hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2401                      hammer2_key_t key, int keybits, int type, size_t bytes,
2402                      hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2403 {
2404         hammer2_dev_t *hmp;
2405         hammer2_chain_t *chain;
2406         hammer2_chain_t *parent;
2407         hammer2_blockref_t *base;
2408         hammer2_blockref_t dummy;
2409         int allocated = 0;
2410         int error = 0;
2411         int count;
2412         int maxloops = 300000;
2413
2414         /*
2415          * Topology may be crossing a PFS boundary.
2416          */
2417         parent = *parentp;
2418         KKASSERT(hammer2_mtx_owned(&parent->lock));
2419         KKASSERT(parent->error == 0);
2420         hmp = parent->hmp;
2421         chain = *chainp;
2422
2423         if (chain == NULL) {
2424                 /*
2425                  * First allocate media space and construct the dummy bref,
2426                  * then allocate the in-memory chain structure.  Set the
2427                  * INITIAL flag for fresh chains which do not have embedded
2428                  * data.
2429                  *
2430                  * XXX for now set the check mode of the child based on
2431                  *     the parent or, if the parent is an inode, the
2432                  *     specification in the inode.
2433                  */
2434                 bzero(&dummy, sizeof(dummy));
2435                 dummy.type = type;
2436                 dummy.key = key;
2437                 dummy.keybits = keybits;
2438                 dummy.data_off = hammer2_getradix(bytes);
2439                 dummy.methods = parent->bref.methods;
2440                 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2441                     parent->data) {
2442                         dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2443                         dummy.methods |= HAMMER2_ENC_CHECK(
2444                                           parent->data->ipdata.meta.check_algo);
2445                 }
2446
2447                 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2448
2449                 /*
2450                  * Lock the chain manually, chain_lock will load the chain
2451                  * which we do NOT want to do.  (note: chain->refs is set
2452                  * to 1 by chain_alloc() for us, but lockcnt is not).
2453                  */
2454                 chain->lockcnt = 1;
2455                 hammer2_mtx_ex(&chain->lock);
2456                 allocated = 1;
2457                 ++curthread->td_tracker;
2458
2459                 /*
2460                  * Set INITIAL to optimize I/O.  The flag will generally be
2461                  * processed when we call hammer2_chain_modify().
2462                  *
2463                  * Recalculate bytes to reflect the actual media block
2464                  * allocation.
2465                  */
2466                 bytes = (hammer2_off_t)1 <<
2467                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2468                 chain->bytes = bytes;
2469
2470                 switch(type) {
2471                 case HAMMER2_BREF_TYPE_VOLUME:
2472                 case HAMMER2_BREF_TYPE_FREEMAP:
2473                         panic("hammer2_chain_create: called with volume type");
2474                         break;
2475                 case HAMMER2_BREF_TYPE_INDIRECT:
2476                         panic("hammer2_chain_create: cannot be used to"
2477                               "create indirect block");
2478                         break;
2479                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2480                         panic("hammer2_chain_create: cannot be used to"
2481                               "create freemap root or node");
2482                         break;
2483                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2484                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2485                         /* fall through */
2486                 case HAMMER2_BREF_TYPE_INODE:
2487                 case HAMMER2_BREF_TYPE_DATA:
2488                 default:
2489                         /*
2490                          * leave chain->data NULL, set INITIAL
2491                          */
2492                         KKASSERT(chain->data == NULL);
2493                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2494                         break;
2495                 }
2496         } else {
2497                 /*
2498                  * We are reattaching a previously deleted chain, possibly
2499                  * under a new parent and possibly with a new key/keybits.
2500                  * The chain does not have to be in a modified state.  The
2501                  * UPDATE flag will be set later on in this routine.
2502                  *
2503                  * Do NOT mess with the current state of the INITIAL flag.
2504                  */
2505                 chain->bref.key = key;
2506                 chain->bref.keybits = keybits;
2507                 if (chain->flags & HAMMER2_CHAIN_DELETED)
2508                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2509                 KKASSERT(chain->parent == NULL);
2510         }
2511         if (flags & HAMMER2_INSERT_PFSROOT)
2512                 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2513         else
2514                 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2515
2516         /*
2517          * Calculate how many entries we have in the blockref array and
2518          * determine if an indirect block is required.
2519          */
2520 again:
2521         if (--maxloops == 0)
2522                 panic("hammer2_chain_create: maxloops");
2523
2524         switch(parent->bref.type) {
2525         case HAMMER2_BREF_TYPE_INODE:
2526                 KKASSERT((parent->data->ipdata.meta.op_flags &
2527                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2528                 KKASSERT(parent->data != NULL);
2529                 base = &parent->data->ipdata.u.blockset.blockref[0];
2530                 count = HAMMER2_SET_COUNT;
2531                 break;
2532         case HAMMER2_BREF_TYPE_INDIRECT:
2533         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2534                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2535                         base = NULL;
2536                 else
2537                         base = &parent->data->npdata[0];
2538                 count = parent->bytes / sizeof(hammer2_blockref_t);
2539                 break;
2540         case HAMMER2_BREF_TYPE_VOLUME:
2541                 KKASSERT(parent->data != NULL);
2542                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2543                 count = HAMMER2_SET_COUNT;
2544                 break;
2545         case HAMMER2_BREF_TYPE_FREEMAP:
2546                 KKASSERT(parent->data != NULL);
2547                 base = &parent->data->blkset.blockref[0];
2548                 count = HAMMER2_SET_COUNT;
2549                 break;
2550         default:
2551                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2552                       parent->bref.type);
2553                 base = NULL;
2554                 count = 0;
2555                 break;
2556         }
2557
2558         /*
2559          * Make sure we've counted the brefs
2560          */
2561         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2562                 hammer2_chain_countbrefs(parent, base, count);
2563
2564         KKASSERT(parent->core.live_count >= 0 &&
2565                  parent->core.live_count <= count);
2566
2567         /*
2568          * If no free blockref could be found we must create an indirect
2569          * block and move a number of blockrefs into it.  With the parent
2570          * locked we can safely lock each child in order to delete+duplicate
2571          * it without causing a deadlock.
2572          *
2573          * This may return the new indirect block or the old parent depending
2574          * on where the key falls.  NULL is returned on error.
2575          */
2576         if (parent->core.live_count == count) {
2577                 hammer2_chain_t *nparent;
2578
2579                 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2580                                                         mtid, type, &error);
2581                 if (nparent == NULL) {
2582                         if (allocated)
2583                                 hammer2_chain_drop(chain);
2584                         chain = NULL;
2585                         goto done;
2586                 }
2587                 if (parent != nparent) {
2588                         hammer2_chain_unlock(parent);
2589                         hammer2_chain_drop(parent);
2590                         parent = *parentp = nparent;
2591                 }
2592                 goto again;
2593         }
2594
2595         /*
2596          * Link the chain into its parent.
2597          */
2598         if (chain->parent != NULL)
2599                 panic("hammer2: hammer2_chain_create: chain already connected");
2600         KKASSERT(chain->parent == NULL);
2601         hammer2_chain_insert(parent, chain,
2602                              HAMMER2_CHAIN_INSERT_SPIN |
2603                              HAMMER2_CHAIN_INSERT_LIVE,
2604                              0);
2605
2606         if (allocated) {
2607                 /*
2608                  * Mark the newly created chain modified.  This will cause
2609                  * UPDATE to be set and process the INITIAL flag.
2610                  *
2611                  * Device buffers are not instantiated for DATA elements
2612                  * as these are handled by logical buffers.
2613                  *
2614                  * Indirect and freemap node indirect blocks are handled
2615                  * by hammer2_chain_create_indirect() and not by this
2616                  * function.
2617                  *
2618                  * Data for all other bref types is expected to be
2619                  * instantiated (INODE, LEAF).
2620                  */
2621                 switch(chain->bref.type) {
2622                 case HAMMER2_BREF_TYPE_DATA:
2623                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2624                 case HAMMER2_BREF_TYPE_INODE:
2625                         hammer2_chain_modify(chain, mtid, dedup_off,
2626                                              HAMMER2_MODIFY_OPTDATA);
2627                         break;
2628                 default:
2629                         /*
2630                          * Remaining types are not supported by this function.
2631                          * In particular, INDIRECT and LEAF_NODE types are
2632                          * handled by create_indirect().
2633                          */
2634                         panic("hammer2_chain_create: bad type: %d",
2635                               chain->bref.type);
2636                         /* NOT REACHED */
2637                         break;
2638                 }
2639         } else {
2640                 /*
2641                  * When reconnecting a chain we must set UPDATE and
2642                  * setflush so the flush recognizes that it must update
2643                  * the bref in the parent.
2644                  */
2645                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2646                         hammer2_chain_ref(chain);
2647                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2648                 }
2649         }
2650
2651         /*
2652          * We must setflush(parent) to ensure that it recurses through to
2653          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2654          * already set in the chain (so it won't recurse up to set it in the
2655          * parent).
2656          */
2657         hammer2_chain_setflush(parent);
2658
2659 done:
2660         *chainp = chain;
2661
2662         return (error);
2663 }
2664
2665 /*
2666  * Move the chain from its old parent to a new parent.  The chain must have
2667  * already been deleted or already disconnected (or never associated) with
2668  * a parent.  The chain is reassociated with the new parent and the deleted
2669  * flag will be cleared (no longer deleted).  The chain's modification state
2670  * is not altered.
2671  *
2672  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2673  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2674  * FULL.  This typically means that the caller is creating the chain after
2675  * doing a hammer2_chain_lookup().
2676  *
2677  * A non-NULL bref is typically passed when key and keybits must be overridden.
2678  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2679  * from a passed-in bref and uses the old chain's bref for everything else.
2680  *
2681  * Neither (parent) or (chain) can be errored.
2682  *
2683  * If (parent) is non-NULL then the new duplicated chain is inserted under
2684  * the parent.
2685  *
2686  * If (parent) is NULL then the newly duplicated chain is not inserted
2687  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2688  * passing into hammer2_chain_create() after this function returns).
2689  *
2690  * WARNING! This function calls create which means it can insert indirect
2691  *          blocks.  This can cause other unrelated chains in the parent to
2692  *          be moved to a newly inserted indirect block in addition to the
2693  *          specific chain.
2694  */
2695 void
2696 hammer2_chain_rename(hammer2_blockref_t *bref,
2697                      hammer2_chain_t **parentp, hammer2_chain_t *chain,
2698                      hammer2_tid_t mtid, int flags)
2699 {
2700         hammer2_dev_t *hmp;
2701         hammer2_chain_t *parent;
2702         size_t bytes;
2703
2704         /*
2705          * WARNING!  We should never resolve DATA to device buffers
2706          *           (XXX allow it if the caller did?), and since
2707          *           we currently do not have the logical buffer cache
2708          *           buffer in-hand to fix its cached physical offset
2709          *           we also force the modify code to not COW it. XXX
2710          */
2711         hmp = chain->hmp;
2712         KKASSERT(chain->parent == NULL);
2713         KKASSERT(chain->error == 0);
2714
2715         /*
2716          * Now create a duplicate of the chain structure, associating
2717          * it with the same core, making it the same size, pointing it
2718          * to the same bref (the same media block).
2719          */
2720         if (bref == NULL)
2721                 bref = &chain->bref;
2722         bytes = (hammer2_off_t)1 <<
2723                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2724
2725         /*
2726          * If parent is not NULL the duplicated chain will be entered under
2727          * the parent and the UPDATE bit set to tell flush to update
2728          * the blockref.
2729          *
2730          * We must setflush(parent) to ensure that it recurses through to
2731          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2732          * already set in the chain (so it won't recurse up to set it in the
2733          * parent).
2734          *
2735          * Having both chains locked is extremely important for atomicy.
2736          */
2737         if (parentp && (parent = *parentp) != NULL) {
2738                 KKASSERT(hammer2_mtx_owned(&parent->lock));
2739                 KKASSERT(parent->refs > 0);
2740                 KKASSERT(parent->error == 0);
2741
2742                 hammer2_chain_create(parentp, &chain, chain->pmp,
2743                                      bref->key, bref->keybits, bref->type,
2744                                      chain->bytes, mtid, 0, flags);
2745                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2746                 hammer2_chain_setflush(*parentp);
2747         }
2748 }
2749
2750 /*
2751  * Helper function for deleting chains.
2752  *
2753  * The chain is removed from the live view (the RBTREE) as well as the parent's
2754  * blockmap.  Both chain and its parent must be locked.
2755  *
2756  * parent may not be errored.  chain can be errored.
2757  */
2758 static void
2759 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2760                              hammer2_tid_t mtid, int flags)
2761 {
2762         hammer2_dev_t *hmp;
2763
2764         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2765                                   HAMMER2_CHAIN_FICTITIOUS)) == 0);
2766         KKASSERT(chain->parent == parent);
2767         hmp = chain->hmp;
2768
2769         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2770                 /*
2771                  * Chain is blockmapped, so there must be a parent.
2772                  * Atomically remove the chain from the parent and remove
2773                  * the blockmap entry.
2774                  */
2775                 hammer2_blockref_t *base;
2776                 int count;
2777
2778                 KKASSERT(parent != NULL);
2779                 KKASSERT(parent->error == 0);
2780                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2781                 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2782
2783                 /*
2784                  * Calculate blockmap pointer
2785                  */
2786                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2787                 hammer2_spin_ex(&parent->core.spin);
2788
2789                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2790                 atomic_add_int(&parent->core.live_count, -1);
2791                 ++parent->core.generation;
2792                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2793                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2794                 --parent->core.chain_count;
2795                 chain->parent = NULL;
2796
2797                 switch(parent->bref.type) {
2798                 case HAMMER2_BREF_TYPE_INODE:
2799                         /*
2800                          * Access the inode's block array.  However, there
2801                          * is no block array if the inode is flagged
2802                          * DIRECTDATA.  The DIRECTDATA case typicaly only
2803                          * occurs when a hardlink has been shifted up the
2804                          * tree and the original inode gets replaced with
2805                          * an OBJTYPE_HARDLINK placeholding inode.
2806                          */
2807                         if (parent->data &&
2808                             (parent->data->ipdata.meta.op_flags &
2809                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2810                                 base =
2811                                    &parent->data->ipdata.u.blockset.blockref[0];
2812                         } else {
2813                                 base = NULL;
2814                         }
2815                         count = HAMMER2_SET_COUNT;
2816                         break;
2817                 case HAMMER2_BREF_TYPE_INDIRECT:
2818                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2819                         if (parent->data)
2820                                 base = &parent->data->npdata[0];
2821                         else
2822                                 base = NULL;
2823                         count = parent->bytes / sizeof(hammer2_blockref_t);
2824                         break;
2825                 case HAMMER2_BREF_TYPE_VOLUME:
2826                         base = &parent->data->voldata.
2827                                         sroot_blockset.blockref[0];
2828                         count = HAMMER2_SET_COUNT;
2829                         break;
2830                 case HAMMER2_BREF_TYPE_FREEMAP:
2831                         base = &parent->data->blkset.blockref[0];
2832                         count = HAMMER2_SET_COUNT;
2833                         break;
2834                 default:
2835                         base = NULL;
2836                         count = 0;
2837                         panic("hammer2_flush_pass2: "
2838                               "unrecognized blockref type: %d",
2839                               parent->bref.type);
2840                 }
2841
2842                 /*
2843                  * delete blockmapped chain from its parent.
2844                  *
2845                  * The parent is not affected by any statistics in chain
2846                  * which are pending synchronization.  That is, there is
2847                  * nothing to undo in the parent since they have not yet
2848                  * been incorporated into the parent.
2849                  *
2850                  * The parent is affected by statistics stored in inodes.
2851                  * Those have already been synchronized, so they must be
2852                  * undone.  XXX split update possible w/delete in middle?
2853                  */
2854                 if (base) {
2855                         int cache_index = -1;
2856                         hammer2_base_delete(parent, base, count,
2857                                             &cache_index, chain);
2858                 }
2859                 hammer2_spin_unex(&parent->core.spin);
2860         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2861                 /*
2862                  * Chain is not blockmapped but a parent is present.
2863                  * Atomically remove the chain from the parent.  There is
2864                  * no blockmap entry to remove.
2865                  *
2866                  * Because chain was associated with a parent but not
2867                  * synchronized, the chain's *_count_up fields contain
2868                  * inode adjustment statistics which must be undone.
2869                  */
2870                 hammer2_spin_ex(&parent->core.spin);
2871                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2872                 atomic_add_int(&parent->core.live_count, -1);
2873                 ++parent->core.generation;
2874                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2875                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2876                 --parent->core.chain_count;
2877                 chain->parent = NULL;
2878                 hammer2_spin_unex(&parent->core.spin);
2879         } else {
2880                 /*
2881                  * Chain is not blockmapped and has no parent.  This
2882                  * is a degenerate case.
2883                  */
2884                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2885         }
2886 }
2887
2888 /*
2889  * Create an indirect block that covers one or more of the elements in the
2890  * current parent.  Either returns the existing parent with no locking or
2891  * ref changes or returns the new indirect block locked and referenced
2892  * and leaving the original parent lock/ref intact as well.
2893  *
2894  * If an error occurs, NULL is returned and *errorp is set to the error.
2895  *
2896  * The returned chain depends on where the specified key falls.
2897  *
2898  * The key/keybits for the indirect mode only needs to follow three rules:
2899  *
2900  * (1) That all elements underneath it fit within its key space and
2901  *
2902  * (2) That all elements outside it are outside its key space.
2903  *
2904  * (3) When creating the new indirect block any elements in the current
2905  *     parent that fit within the new indirect block's keyspace must be
2906  *     moved into the new indirect block.
2907  *
2908  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2909  *     keyspace the the current parent, but lookup/iteration rules will
2910  *     ensure (and must ensure) that rule (2) for all parents leading up
2911  *     to the nearest inode or the root volume header is adhered to.  This
2912  *     is accomplished by always recursing through matching keyspaces in
2913  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
2914  *
2915  * The current implementation calculates the current worst-case keyspace by
2916  * iterating the current parent and then divides it into two halves, choosing
2917  * whichever half has the most elements (not necessarily the half containing
2918  * the requested key).
2919  *
2920  * We can also opt to use the half with the least number of elements.  This
2921  * causes lower-numbered keys (aka logical file offsets) to recurse through
2922  * fewer indirect blocks and higher-numbered keys to recurse through more.
2923  * This also has the risk of not moving enough elements to the new indirect
2924  * block and being forced to create several indirect blocks before the element
2925  * can be inserted.
2926  *
2927  * Must be called with an exclusively locked parent.
2928  */
2929 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2930                                 hammer2_key_t *keyp, int keybits,
2931                                 hammer2_blockref_t *base, int count);
2932 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2933                                 hammer2_key_t *keyp, int keybits,
2934                                 hammer2_blockref_t *base, int count);
2935 static
2936 hammer2_chain_t *
2937 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2938                               hammer2_key_t create_key, int create_bits,
2939                               hammer2_tid_t mtid, int for_type, int *errorp)
2940 {
2941         hammer2_dev_t *hmp;
2942         hammer2_blockref_t *base;
2943         hammer2_blockref_t *bref;
2944         hammer2_blockref_t bcopy;
2945         hammer2_chain_t *chain;
2946         hammer2_chain_t *ichain;
2947         hammer2_chain_t dummy;
2948         hammer2_key_t key = create_key;
2949         hammer2_key_t key_beg;
2950         hammer2_key_t key_end;
2951         hammer2_key_t key_next;
2952         int keybits = create_bits;
2953         int count;
2954         int nbytes;
2955         int cache_index;
2956         int loops;
2957         int reason;
2958         int generation;
2959         int maxloops = 300000;
2960
2961         /*
2962          * Calculate the base blockref pointer or NULL if the chain
2963          * is known to be empty.  We need to calculate the array count
2964          * for RB lookups either way.
2965          */
2966         hmp = parent->hmp;
2967         *errorp = 0;
2968         KKASSERT(hammer2_mtx_owned(&parent->lock));
2969
2970         /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2971         base = hammer2_chain_base_and_count(parent, &count);
2972
2973         /*
2974          * dummy used in later chain allocation (no longer used for lookups).
2975          */
2976         bzero(&dummy, sizeof(dummy));
2977
2978         /*
2979          * When creating an indirect block for a freemap node or leaf
2980          * the key/keybits must be fitted to static radix levels because
2981          * particular radix levels use particular reserved blocks in the
2982          * related zone.
2983          *
2984          * This routine calculates the key/radix of the indirect block
2985          * we need to create, and whether it is on the high-side or the
2986          * low-side.
2987          */
2988         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2989             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2990                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2991                                                        base, count);
2992         } else {
2993                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2994                                                       base, count);
2995         }
2996
2997         /*
2998          * Normalize the key for the radix being represented, keeping the
2999          * high bits and throwing away the low bits.
3000          */
3001         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3002
3003         /*
3004          * How big should our new indirect block be?  It has to be at least
3005          * as large as its parent.
3006          *
3007          * The freemap uses a specific indirect block size.
3008          *
3009          * The first indirect block level down from an inode typically
3010          * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3011          */
3012         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3013             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3014                 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3015         } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3016                 nbytes = HAMMER2_IND_BYTES_MIN;
3017         } else {
3018                 nbytes = HAMMER2_IND_BYTES_MAX;
3019         }
3020         if (nbytes < count * sizeof(hammer2_blockref_t)) {
3021                 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3022                          for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3023                 nbytes = count * sizeof(hammer2_blockref_t);
3024         }
3025
3026         /*
3027          * Ok, create our new indirect block
3028          */
3029         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3030             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3031                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3032         } else {
3033                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3034         }
3035         dummy.bref.key = key;
3036         dummy.bref.keybits = keybits;
3037         dummy.bref.data_off = hammer2_getradix(nbytes);
3038         dummy.bref.methods = parent->bref.methods;
3039
3040         ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3041         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3042         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3043         /* ichain has one ref at this point */
3044
3045         /*
3046          * We have to mark it modified to allocate its block, but use
3047          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3048          * it won't be acted upon by the flush code.
3049          */
3050         hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3051
3052         /*
3053          * Iterate the original parent and move the matching brefs into
3054          * the new indirect block.
3055          *
3056          * XXX handle flushes.
3057          */
3058         key_beg = 0;
3059         key_end = HAMMER2_KEY_MAX;
3060         cache_index = 0;
3061         hammer2_spin_ex(&parent->core.spin);
3062         loops = 0;
3063         reason = 0;
3064
3065         for (;;) {
3066                 /*
3067                  * Parent may have been modified, relocating its block array.
3068                  * Reload the base pointer.
3069                  */
3070                 base = hammer2_chain_base_and_count(parent, &count);
3071
3072                 if (++loops > 100000) {
3073                     hammer2_spin_unex(&parent->core.spin);
3074                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3075                           reason, parent, base, count, key_next);
3076                 }
3077
3078                 /*
3079                  * NOTE: spinlock stays intact, returned chain (if not NULL)
3080                  *       is not referenced or locked which means that we
3081                  *       cannot safely check its flagged / deletion status
3082                  *       until we lock it.
3083                  */
3084                 chain = hammer2_combined_find(parent, base, count,
3085                                               &cache_index, &key_next,
3086                                               key_beg, key_end,
3087                                               &bref);
3088                 generation = parent->core.generation;
3089                 if (bref == NULL)
3090                         break;
3091                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3092
3093                 /*
3094                  * Skip keys that are not within the key/radix of the new
3095                  * indirect block.  They stay in the parent.
3096                  */
3097                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3098                     (key ^ bref->key)) != 0) {
3099                         goto next_key_spinlocked;
3100                 }
3101
3102                 /*
3103                  * Load the new indirect block by acquiring the related
3104                  * chains (potentially from media as it might not be
3105                  * in-memory).  Then move it to the new parent (ichain)
3106                  * via DELETE-DUPLICATE.
3107                  *
3108                  * chain is referenced but not locked.  We must lock the
3109                  * chain to obtain definitive DUPLICATED/DELETED state
3110                  */
3111                 if (chain) {
3112                         /*
3113                          * Use chain already present in the RBTREE
3114                          */
3115                         hammer2_chain_ref(chain);
3116                         hammer2_spin_unex(&parent->core.spin);
3117                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3118                 } else {
3119                         /*
3120                          * Get chain for blockref element.  _get returns NULL
3121                          * on insertion race.
3122                          */
3123                         bcopy = *bref;
3124                         hammer2_spin_unex(&parent->core.spin);
3125                         chain = hammer2_chain_get(parent, generation, &bcopy);
3126                         if (chain == NULL) {
3127                                 reason = 1;
3128                                 hammer2_spin_ex(&parent->core.spin);
3129                                 continue;
3130                         }
3131                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3132                                 kprintf("REASON 2\n");
3133                                 reason = 2;
3134                                 hammer2_chain_drop(chain);
3135                                 hammer2_spin_ex(&parent->core.spin);
3136                                 continue;
3137                         }
3138                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3139                 }
3140
3141                 /*
3142                  * This is always live so if the chain has been deleted
3143                  * we raced someone and we have to retry.
3144                  *
3145                  * NOTE: Lookups can race delete-duplicate because
3146                  *       delete-duplicate does not lock the parent's core
3147                  *       (they just use the spinlock on the core).  We must
3148                  *       check for races by comparing the DUPLICATED flag before
3149                  *       releasing the spinlock with the flag after locking the
3150                  *       chain.
3151                  *
3152                  *       (note reversed logic for this one)
3153                  */
3154                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3155                         hammer2_chain_unlock(chain);
3156                         hammer2_chain_drop(chain);
3157                         goto next_key;
3158                 }
3159
3160                 /*
3161                  * Shift the chain to the indirect block.
3162                  *
3163                  * WARNING! No reason for us to load chain data, pass NOSTATS
3164                  *          to prevent delete/insert from trying to access
3165                  *          inode stats (and thus asserting if there is no
3166                  *          chain->data loaded).
3167                  *
3168                  * WARNING! The (parent, chain) deletion may modify the parent
3169                  *          and invalidate the base pointer.
3170                  */
3171                 hammer2_chain_delete(parent, chain, mtid, 0);
3172                 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3173                 hammer2_chain_unlock(chain);
3174                 hammer2_chain_drop(chain);
3175                 KKASSERT(parent->refs > 0);
3176                 chain = NULL;
3177                 base = NULL;    /* safety */
3178 next_key:
3179                 hammer2_spin_ex(&parent->core.spin);
3180 next_key_spinlocked:
3181                 if (--maxloops == 0)
3182                         panic("hammer2_chain_create_indirect: maxloops");
3183                 reason = 4;
3184                 if (key_next == 0 || key_next > key_end)
3185                         break;
3186                 key_beg = key_next;
3187                 /* loop */
3188         }
3189         hammer2_spin_unex(&parent->core.spin);
3190
3191         /*
3192          * Insert the new indirect block into the parent now that we've
3193          * cleared out some entries in the parent.  We calculated a good
3194          * insertion index in the loop above (ichain->index).
3195          *
3196          * We don't have to set UPDATE here because we mark ichain
3197          * modified down below (so the normal modified -> flush -> set-moved
3198          * sequence applies).
3199          *
3200          * The insertion shouldn't race as this is a completely new block
3201          * and the parent is locked.
3202          */
3203         base = NULL;    /* safety, parent modify may change address */
3204         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3205         hammer2_chain_insert(parent, ichain,
3206                              HAMMER2_CHAIN_INSERT_SPIN |
3207                              HAMMER2_CHAIN_INSERT_LIVE,
3208                              0);
3209
3210         /*
3211          * Make sure flushes propogate after our manual insertion.
3212          */
3213         hammer2_chain_setflush(ichain);
3214         hammer2_chain_setflush(parent);
3215
3216         /*
3217          * Figure out what to return.
3218          */
3219         if (~(((hammer2_key_t)1 << keybits) - 1) &
3220                    (create_key ^ key)) {
3221                 /*
3222                  * Key being created is outside the key range,
3223                  * return the original parent.
3224                  */
3225                 hammer2_chain_unlock(ichain);
3226                 hammer2_chain_drop(ichain);
3227         } else {
3228                 /*
3229                  * Otherwise its in the range, return the new parent.
3230                  * (leave both the new and old parent locked).
3231                  */
3232                 parent = ichain;
3233         }
3234
3235         return(parent);
3236 }
3237
3238 /*
3239  * Calculate the keybits and highside/lowside of the freemap node the
3240  * caller is creating.
3241  *
3242  * This routine will specify the next higher-level freemap key/radix
3243  * representing the lowest-ordered set.  By doing so, eventually all
3244  * low-ordered sets will be moved one level down.
3245  *
3246  * We have to be careful here because the freemap reserves a limited
3247  * number of blocks for a limited number of levels.  So we can't just
3248  * push indiscriminately.
3249  */
3250 int
3251 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3252                              int keybits, hammer2_blockref_t *base, int count)
3253 {
3254         hammer2_chain_t *chain;
3255         hammer2_blockref_t *bref;
3256         hammer2_key_t key;
3257         hammer2_key_t key_beg;
3258         hammer2_key_t key_end;
3259         hammer2_key_t key_next;
3260         int cache_index;
3261         int locount;
3262         int hicount;
3263         int maxloops = 300000;
3264
3265         key = *keyp;
3266         locount = 0;
3267         hicount = 0;
3268         keybits = 64;
3269
3270         /*
3271          * Calculate the range of keys in the array being careful to skip
3272          * slots which are overridden with a deletion.
3273          */
3274         key_beg = 0;
3275         key_end = HAMMER2_KEY_MAX;
3276         cache_index = 0;
3277         hammer2_spin_ex(&parent->core.spin);
3278
3279         for (;;) {
3280                 if (--maxloops == 0) {
3281                         panic("indkey_freemap shit %p %p:%d\n",
3282                               parent, base, count);
3283                 }
3284                 chain = hammer2_combined_find(parent, base, count,
3285                                               &cache_index, &key_next,
3286                                               key_beg, key_end,
3287                                               &bref);
3288
3289                 /*
3290                  * Exhausted search
3291                  */
3292                 if (bref == NULL)
3293                         break;
3294
3295                 /*
3296                  * Skip deleted chains.
3297                  */
3298                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3299                         if (key_next == 0 || key_next > key_end)
3300                                 break;
3301                         key_beg = key_next;
3302                         continue;
3303                 }
3304
3305                 /*
3306                  * Use the full live (not deleted) element for the scan
3307                  * iteration.  HAMMER2 does not allow partial replacements.
3308                  *
3309                  * XXX should be built into hammer2_combined_find().
3310                  */
3311                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3312
3313                 if (keybits > bref->keybits) {
3314                         key = bref->key;
3315                         keybits = bref->keybits;
3316                 } else if (keybits == bref->keybits && bref->key < key) {
3317                         key = bref->key;
3318                 }
3319                 if (key_next == 0)
3320                         break;
3321                 key_beg = key_next;
3322         }
3323         hammer2_spin_unex(&parent->core.spin);
3324
3325         /*
3326          * Return the keybits for a higher-level FREEMAP_NODE covering
3327          * this node.
3328          */
3329         switch(keybits) {
3330         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3331                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3332                 break;
3333         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3334                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3335                 break;
3336         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3337                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3338                 break;
3339         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3340                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3341                 break;
3342         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3343                 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3344                 break;
3345         case HAMMER2_FREEMAP_LEVEL5_RADIX:
3346                 panic("hammer2_chain_indkey_freemap: level too high");
3347                 break;
3348         default:
3349                 panic("hammer2_chain_indkey_freemap: bad radix");
3350                 break;
3351         }
3352         *keyp = key;
3353
3354         return (keybits);
3355 }
3356
3357 /*
3358  * Calculate the keybits and highside/lowside of the indirect block the
3359  * caller is creating.
3360  */
3361 static int
3362 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3363                             int keybits, hammer2_blockref_t *base, int count)
3364 {
3365         hammer2_blockref_t *bref;
3366         hammer2_chain_t *chain;
3367         hammer2_key_t key_beg;
3368         hammer2_key_t key_end;
3369         hammer2_key_t key_next;
3370         hammer2_key_t key;
3371         int nkeybits;
3372         int locount;
3373         int hicount;
3374         int cache_index;
3375         int maxloops = 300000;
3376
3377         key = *keyp;
3378         locount = 0;
3379         hicount = 0;
3380
3381         /*
3382          * Calculate the range of keys in the array being careful to skip
3383          * slots which are overridden with a deletion.  Once the scan
3384          * completes we will cut the key range in half and shift half the
3385          * range into the new indirect block.
3386          */
3387         key_beg = 0;
3388         key_end = HAMMER2_KEY_MAX;
3389         cache_index = 0;
3390         hammer2_spin_ex(&parent->core.spin);
3391
3392         for (;;) {
3393                 if (--maxloops == 0) {
3394                         panic("indkey_freemap shit %p %p:%d\n",
3395                               parent, base, count);
3396                 }
3397                 chain = hammer2_combined_find(parent, base, count,
3398                                               &cache_index, &key_next,
3399                                               key_beg, key_end,
3400                                               &bref);
3401
3402                 /*
3403                  * Exhausted search
3404                  */
3405                 if (bref == NULL)
3406                         break;
3407
3408                 /*
3409                  * NOTE: No need to check DUPLICATED here because we do
3410                  *       not release the spinlock.
3411                  */
3412                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3413                         if (key_next == 0 || key_next > key_end)
3414                                 break;
3415                         key_beg = key_next;
3416                         continue;
3417                 }
3418
3419                 /*
3420                  * Use the full live (not deleted) element for the scan
3421                  * iteration.  HAMMER2 does not allow partial replacements.
3422                  *
3423                  * XXX should be built into hammer2_combined_find().
3424                  */
3425                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3426
3427                 /*
3428                  * Expand our calculated key range (key, keybits) to fit
3429                  * the scanned key.  nkeybits represents the full range
3430                  * that we will later cut in half (two halves @ nkeybits - 1).
3431                  */
3432                 nkeybits = keybits;
3433                 if (nkeybits < bref->keybits) {
3434                         if (bref->keybits > 64) {
3435                                 kprintf("bad bref chain %p bref %p\n",
3436                                         chain, bref);
3437                                 Debugger("fubar");
3438                         }
3439                         nkeybits = bref->keybits;
3440                 }
3441                 while (nkeybits < 64 &&
3442                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3443                         (key ^ bref->key)) != 0) {
3444                         ++nkeybits;
3445                 }
3446
3447                 /*
3448                  * If the new key range is larger we have to determine
3449                  * which side of the new key range the existing keys fall
3450                  * under by checking the high bit, then collapsing the
3451                  * locount into the hicount or vise-versa.
3452                  */
3453                 if (keybits != nkeybits) {
3454                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3455                                 hicount += locount;
3456                                 locount = 0;
3457                         } else {
3458                                 locount += hicount;
3459                                 hicount = 0;
3460                         }
3461                         keybits = nkeybits;
3462                 }
3463
3464                 /*
3465                  * The newly scanned key will be in the lower half or the
3466                  * upper half of the (new) key range.
3467                  */
3468                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3469                         ++hicount;
3470                 else
3471                         ++locount;
3472
3473                 if (key_next == 0)
3474                         break;
3475                 key_beg = key_next;
3476         }
3477         hammer2_spin_unex(&parent->core.spin);
3478         bref = NULL;    /* now invalid (safety) */
3479
3480         /*
3481          * Adjust keybits to represent half of the full range calculated
3482          * above (radix 63 max)
3483          */
3484         --keybits;
3485
3486         /*
3487          * Select whichever half contains the most elements.  Theoretically
3488          * we can select either side as long as it contains at least one
3489          * element (in order to ensure that a free slot is present to hold
3490          * the indirect block).
3491          */
3492         if (hammer2_indirect_optimize) {
3493                 /*
3494                  * Insert node for least number of keys, this will arrange
3495                  * the first few blocks of a large file or the first few
3496                  * inodes in a directory with fewer indirect blocks when
3497                  * created linearly.
3498                  */
3499                 if (hicount < locount && hicount != 0)
3500                         key |= (hammer2_key_t)1 << keybits;
3501                 else
3502                         key &= ~(hammer2_key_t)1 << keybits;
3503         } else {
3504                 /*
3505                  * Insert node for most number of keys, best for heavily
3506                  * fragmented files.
3507                  */
3508                 if (hicount > locount)
3509                         key |= (hammer2_key_t)1 << keybits;
3510                 else
3511                         key &= ~(hammer2_key_t)1 << keybits;
3512         }
3513         *keyp = key;
3514
3515         return (keybits);
3516 }
3517
3518 /*
3519  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3520  * it exists.
3521  *
3522  * Both parent and chain must be locked exclusively.
3523  *
3524  * This function will modify the parent if the blockref requires removal
3525  * from the parent's block table.
3526  *
3527  * This function is NOT recursive.  Any entity already pushed into the
3528  * chain (such as an inode) may still need visibility into its contents,
3529  * as well as the ability to read and modify the contents.  For example,
3530  * for an unlinked file which is still open.
3531  */
3532 void
3533 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3534                      hammer2_tid_t mtid, int flags)
3535 {
3536         KKASSERT(hammer2_mtx_owned(&chain->lock));
3537
3538         /*
3539          * Nothing to do if already marked.
3540          *
3541          * We need the spinlock on the core whos RBTREE contains chain
3542          * to protect against races.
3543          */
3544         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3545                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3546                          chain->parent == parent);
3547                 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3548         }
3549
3550         /*
3551          * To avoid losing track of a permanent deletion we add the chain
3552          * to the delayed flush queue.  If we were to flush it right now the
3553          * parent would end up in a modified state and generate I/O.
3554          * The delayed queue gives the parent a chance to be deleted to
3555          * (e.g. rm -rf).
3556          */
3557         if (flags & HAMMER2_DELETE_PERMANENT) {
3558                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3559                 hammer2_delayed_flush(chain);
3560         } else {
3561                 /* XXX might not be needed */
3562                 hammer2_chain_setflush(chain);
3563         }
3564 }
3565
3566 /*
3567  * Returns the index of the nearest element in the blockref array >= elm.
3568  * Returns (count) if no element could be found.
3569  *
3570  * Sets *key_nextp to the next key for loop purposes but does not modify
3571  * it if the next key would be higher than the current value of *key_nextp.
3572  * Note that *key_nexp can overflow to 0, which should be tested by the
3573  * caller.
3574  *
3575  * (*cache_indexp) is a heuristic and can be any value without effecting
3576  * the result.
3577  *
3578  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3579  *           held through the operation.
3580  */
3581 static int
3582 hammer2_base_find(hammer2_chain_t *parent,
3583                   hammer2_blockref_t *base, int count,
3584                   int *cache_indexp, hammer2_key_t *key_nextp,
3585                   hammer2_key_t key_beg, hammer2_key_t key_end)
3586 {
3587         hammer2_blockref_t *scan;
3588         hammer2_key_t scan_end;
3589         int i;
3590         int limit;
3591
3592         /*
3593          * Require the live chain's already have their core's counted
3594          * so we can optimize operations.
3595          */
3596         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3597
3598         /*
3599          * Degenerate case
3600          */
3601         if (count == 0 || base == NULL)
3602                 return(count);
3603
3604         /*
3605          * Sequential optimization using *cache_indexp.  This is the most
3606          * likely scenario.
3607          *
3608          * We can avoid trailing empty entries on live chains, otherwise
3609          * we might have to check the whole block array.
3610          */
3611         i = *cache_indexp;
3612         cpu_ccfence();
3613         limit = parent->core.live_zero;
3614         if (i >= limit)
3615                 i = limit - 1;
3616         if (i < 0)
3617                 i = 0;
3618         KKASSERT(i < count);
3619
3620         /*
3621          * Search backwards
3622          */
3623         scan = &base[i];
3624         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3625                 --scan;
3626                 --i;
3627         }
3628         *cache_indexp = i;
3629
3630         /*
3631          * Search forwards, stop when we find a scan element which
3632          * encloses the key or until we know that there are no further
3633          * elements.
3634          */
3635         while (i < count) {
3636                 if (scan->type != 0) {
3637                         scan_end = scan->key +
3638                                    ((hammer2_key_t)1 << scan->keybits) - 1;
3639                         if (scan->key > key_beg || scan_end >= key_beg)
3640                                 break;
3641                 }
3642                 if (i >= limit)
3643                         return (count);
3644                 ++scan;
3645                 ++i;
3646         }
3647         if (i != count) {
3648                 *cache_indexp = i;
3649                 if (i >= limit) {
3650                         i = count;
3651                 } else {
3652                         scan_end = scan->key +
3653                                    ((hammer2_key_t)1 << scan->keybits);
3654                         if (scan_end && (*key_nextp > scan_end ||
3655                                          *key_nextp == 0)) {
3656                                 *key_nextp = scan_end;
3657                         }
3658                 }
3659         }
3660         return (i);
3661 }
3662
3663 /*
3664  * Do a combined search and return the next match either from the blockref
3665  * array or from the in-memory chain.  Sets *bresp to the returned bref in
3666  * both cases, or sets it to NULL if the search exhausted.  Only returns
3667  * a non-NULL chain if the search matched from the in-memory chain.
3668  *
3669  * When no in-memory chain has been found and a non-NULL bref is returned
3670  * in *bresp.
3671  *
3672  *
3673  * The returned chain is not locked or referenced.  Use the returned bref
3674  * to determine if the search exhausted or not.  Iterate if the base find
3675  * is chosen but matches a deleted chain.
3676  *
3677  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3678  *           held through the operation.
3679  */
3680 static hammer2_chain_t *
3681 hammer2_combined_find(hammer2_chain_t *parent,
3682                       hammer2_blockref_t *base, int count,
3683                       int *cache_indexp, hammer2_key_t *key_nextp,
3684                       hammer2_key_t key_beg, hammer2_key_t key_end,
3685                       hammer2_blockref_t **bresp)
3686 {
3687         hammer2_blockref_t *bref;
3688         hammer2_chain_t *chain;
3689         int i;
3690
3691         /*
3692          * Lookup in block array and in rbtree.
3693          */
3694         *key_nextp = key_end + 1;
3695         i = hammer2_base_find(parent, base, count, cache_indexp,
3696                               key_nextp, key_beg, key_end);
3697         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3698
3699         /*
3700          * Neither matched
3701          */
3702         if (i == count && chain == NULL) {
3703                 *bresp = NULL;
3704                 return(NULL);
3705         }
3706
3707         /*
3708          * Only chain matched.
3709          */
3710         if (i == count) {
3711                 bref = &chain->bref;
3712                 goto found;
3713         }
3714
3715         /*
3716          * Only blockref matched.
3717          */
3718         if (chain == NULL) {
3719                 bref = &base[i];
3720                 goto found;
3721         }
3722
3723         /*
3724          * Both in-memory and blockref matched, select the nearer element.
3725          *
3726          * If both are flush with the left-hand side or both are the
3727          * same distance away, select the chain.  In this situation the
3728          * chain must have been loaded from the matching blockmap.
3729          */
3730         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3731             chain->bref.key == base[i].key) {
3732                 KKASSERT(chain->bref.key == base[i].key);
3733                 bref = &chain->bref;
3734                 goto found;
3735         }
3736
3737         /*
3738          * Select the nearer key
3739          */
3740         if (chain->bref.key < base[i].key) {
3741                 bref = &chain->bref;
3742         } else {
3743                 bref = &base[i];
3744                 chain = NULL;
3745         }
3746
3747         /*
3748          * If the bref is out of bounds we've exhausted our search.
3749          */
3750 found:
3751         if (bref->key > key_end) {
3752                 *bresp = NULL;
3753                 chain = NULL;
3754         } else {
3755                 *bresp = bref;
3756         }
3757         return(chain);
3758 }
3759
3760 /*
3761  * Locate the specified block array element and delete it.  The element
3762  * must exist.
3763  *
3764  * The spin lock on the related chain must be held.
3765  *
3766  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3767  *       need to be adjusted when we commit the media change.
3768  */
3769 void
3770 hammer2_base_delete(hammer2_chain_t *parent,
3771                     hammer2_blockref_t *base, int count,
3772                     int *cache_indexp, hammer2_chain_t *chain)
3773 {
3774         hammer2_blockref_t *elm = &chain->bref;
3775         hammer2_key_t key_next;
3776         int i;
3777
3778         /*
3779          * Delete element.  Expect the element to exist.
3780          *
3781          * XXX see caller, flush code not yet sophisticated enough to prevent
3782          *     re-flushed in some cases.
3783          */
3784         key_next = 0; /* max range */
3785         i = hammer2_base_find(parent, base, count, cache_indexp,
3786                               &key_next, elm->key, elm->key);
3787         if (i == count || base[i].type == 0 ||
3788             base[i].key != elm->key ||
3789             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3790              base[i].keybits != elm->keybits)) {
3791                 hammer2_spin_unex(&parent->core.spin);
3792                 panic("delete base %p element not found at %d/%d elm %p\n",
3793                       base, i, count, elm);
3794                 return;
3795         }
3796
3797         /*
3798          * Update stats and zero the entry
3799          */
3800         parent->bref.data_count -= base[i].data_count;
3801         parent->bref.data_count -= (hammer2_off_t)1 <<
3802                         (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3803         parent->bref.inode_count -= base[i].inode_count;
3804         if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3805                 parent->bref.inode_count -= 1;
3806
3807         bzero(&base[i], sizeof(*base));
3808
3809         /*
3810          * We can only optimize parent->core.live_zero for live chains.
3811          */
3812         if (parent->core.live_zero == i + 1) {
3813                 while (--i >= 0 && base[i].type == 0)
3814                         ;
3815                 parent->core.live_zero = i + 1;
3816         }
3817
3818         /*
3819          * Clear appropriate blockmap flags in chain.
3820          */
3821         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3822                                         HAMMER2_CHAIN_BMAPUPD);
3823 }
3824
3825 /*
3826  * Insert the specified element.  The block array must not already have the
3827  * element and must have space available for the insertion.
3828  *
3829  * The spin lock on the related chain must be held.
3830  *
3831  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3832  *       need to be adjusted when we commit the media change.
3833  */
3834 void
3835 hammer2_base_insert(hammer2_chain_t *parent,
3836                     hammer2_blockref_t *base, int count,
3837                     int *cache_indexp, hammer2_chain_t *chain)
3838 {
3839         hammer2_blockref_t *elm = &chain->bref;
3840         hammer2_key_t key_next;
3841         hammer2_key_t xkey;
3842         int i;
3843         int j;
3844         int k;
3845         int l;
3846         int u = 1;
3847
3848         /*
3849          * Insert new element.  Expect the element to not already exist
3850          * unless we are replacing it.
3851          *
3852          * XXX see caller, flush code not yet sophisticated enough to prevent
3853          *     re-flushed in some cases.
3854          */
3855         key_next = 0; /* max range */
3856         i = hammer2_base_find(parent, base, count, cache_indexp,
3857                               &key_next, elm->key, elm->key);
3858
3859         /*
3860          * Shortcut fill optimization, typical ordered insertion(s) may not
3861          * require a search.
3862          */
3863         KKASSERT(i >= 0 && i <= count);
3864
3865         /*
3866          * Set appropriate blockmap flags in chain.
3867          */
3868         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3869
3870         /*
3871          * Update stats and zero the entry
3872          */
3873         parent->bref.data_count += elm->data_count;
3874         parent->bref.data_count += (hammer2_off_t)1 <<
3875                         (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3876         parent->bref.inode_count += elm->inode_count;
3877         if (elm->type == HAMMER2_BREF_TYPE_INODE)
3878                 parent->bref.inode_count += 1;
3879
3880
3881         /*
3882          * We can only optimize parent->core.live_zero for live chains.
3883          */
3884         if (i == count && parent->core.live_zero < count) {
3885                 i = parent->core.live_zero++;
3886                 base[i] = *elm;
3887                 return;
3888         }
3889
3890         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3891         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3892                 hammer2_spin_unex(&parent->core.spin);
3893                 panic("insert base %p overlapping elements at %d elm %p\n",
3894                       base, i, elm);
3895         }
3896
3897         /*
3898          * Try to find an empty slot before or after.
3899          */
3900         j = i;
3901         k = i;
3902         while (j > 0 || k < count) {
3903                 --j;
3904                 if (j >= 0 && base[j].type == 0) {
3905                         if (j == i - 1) {
3906                                 base[j] = *elm;
3907                         } else {
3908                                 bcopy(&base[j+1], &base[j],
3909                                       (i - j - 1) * sizeof(*base));
3910                                 base[i - 1] = *elm;
3911                         }
3912                         goto validate;
3913                 }
3914                 ++k;
3915                 if (k < count && base[k].type == 0) {
3916                         bcopy(&base[i], &base[i+1],
3917                               (k - i) * sizeof(hammer2_blockref_t));
3918                         base[i] = *elm;
3919
3920                         /*
3921                          * We can only update parent->core.live_zero for live
3922                          * chains.
3923                          */
3924                         if (parent->core.live_zero <= k)
3925                                 parent->core.live_zero = k + 1;
3926                         u = 2;
3927                         goto validate;
3928                 }
3929         }
3930         panic("hammer2_base_insert: no room!");
3931
3932         /*
3933          * Debugging
3934          */
3935 validate:
3936         key_next = 0;
3937         for (l = 0; l < count; ++l) {
3938                 if (base[l].type) {
3939                         key_next = base[l].key +
3940                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3941                         break;
3942                 }
3943         }
3944         while (++l < count) {
3945                 if (base[l].type) {
3946                         if (base[l].key <= key_next)
3947                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3948                         key_next = base[l].key +
3949                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3950
3951                 }
3952         }
3953
3954 }
3955
3956 #if 0
3957
3958 /*
3959  * Sort the blockref array for the chain.  Used by the flush code to
3960  * sort the blockref[] array.
3961  *
3962  * The chain must be exclusively locked AND spin-locked.
3963  */
3964 typedef hammer2_blockref_t *hammer2_blockref_p;
3965
3966 static
3967 int
3968 hammer2_base_sort_callback(const void *v1, const void *v2)
3969 {
3970         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3971         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3972
3973         /*
3974          * Make sure empty elements are placed at the end of the array
3975          */
3976         if (bref1->type == 0) {
3977                 if (bref2->type == 0)
3978                         return(0);
3979                 return(1);
3980         } else if (bref2->type == 0) {
3981                 return(-1);
3982         }
3983
3984         /*
3985          * Sort by key
3986          */
3987         if (bref1->key < bref2->key)
3988                 return(-1);
3989         if (bref1->key > bref2->key)
3990                 return(1);
3991         return(0);
3992 }
3993
3994 void
3995 hammer2_base_sort(hammer2_chain_t *chain)
3996 {
3997         hammer2_blockref_t *base;
3998         int count;
3999
4000         switch(chain->bref.type) {
4001         case HAMMER2_BREF_TYPE_INODE:
4002                 /*
4003                  * Special shortcut for embedded data returns the inode
4004                  * itself.  Callers must detect this condition and access
4005                  * the embedded data (the strategy code does this for us).
4006                  *
4007                  * This is only applicable to regular files and softlinks.
4008                  */
4009                 if (chain->data->ipdata.meta.op_flags &
4010                     HAMMER2_OPFLAG_DIRECTDATA) {
4011                         return;
4012                 }
4013                 base = &chain->data->ipdata.u.blockset.blockref[0];
4014                 count = HAMMER2_SET_COUNT;
4015                 break;
4016         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4017         case HAMMER2_BREF_TYPE_INDIRECT:
4018                 /*
4019                  * Optimize indirect blocks in the INITIAL state to avoid
4020                  * I/O.
4021                  */
4022                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4023                 base = &chain->data->npdata[0];
4024                 count = chain->bytes / sizeof(hammer2_blockref_t);
4025                 break;
4026         case HAMMER2_BREF_TYPE_VOLUME:
4027                 base = &chain->data->voldata.sroot_blockset.blockref[0];
4028                 count = HAMMER2_SET_COUNT;
4029                 break;
4030         case HAMMER2_BREF_TYPE_FREEMAP:
4031                 base = &chain->data->blkset.blockref[0];
4032                 count = HAMMER2_SET_COUNT;
4033                 break;
4034         default:
4035                 kprintf("hammer2_chain_lookup: unrecognized "
4036                         "blockref(A) type: %d",
4037                         chain->bref.type);
4038                 while (1)
4039                         tsleep(&base, 0, "dead", 0);
4040                 panic("hammer2_chain_lookup: unrecognized "
4041                       "blockref(A) type: %d",
4042                       chain->bref.type);
4043                 base = NULL;    /* safety */
4044                 count = 0;      /* safety */
4045         }
4046         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4047 }
4048
4049 #endif
4050
4051 /*
4052  * Chain memory management
4053  */
4054 void
4055 hammer2_chain_wait(hammer2_chain_t *chain)
4056 {
4057         tsleep(chain, 0, "chnflw", 1);
4058 }
4059
4060 const hammer2_media_data_t *
4061 hammer2_chain_rdata(hammer2_chain_t *chain)
4062 {
4063         KKASSERT(chain->data != NULL);
4064         return (chain->data);
4065 }
4066
4067 hammer2_media_data_t *
4068 hammer2_chain_wdata(hammer2_chain_t *chain)
4069 {
4070         KKASSERT(chain->data != NULL);
4071         return (chain->data);
4072 }
4073
4074 /*
4075  * Set the check data for a chain.  This can be a heavy-weight operation
4076  * and typically only runs on-flush.  For file data check data is calculated
4077  * when the logical buffers are flushed.
4078  */
4079 void
4080 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4081 {
4082         chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4083
4084         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4085         case HAMMER2_CHECK_NONE:
4086                 break;
4087         case HAMMER2_CHECK_DISABLED:
4088                 break;
4089         case HAMMER2_CHECK_ISCSI32:
4090                 chain->bref.check.iscsi32.value =
4091                         hammer2_icrc32(bdata, chain->bytes);
4092                 break;
4093         case HAMMER2_CHECK_CRC64:
4094                 chain->bref.check.crc64.value = 0;
4095                 /* XXX */
4096                 break;
4097         case HAMMER2_CHECK_SHA192:
4098                 {
4099                         SHA256_CTX hash_ctx;
4100                         union {
4101                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4102                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4103                         } u;
4104
4105                         SHA256_Init(&hash_ctx);
4106                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4107                         SHA256_Final(u.digest, &hash_ctx);
4108                         u.digest64[2] ^= u.digest64[3];
4109                         bcopy(u.digest,
4110                               chain->bref.check.sha192.data,
4111                               sizeof(chain->bref.check.sha192.data));
4112                 }
4113                 break;
4114         case HAMMER2_CHECK_FREEMAP:
4115                 chain->bref.check.freemap.icrc32 =
4116                         hammer2_icrc32(bdata, chain->bytes);
4117                 break;
4118         default:
4119                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4120                         chain->bref.methods);
4121                 break;
4122         }
4123 }
4124
4125 int
4126 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4127 {
4128         int r;
4129
4130         if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4131                 return 1;
4132
4133         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4134         case HAMMER2_CHECK_NONE:
4135                 r = 1;
4136                 break;
4137         case HAMMER2_CHECK_DISABLED:
4138                 r = 1;
4139                 break;
4140         case HAMMER2_CHECK_ISCSI32:
4141                 r = (chain->bref.check.iscsi32.value ==
4142                      hammer2_icrc32(bdata, chain->bytes));
4143                 break;
4144         case HAMMER2_CHECK_CRC64:
4145                 r = (chain->bref.check.crc64.value == 0);
4146                 /* XXX */
4147                 break;
4148         case HAMMER2_CHECK_SHA192:
4149                 {
4150                         SHA256_CTX hash_ctx;
4151                         union {
4152                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4153                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4154                         } u;
4155
4156                         SHA256_Init(&hash_ctx);
4157                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4158                         SHA256_Final(u.digest, &hash_ctx);
4159                         u.digest64[2] ^= u.digest64[3];
4160                         if (bcmp(u.digest,
4161                                  chain->bref.check.sha192.data,
4162                                  sizeof(chain->bref.check.sha192.data)) == 0) {
4163                                 r = 1;
4164                         } else {
4165                                 r = 0;
4166                         }
4167                 }
4168                 break;
4169         case HAMMER2_CHECK_FREEMAP:
4170                 r = (chain->bref.check.freemap.icrc32 ==
4171                      hammer2_icrc32(bdata, chain->bytes));
4172                 if (r == 0) {
4173                         kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4174                                 chain->bref.check.freemap.icrc32,
4175                                 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4176                         if (chain->dio)
4177                                 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4178                                         chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4179                 }
4180
4181                 break;
4182         default:
4183                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4184                         chain->bref.methods);
4185                 r = 1;
4186                 break;
4187         }
4188         return r;
4189 }
4190
4191 /*
4192  * The caller presents a shared-locked (parent, chain) where the chain
4193  * is of type HAMMER2_OBJTYPE_HARDLINK.  The caller must hold the ip
4194  * structure representing the inode locked to prevent
4195  * consolidation/deconsolidation races.
4196  *
4197  * We locate the hardlink in the current or a common parent directory.
4198  *
4199  * If we are unable to locate the hardlink, EIO is returned and
4200  * (*chainp) is unlocked and dropped.
4201  */
4202 int
4203 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4204                         hammer2_chain_t **parentp,
4205                         hammer2_chain_t **chainp,
4206                         int flags)
4207 {
4208         hammer2_chain_t *parent;
4209         hammer2_chain_t *rchain;
4210         hammer2_key_t key_dummy;
4211         hammer2_key_t lhc;
4212         int cache_index = -1;
4213
4214         /*
4215          * Obtain the key for the hardlink from *chainp.
4216          */
4217         rchain = *chainp;
4218         lhc = rchain->data->ipdata.meta.inum;
4219         hammer2_chain_unlock(rchain);
4220         hammer2_chain_drop(rchain);
4221         rchain = NULL;
4222
4223         for (;;) {
4224                 int nloops;
4225                 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4226                                               lhc, lhc,
4227                                               &cache_index, flags);
4228                 if (rchain)
4229                         break;
4230
4231                 /*
4232                  * Iterate parents, handle parent rename races by retrying
4233                  * the operation.
4234                  */
4235                 nloops = -1;
4236                 while (nloops) {
4237                         --nloops;
4238                         parent = *parentp;
4239                         if (nloops < 0 &&
4240                             parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4241                                 nloops = 1;
4242                         }
4243                         if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4244                                 goto done;
4245                         if (parent->parent == NULL)
4246                                 goto done;
4247                         parent = parent->parent;
4248                         hammer2_chain_ref(parent);
4249                         hammer2_chain_unlock(*parentp);
4250                         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4251                                                    flags);
4252                         if ((*parentp)->parent == parent) {
4253                                 hammer2_chain_drop(*parentp);
4254                                 *parentp = parent;
4255                         } else {
4256                                 hammer2_chain_unlock(parent);
4257                                 hammer2_chain_drop(parent);
4258                                 hammer2_chain_lock(*parentp,
4259                                                    HAMMER2_RESOLVE_ALWAYS |
4260                                                    flags);
4261                                 parent = NULL;  /* safety */
4262                                 /* retry */
4263                         }
4264                 }
4265         }
4266 done:
4267
4268         *chainp = rchain;
4269         return (rchain ? EINVAL : 0);
4270 }
4271
4272 /*
4273  * Used by the bulkscan code to snapshot the synchronized storage for
4274  * a volume, allowing it to be scanned concurrently against normal
4275  * operation.
4276  */
4277 hammer2_chain_t *
4278 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4279 {
4280         hammer2_chain_t *copy;
4281
4282         copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4283         switch(chain->bref.type) {
4284         case HAMMER2_BREF_TYPE_VOLUME:
4285                 copy->data = kmalloc(sizeof(copy->data->voldata),
4286                                      chain->hmp->mchain,
4287                                      M_WAITOK | M_ZERO);
4288                 hammer2_spin_ex(&chain->core.spin);
4289                 copy->data->voldata = chain->data->voldata;
4290                 hammer2_spin_unex(&chain->core.spin);
4291                 break;
4292         case HAMMER2_BREF_TYPE_FREEMAP:
4293                 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4294                                      chain->hmp->mchain,
4295                                      M_WAITOK | M_ZERO);
4296                 hammer2_spin_ex(&chain->core.spin);
4297                 copy->data->blkset = chain->data->blkset;
4298                 hammer2_spin_unex(&chain->core.spin);
4299                 break;
4300         default:
4301                 break;
4302         }
4303         return copy;
4304 }
4305
4306 void
4307 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4308 {
4309         switch(copy->bref.type) {
4310         case HAMMER2_BREF_TYPE_VOLUME:
4311         case HAMMER2_BREF_TYPE_FREEMAP:
4312                 KKASSERT(copy->data);
4313                 kfree(copy->data, copy->hmp->mchain);
4314                 copy->data = NULL;
4315         default:
4316                 break;
4317         }
4318         hammer2_chain_drop(copy);
4319 }
4320
4321 /*
4322  * Create a snapshot of the specified {parent, ochain} with the specified
4323  * label.  The originating hammer2_inode must be exclusively locked for
4324  * safety.
4325  *
4326  * The ioctl code has already synced the filesystem.
4327  */
4328 int
4329 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4330                        hammer2_tid_t mtid)
4331 {
4332         hammer2_dev_t *hmp;
4333         const hammer2_inode_data_t *ripdata;
4334         hammer2_inode_data_t *wipdata;
4335         hammer2_chain_t *nchain;
4336         hammer2_inode_t *nip;
4337         size_t name_len;
4338         hammer2_key_t lhc;
4339         struct vattr vat;
4340 #if 0
4341         uuid_t opfs_clid;
4342 #endif
4343         int error;
4344
4345         kprintf("snapshot %s\n", pmp->name);
4346
4347         name_len = strlen(pmp->name);
4348         lhc = hammer2_dirhash(pmp->name, name_len);
4349
4350         /*
4351          * Get the clid
4352          */
4353         ripdata = &chain->data->ipdata;
4354 #if 0
4355         opfs_clid = ripdata->meta.pfs_clid;
4356 #endif
4357         hmp = chain->hmp;
4358
4359         /*
4360          * Create the snapshot directory under the super-root
4361          *
4362          * Set PFS type, generate a unique filesystem id, and generate
4363          * a cluster id.  Use the same clid when snapshotting a PFS root,
4364          * which theoretically allows the snapshot to be used as part of
4365          * the same cluster (perhaps as a cache).
4366          *
4367          * Copy the (flushed) blockref array.  Theoretically we could use
4368          * chain_duplicate() but it becomes difficult to disentangle
4369          * the shared core so for now just brute-force it.
4370          */
4371         VATTR_NULL(&vat);
4372         vat.va_type = VDIR;
4373         vat.va_mode = 0755;
4374         nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4375                                    pmp->name, name_len, 0,
4376                                    1, 0, 0,
4377                                    HAMMER2_INSERT_PFSROOT, &error);
4378
4379         if (nip) {
4380                 hammer2_inode_modify(nip);
4381                 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4382                 hammer2_chain_modify(nchain, mtid, 0, 0);
4383                 wipdata = &nchain->data->ipdata;
4384
4385                 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4386                 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4387                 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4388                 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4389
4390                 /*
4391                  * Give the snapshot its own private cluster id.  As a
4392                  * snapshot no further synchronization with the original
4393                  * cluster will be done.
4394                  */
4395 #if 0
4396                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4397                         nip->meta.pfs_clid = opfs_clid;
4398                 else
4399                         kern_uuidgen(&nip->meta.pfs_clid, 1);
4400 #endif
4401                 kern_uuidgen(&nip->meta.pfs_clid, 1);
4402                 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4403
4404                 /* XXX hack blockset copy */
4405                 /* XXX doesn't work with real cluster */
4406                 wipdata->meta = nip->meta;
4407                 wipdata->u.blockset = ripdata->u.blockset;
4408                 hammer2_flush(nchain, 1);
4409                 hammer2_chain_unlock(nchain);
4410                 hammer2_chain_drop(nchain);
4411                 hammer2_inode_unlock(nip);
4412         }
4413         return (error);
4414 }