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