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