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