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