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