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