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