2 * Copyright (c) 2011-2018 The DragonFly Project. All rights reserved.
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>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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
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.
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
36 * This subsystem implements most of the core support functions for
37 * the hammer2_chain structure.
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
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
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.
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
60 #include <sys/kern_syscall.h>
63 #include <crypto/sha2/sha2.h>
67 static hammer2_chain_t *hammer2_chain_create_indirect(
68 hammer2_chain_t *parent,
69 hammer2_key_t key, int keybits,
70 hammer2_tid_t mtid, int for_type, int *errorp);
71 static void hammer2_chain_rename_obref(hammer2_chain_t **parentp,
72 hammer2_chain_t *chain, hammer2_tid_t mtid,
73 int flags, hammer2_blockref_t *obref);
74 static int hammer2_chain_delete_obref(hammer2_chain_t *parent,
75 hammer2_chain_t *chain,
76 hammer2_tid_t mtid, int flags,
77 hammer2_blockref_t *obref);
78 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain);
79 static hammer2_chain_t *hammer2_combined_find(
80 hammer2_chain_t *parent,
81 hammer2_blockref_t *base, int count,
82 hammer2_key_t *key_nextp,
83 hammer2_key_t key_beg, hammer2_key_t key_end,
84 hammer2_blockref_t **bresp);
86 static struct krate krate_h2me = { .freq = 1 };
89 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
90 * overlap in the RB trees. Deleted chains are moved from rbtree to either
93 * Chains in delete-duplicate sequences can always iterate through core_entry
94 * to locate the live version of the chain.
96 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
99 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
101 hammer2_key_t c1_beg;
102 hammer2_key_t c1_end;
103 hammer2_key_t c2_beg;
104 hammer2_key_t c2_end;
107 * Compare chains. Overlaps are not supposed to happen and catch
108 * any software issues early we count overlaps as a match.
110 c1_beg = chain1->bref.key;
111 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
112 c2_beg = chain2->bref.key;
113 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
115 if (c1_end < c2_beg) /* fully to the left */
117 if (c1_beg > c2_end) /* fully to the right */
119 return(0); /* overlap (must not cross edge boundary) */
123 * Assert that a chain has no media data associated with it.
126 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
128 KKASSERT(chain->dio == NULL);
129 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
130 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
132 panic("hammer2_chain_assert_no_data: chain %p still has data",
138 * Make a chain visible to the flusher. The flusher operates using a top-down
139 * recursion based on the ONFLUSH flag. It locates MODIFIED and UPDATE chains,
140 * flushes them, and updates blocks back to the volume root.
142 * This routine sets the ONFLUSH flag upward from the triggering chain until
143 * it hits an inode root or the volume root. Inode chains serve as inflection
144 * points, requiring the flusher to bridge across trees. Inodes include
145 * regular inodes, PFS roots (pmp->iroot), and the media super root
149 hammer2_chain_setflush(hammer2_chain_t *chain)
151 hammer2_chain_t *parent;
153 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
154 hammer2_spin_sh(&chain->core.spin);
155 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
156 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
157 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
159 if ((parent = chain->parent) == NULL)
161 hammer2_spin_sh(&parent->core.spin);
162 hammer2_spin_unsh(&chain->core.spin);
165 hammer2_spin_unsh(&chain->core.spin);
170 * Allocate a new disconnected chain element representing the specified
171 * bref. chain->refs is set to 1 and the passed bref is copied to
172 * chain->bref. chain->bytes is derived from the bref.
174 * chain->pmp inherits pmp unless the chain is an inode (other than the
177 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
180 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
181 hammer2_blockref_t *bref)
183 hammer2_chain_t *chain;
187 * Special case - radix of 0 indicates a chain that does not
188 * need a data reference (context is completely embedded in the
191 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
192 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
196 atomic_add_long(&hammer2_chain_allocs, 1);
199 * Construct the appropriate system structure.
202 case HAMMER2_BREF_TYPE_DIRENT:
203 case HAMMER2_BREF_TYPE_INODE:
204 case HAMMER2_BREF_TYPE_INDIRECT:
205 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
206 case HAMMER2_BREF_TYPE_DATA:
207 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
209 * Chain's are really only associated with the hmp but we
210 * maintain a pmp association for per-mount memory tracking
211 * purposes. The pmp can be NULL.
213 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
215 case HAMMER2_BREF_TYPE_VOLUME:
216 case HAMMER2_BREF_TYPE_FREEMAP:
218 * Only hammer2_chain_bulksnap() calls this function with these
221 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
225 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
230 * Initialize the new chain structure. pmp must be set to NULL for
231 * chains belonging to the super-root topology of a device mount.
233 if (pmp == hmp->spmp)
240 chain->bytes = bytes;
242 chain->flags = HAMMER2_CHAIN_ALLOCATED;
243 lockinit(&chain->diolk, "chdio", 0, 0);
246 * Set the PFS boundary flag if this chain represents a PFS root.
248 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
249 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
250 hammer2_chain_core_init(chain);
256 * Initialize a chain's core structure. This structure used to be allocated
257 * but is now embedded.
259 * The core is not locked. No additional refs on the chain are made.
260 * (trans) must not be NULL if (core) is not NULL.
263 hammer2_chain_core_init(hammer2_chain_t *chain)
266 * Fresh core under nchain (no multi-homing of ochain's
269 RB_INIT(&chain->core.rbtree); /* live chains */
270 hammer2_mtx_init(&chain->lock, "h2chain");
274 * Add a reference to a chain element, preventing its destruction.
276 * (can be called with spinlock held)
279 hammer2_chain_ref(hammer2_chain_t *chain)
281 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
283 * Just flag that the chain was used and should be recycled
284 * on the LRU if it encounters it later.
286 if (chain->flags & HAMMER2_CHAIN_ONLRU)
287 atomic_set_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
291 * REMOVED - reduces contention, lru_list is more heuristical
294 * 0->non-zero transition must ensure that chain is removed
297 * NOTE: Already holding lru_spin here so we cannot call
298 * hammer2_chain_ref() to get it off lru_list, do
301 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
302 hammer2_pfs_t *pmp = chain->pmp;
303 hammer2_spin_ex(&pmp->lru_spin);
304 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
305 atomic_add_int(&pmp->lru_count, -1);
306 atomic_clear_int(&chain->flags,
307 HAMMER2_CHAIN_ONLRU);
308 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
310 hammer2_spin_unex(&pmp->lru_spin);
317 * Ref a locked chain and force the data to be held across an unlock.
318 * Chain must be currently locked. The user of the chain who desires
319 * to release the hold must call hammer2_chain_lock_unhold() to relock
320 * and unhold the chain, then unlock normally, or may simply call
321 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
324 hammer2_chain_ref_hold(hammer2_chain_t *chain)
326 atomic_add_int(&chain->lockcnt, 1);
327 hammer2_chain_ref(chain);
331 * Insert the chain in the core rbtree.
333 * Normal insertions are placed in the live rbtree. Insertion of a deleted
334 * chain is a special case used by the flush code that is placed on the
335 * unstaged deleted list to avoid confusing the live view.
337 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
338 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
339 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
343 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
344 int flags, int generation)
346 hammer2_chain_t *xchain;
349 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
350 hammer2_spin_ex(&parent->core.spin);
353 * Interlocked by spinlock, check for race
355 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
356 parent->core.generation != generation) {
357 error = HAMMER2_ERROR_EAGAIN;
364 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
365 KASSERT(xchain == NULL,
366 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
367 chain, xchain, chain->bref.key));
368 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
369 chain->parent = parent;
370 ++parent->core.chain_count;
371 ++parent->core.generation; /* XXX incs for _get() too, XXX */
374 * We have to keep track of the effective live-view blockref count
375 * so the create code knows when to push an indirect block.
377 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
378 atomic_add_int(&parent->core.live_count, 1);
380 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
381 hammer2_spin_unex(&parent->core.spin);
386 * Drop the caller's reference to the chain. When the ref count drops to
387 * zero this function will try to disassociate the chain from its parent and
388 * deallocate it, then recursely drop the parent using the implied ref
389 * from the chain's chain->parent.
391 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
392 * races an acquisition by another cpu. Therefore we can loop if we are
393 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
394 * race against another drop.
396 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
398 static void hammer2_chain_lru_flush(hammer2_pfs_t *pmp);
401 hammer2_chain_drop(hammer2_chain_t *chain)
405 if (hammer2_debug & 0x200000)
408 KKASSERT(chain->refs > 0);
416 if (hammer2_mtx_ex_try(&chain->lock) == 0)
417 chain = hammer2_chain_lastdrop(chain, 0);
418 /* retry the same chain, or chain from lastdrop */
420 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
422 /* retry the same chain */
429 * Unhold a held and probably not-locked chain, ensure that the data is
430 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
431 * lock and then simply unlocking the chain.
434 hammer2_chain_unhold(hammer2_chain_t *chain)
440 lockcnt = chain->lockcnt;
443 if (atomic_cmpset_int(&chain->lockcnt,
444 lockcnt, lockcnt - 1)) {
447 } else if (hammer2_mtx_ex_try(&chain->lock) == 0) {
448 hammer2_chain_unlock(chain);
452 * This situation can easily occur on SMP due to
453 * the gap inbetween the 1->0 transition and the
454 * final unlock. We cannot safely block on the
455 * mutex because lockcnt might go above 1.
457 * XXX Sleep for one tick if it takes too long.
460 if (iter > 1000 + hz) {
461 kprintf("hammer2: h2race1 %p\n", chain);
464 tsleep(&iter, 0, "h2race1", 1);
472 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
474 hammer2_chain_unhold(chain);
475 hammer2_chain_drop(chain);
479 hammer2_chain_rehold(hammer2_chain_t *chain)
481 hammer2_chain_lock(chain, HAMMER2_RESOLVE_SHARED);
482 atomic_add_int(&chain->lockcnt, 1);
483 hammer2_chain_unlock(chain);
487 * Handles the (potential) last drop of chain->refs from 1->0. Called with
488 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
489 * possible against refs and lockcnt. We must dispose of the mutex on chain.
491 * This function returns an unlocked chain for recursive drop or NULL. It
492 * can return the same chain if it determines it has raced another ref.
496 * When two chains need to be recursively dropped we use the chain we
497 * would otherwise free to placehold the additional chain. It's a bit
498 * convoluted but we can't just recurse without potentially blowing out
501 * The chain cannot be freed if it has any children.
502 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
503 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
504 * Any dedup registration can remain intact.
506 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
510 hammer2_chain_lastdrop(hammer2_chain_t *chain, int depth)
514 hammer2_chain_t *parent;
515 hammer2_chain_t *rdrop;
518 * We need chain's spinlock to interlock the sub-tree test.
519 * We already have chain's mutex, protecting chain->parent.
521 * Remember that chain->refs can be in flux.
523 hammer2_spin_ex(&chain->core.spin);
525 if (chain->parent != NULL) {
527 * If the chain has a parent the UPDATE bit prevents scrapping
528 * as the chain is needed to properly flush the parent. Try
529 * to complete the 1->0 transition and return NULL. Retry
530 * (return chain) if we are unable to complete the 1->0
531 * transition, else return NULL (nothing more to do).
533 * If the chain has a parent the MODIFIED bit prevents
536 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
538 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
539 HAMMER2_CHAIN_MODIFIED)) {
540 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
541 hammer2_spin_unex(&chain->core.spin);
542 hammer2_chain_assert_no_data(chain);
543 hammer2_mtx_unlock(&chain->lock);
546 hammer2_spin_unex(&chain->core.spin);
547 hammer2_mtx_unlock(&chain->lock);
551 /* spinlock still held */
552 } else if (chain->bref.type == HAMMER2_BREF_TYPE_VOLUME ||
553 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP) {
555 * Retain the static vchain and fchain. Clear bits that
556 * are not relevant. Do not clear the MODIFIED bit,
557 * and certainly do not put it on the delayed-flush queue.
559 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
562 * The chain has no parent and can be flagged for destruction.
563 * Since it has no parent, UPDATE can also be cleared.
565 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
566 if (chain->flags & HAMMER2_CHAIN_UPDATE)
567 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
570 * If the chain has children we must propagate the DESTROY
571 * flag downward and rip the disconnected topology apart.
572 * This is accomplished by calling hammer2_flush() on the
575 * Any dedup is already handled by the underlying DIO, so
576 * we do not have to specifically flush it here.
578 if (chain->core.chain_count) {
579 hammer2_spin_unex(&chain->core.spin);
580 hammer2_flush(chain, HAMMER2_FLUSH_TOP |
582 hammer2_mtx_unlock(&chain->lock);
584 return(chain); /* retry drop */
588 * Otherwise we can scrap the MODIFIED bit if it is set,
589 * and continue along the freeing path.
591 * Be sure to clean-out any dedup bits. Without a parent
592 * this chain will no longer be visible to the flush code.
593 * Easy check data_off to avoid the volume root.
595 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
596 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
597 atomic_add_long(&hammer2_count_modified_chains, -1);
599 hammer2_pfs_memory_wakeup(chain->pmp);
601 /* spinlock still held */
604 /* spinlock still held */
607 * If any children exist we must leave the chain intact with refs == 0.
608 * They exist because chains are retained below us which have refs or
609 * may require flushing.
611 * Retry (return chain) if we fail to transition the refs to 0, else
612 * return NULL indication nothing more to do.
614 * Chains with children are NOT put on the LRU list.
616 if (chain->core.chain_count) {
617 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
618 hammer2_spin_unex(&chain->core.spin);
619 hammer2_chain_assert_no_data(chain);
620 hammer2_mtx_unlock(&chain->lock);
623 hammer2_spin_unex(&chain->core.spin);
624 hammer2_mtx_unlock(&chain->lock);
628 /* spinlock still held */
629 /* no chains left under us */
632 * chain->core has no children left so no accessors can get to our
633 * chain from there. Now we have to lock the parent core to interlock
634 * remaining possible accessors that might bump chain's refs before
635 * we can safely drop chain's refs with intent to free the chain.
638 pmp = chain->pmp; /* can be NULL */
641 parent = chain->parent;
644 * WARNING! chain's spin lock is still held here, and other spinlocks
645 * will be acquired and released in the code below. We
646 * cannot be making fancy procedure calls!
650 * We can cache the chain if it is associated with a pmp
651 * and not flagged as being destroyed or requesting a full
652 * release. In this situation the chain is not removed
653 * from its parent, i.e. it can still be looked up.
655 * We intentionally do not cache DATA chains because these
656 * were likely used to load data into the logical buffer cache
657 * and will not be accessed again for some time.
660 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
662 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
664 hammer2_spin_ex(&parent->core.spin);
665 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
667 * 1->0 transition failed, retry. Do not drop
668 * the chain's data yet!
671 hammer2_spin_unex(&parent->core.spin);
672 hammer2_spin_unex(&chain->core.spin);
673 hammer2_mtx_unlock(&chain->lock);
681 hammer2_chain_assert_no_data(chain);
684 * Make sure we are on the LRU list, clean up excessive
685 * LRU entries. We can only really drop one but there might
686 * be other entries that we can remove from the lru_list
689 * NOTE: HAMMER2_CHAIN_ONLRU may only be safely set when
690 * chain->core.spin AND pmp->lru_spin are held, but
691 * can be safely cleared only holding pmp->lru_spin.
693 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
694 hammer2_spin_ex(&pmp->lru_spin);
695 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
696 atomic_set_int(&chain->flags,
697 HAMMER2_CHAIN_ONLRU);
698 TAILQ_INSERT_TAIL(&pmp->lru_list,
700 atomic_add_int(&pmp->lru_count, 1);
702 if (pmp->lru_count < HAMMER2_LRU_LIMIT)
703 depth = 1; /* disable lru_list flush */
704 hammer2_spin_unex(&pmp->lru_spin);
706 /* disable lru flush */
711 hammer2_spin_unex(&parent->core.spin);
712 parent = NULL; /* safety */
714 hammer2_spin_unex(&chain->core.spin);
715 hammer2_mtx_unlock(&chain->lock);
718 * lru_list hysteresis (see above for depth overrides).
719 * Note that depth also prevents excessive lastdrop recursion.
722 hammer2_chain_lru_flush(pmp);
729 * Make sure we are not on the LRU list.
731 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
732 hammer2_spin_ex(&pmp->lru_spin);
733 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
734 atomic_add_int(&pmp->lru_count, -1);
735 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
736 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
738 hammer2_spin_unex(&pmp->lru_spin);
742 * Spinlock the parent and try to drop the last ref on chain.
743 * On success determine if we should dispose of the chain
744 * (remove the chain from its parent, etc).
746 * (normal core locks are top-down recursive but we define
747 * core spinlocks as bottom-up recursive, so this is safe).
750 hammer2_spin_ex(&parent->core.spin);
751 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
753 * 1->0 transition failed, retry.
755 hammer2_spin_unex(&parent->core.spin);
756 hammer2_spin_unex(&chain->core.spin);
757 hammer2_mtx_unlock(&chain->lock);
763 * 1->0 transition successful, parent spin held to prevent
764 * new lookups, chain spinlock held to protect parent field.
765 * Remove chain from the parent.
767 * If the chain is being removed from the parent's btree but
768 * is not bmapped, we have to adjust live_count downward. If
769 * it is bmapped then the blockref is retained in the parent
770 * as is its associated live_count. This case can occur when
771 * a chain added to the topology is unable to flush and is
772 * then later deleted.
774 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
775 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
776 (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
777 atomic_add_int(&parent->core.live_count, -1);
779 RB_REMOVE(hammer2_chain_tree,
780 &parent->core.rbtree, chain);
781 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
782 --parent->core.chain_count;
783 chain->parent = NULL;
787 * If our chain was the last chain in the parent's core the
788 * core is now empty and its parent might have to be
789 * re-dropped if it has 0 refs.
791 if (parent->core.chain_count == 0) {
793 atomic_add_int(&rdrop->refs, 1);
795 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
799 hammer2_spin_unex(&parent->core.spin);
800 parent = NULL; /* safety */
806 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
808 * 1->0 transition failed, retry.
810 hammer2_spin_unex(&parent->core.spin);
811 hammer2_spin_unex(&chain->core.spin);
812 hammer2_mtx_unlock(&chain->lock);
819 * Successful 1->0 transition, no parent, no children... no way for
820 * anyone to ref this chain any more. We can clean-up and free it.
822 * We still have the core spinlock, and core's chain_count is 0.
823 * Any parent spinlock is gone.
825 hammer2_spin_unex(&chain->core.spin);
826 hammer2_chain_assert_no_data(chain);
827 hammer2_mtx_unlock(&chain->lock);
828 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
829 chain->core.chain_count == 0);
832 * All locks are gone, no pointers remain to the chain, finish
835 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
836 HAMMER2_CHAIN_MODIFIED)) == 0);
839 * Once chain resources are gone we can use the now dead chain
840 * structure to placehold what might otherwise require a recursive
841 * drop, because we have potentially two things to drop and can only
842 * return one directly.
844 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
845 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
847 kfree(chain, hmp->mchain);
851 * Possible chaining loop when parent re-drop needed.
857 * Heuristical flush of the LRU, try to reduce the number of entries
858 * on the LRU to (HAMMER2_LRU_LIMIT * 2 / 3). This procedure is called
859 * only when lru_count exceeds HAMMER2_LRU_LIMIT.
863 hammer2_chain_lru_flush(hammer2_pfs_t *pmp)
865 hammer2_chain_t *chain;
869 hammer2_spin_ex(&pmp->lru_spin);
870 while (pmp->lru_count > HAMMER2_LRU_LIMIT * 2 / 3) {
872 * Pick a chain off the lru_list, just recycle it quickly
873 * if LRUHINT is set (the chain was ref'd but left on
874 * the lru_list, so cycle to the end).
876 chain = TAILQ_FIRST(&pmp->lru_list);
877 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
879 if (chain->flags & HAMMER2_CHAIN_LRUHINT) {
880 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
881 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
887 * Ok, we are off the LRU. We must adjust refs before we
888 * can safely clear the ONLRU flag.
890 atomic_add_int(&pmp->lru_count, -1);
891 if (atomic_cmpset_int(&chain->refs, 0, 1)) {
892 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
893 atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
896 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
899 hammer2_spin_unex(&pmp->lru_spin);
904 * If we picked a chain off the lru list we may be able to lastdrop
905 * it. Use a depth of 1 to prevent excessive lastdrop recursion.
915 if (hammer2_mtx_ex_try(&chain->lock) == 0)
916 chain = hammer2_chain_lastdrop(chain, 1);
917 /* retry the same chain, or chain from lastdrop */
919 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
921 /* retry the same chain */
929 * On last lock release.
931 static hammer2_io_t *
932 hammer2_chain_drop_data(hammer2_chain_t *chain)
936 if ((dio = chain->dio) != NULL) {
940 switch(chain->bref.type) {
941 case HAMMER2_BREF_TYPE_VOLUME:
942 case HAMMER2_BREF_TYPE_FREEMAP:
945 if (chain->data != NULL) {
946 hammer2_spin_unex(&chain->core.spin);
947 panic("chain data not null: "
948 "chain %p bref %016jx.%02x "
949 "refs %d parent %p dio %p data %p",
950 chain, chain->bref.data_off,
951 chain->bref.type, chain->refs,
953 chain->dio, chain->data);
955 KKASSERT(chain->data == NULL);
963 * Lock a referenced chain element, acquiring its data with I/O if necessary,
964 * and specify how you would like the data to be resolved.
966 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
968 * The lock is allowed to recurse, multiple locking ops will aggregate
969 * the requested resolve types. Once data is assigned it will not be
970 * removed until the last unlock.
972 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
973 * (typically used to avoid device/logical buffer
976 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
977 * the INITIAL-create state (indirect blocks only).
979 * Do not resolve data elements for DATA chains.
980 * (typically used to avoid device/logical buffer
983 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
985 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
986 * it will be locked exclusive.
988 * HAMMER2_RESOLVE_NONBLOCK- (flag) The chain is locked non-blocking. If
989 * the lock fails, EAGAIN is returned.
991 * NOTE: Embedded elements (volume header, inodes) are always resolved
994 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
995 * element will instantiate and zero its buffer, and flush it on
998 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
999 * so as not to instantiate a device buffer, which could alias against
1000 * a logical file buffer. However, if ALWAYS is specified the
1001 * device buffer will be instantiated anyway.
1003 * NOTE: The return value is always 0 unless NONBLOCK is specified, in which
1004 * case it can be either 0 or EAGAIN.
1006 * WARNING! This function blocks on I/O if data needs to be fetched. This
1007 * blocking can run concurrent with other compatible lock holders
1008 * who do not need data returning. The lock is not upgraded to
1009 * exclusive during a data fetch, a separate bit is used to
1010 * interlock I/O. However, an exclusive lock holder can still count
1011 * on being interlocked against an I/O fetch managed by a shared
1015 hammer2_chain_lock(hammer2_chain_t *chain, int how)
1017 KKASSERT(chain->refs > 0);
1019 if (how & HAMMER2_RESOLVE_NONBLOCK) {
1021 * We still have to bump lockcnt before acquiring the lock,
1022 * even for non-blocking operation, because the unlock code
1023 * live-loops on lockcnt == 1 when dropping the last lock.
1025 * If the non-blocking operation fails we have to use an
1026 * unhold sequence to undo the mess.
1028 * NOTE: LOCKAGAIN must always succeed without blocking,
1029 * even if NONBLOCK is specified.
1031 atomic_add_int(&chain->lockcnt, 1);
1032 if (how & HAMMER2_RESOLVE_SHARED) {
1033 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1034 hammer2_mtx_sh_again(&chain->lock);
1036 if (hammer2_mtx_sh_try(&chain->lock) != 0) {
1037 hammer2_chain_unhold(chain);
1042 if (hammer2_mtx_ex_try(&chain->lock) != 0) {
1043 hammer2_chain_unhold(chain);
1047 ++curthread->td_tracker;
1050 * Get the appropriate lock. If LOCKAGAIN is flagged with
1051 * SHARED the caller expects a shared lock to already be
1052 * present and we are giving it another ref. This case must
1053 * importantly not block if there is a pending exclusive lock
1056 atomic_add_int(&chain->lockcnt, 1);
1057 if (how & HAMMER2_RESOLVE_SHARED) {
1058 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1059 hammer2_mtx_sh_again(&chain->lock);
1061 hammer2_mtx_sh(&chain->lock);
1064 hammer2_mtx_ex(&chain->lock);
1066 ++curthread->td_tracker;
1070 * If we already have a valid data pointer make sure the data is
1071 * synchronized to the current cpu, and then no further action is
1076 hammer2_io_bkvasync(chain->dio);
1081 * Do we have to resolve the data? This is generally only
1082 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
1083 * Other BREF types expects the data to be there.
1085 switch(how & HAMMER2_RESOLVE_MASK) {
1086 case HAMMER2_RESOLVE_NEVER:
1088 case HAMMER2_RESOLVE_MAYBE:
1089 if (chain->flags & HAMMER2_CHAIN_INITIAL)
1091 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1094 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
1096 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
1100 case HAMMER2_RESOLVE_ALWAYS:
1106 * Caller requires data
1108 hammer2_chain_load_data(chain);
1114 * Lock the chain, retain the hold, and drop the data persistence count.
1115 * The data should remain valid because we never transitioned lockcnt
1119 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
1121 hammer2_chain_lock(chain, how);
1122 atomic_add_int(&chain->lockcnt, -1);
1127 * Downgrade an exclusive chain lock to a shared chain lock.
1129 * NOTE: There is no upgrade equivalent due to the ease of
1130 * deadlocks in that direction.
1133 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1135 hammer2_mtx_downgrade(&chain->lock);
1140 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1141 * may be of any type.
1143 * Once chain->data is set it cannot be disposed of until all locks are
1146 * Make sure the data is synchronized to the current cpu.
1149 hammer2_chain_load_data(hammer2_chain_t *chain)
1151 hammer2_blockref_t *bref;
1158 * Degenerate case, data already present, or chain has no media
1159 * reference to load.
1161 KKASSERT(chain->lock.mtx_lock & MTX_MASK);
1164 hammer2_io_bkvasync(chain->dio);
1167 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1171 KKASSERT(hmp != NULL);
1174 * Gain the IOINPROG bit, interlocked block.
1180 oflags = chain->flags;
1182 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1183 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1184 tsleep_interlock(&chain->flags, 0);
1185 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1186 tsleep(&chain->flags, PINTERLOCKED,
1191 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1192 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1200 * We own CHAIN_IOINPROG
1202 * Degenerate case if we raced another load.
1206 hammer2_io_bkvasync(chain->dio);
1211 * We must resolve to a device buffer, either by issuing I/O or
1212 * by creating a zero-fill element. We do not mark the buffer
1213 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1214 * API must still be used to do that).
1216 * The device buffer is variable-sized in powers of 2 down
1217 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1218 * chunk always contains buffers of the same size. (XXX)
1220 * The minimum physical IO size may be larger than the variable
1223 bref = &chain->bref;
1226 * The getblk() optimization can only be used on newly created
1227 * elements if the physical block size matches the request.
1229 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1230 error = hammer2_io_new(hmp, bref->type,
1231 bref->data_off, chain->bytes,
1234 error = hammer2_io_bread(hmp, bref->type,
1235 bref->data_off, chain->bytes,
1237 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1240 chain->error = HAMMER2_ERROR_EIO;
1241 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1242 (intmax_t)bref->data_off, error);
1243 hammer2_io_bqrelse(&chain->dio);
1249 * This isn't perfect and can be ignored on OSs which do not have
1250 * an indication as to whether a buffer is coming from cache or
1251 * if I/O was actually issued for the read. TESTEDGOOD will work
1252 * pretty well without the B_IOISSUED logic because chains are
1253 * cached, but in that situation (without B_IOISSUED) it will not
1254 * detect whether a re-read via I/O is corrupted verses the original
1257 * We can't re-run the CRC on every fresh lock. That would be
1258 * insanely expensive.
1260 * If the underlying kernel buffer covers the entire chain we can
1261 * use the B_IOISSUED indication to determine if we have to re-run
1262 * the CRC on chain data for chains that managed to stay cached
1263 * across the kernel disposal of the original buffer.
1265 if ((dio = chain->dio) != NULL && dio->bp) {
1266 struct buf *bp = dio->bp;
1268 if (dio->psize == chain->bytes &&
1269 (bp->b_flags & B_IOISSUED)) {
1270 atomic_clear_int(&chain->flags,
1271 HAMMER2_CHAIN_TESTEDGOOD);
1272 bp->b_flags &= ~B_IOISSUED;
1277 * NOTE: A locked chain's data cannot be modified without first
1278 * calling hammer2_chain_modify().
1282 * Clear INITIAL. In this case we used io_new() and the buffer has
1283 * been zero'd and marked dirty.
1285 * NOTE: hammer2_io_data() call issues bkvasync()
1287 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1289 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1290 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1291 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1292 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1294 * check data not currently synchronized due to
1295 * modification. XXX assumes data stays in the buffer
1296 * cache, which might not be true (need biodep on flush
1297 * to calculate crc? or simple crc?).
1299 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1300 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1301 chain->error = HAMMER2_ERROR_CHECK;
1303 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1308 * Setup the data pointer, either pointing it to an embedded data
1309 * structure and copying the data from the buffer, or pointing it
1312 * The buffer is not retained when copying to an embedded data
1313 * structure in order to avoid potential deadlocks or recursions
1314 * on the same physical buffer.
1316 * WARNING! Other threads can start using the data the instant we
1317 * set chain->data non-NULL.
1319 switch (bref->type) {
1320 case HAMMER2_BREF_TYPE_VOLUME:
1321 case HAMMER2_BREF_TYPE_FREEMAP:
1323 * Copy data from bp to embedded buffer
1325 panic("hammer2_chain_load_data: unresolved volume header");
1327 case HAMMER2_BREF_TYPE_DIRENT:
1328 KKASSERT(chain->bytes != 0);
1330 case HAMMER2_BREF_TYPE_INODE:
1331 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1332 case HAMMER2_BREF_TYPE_INDIRECT:
1333 case HAMMER2_BREF_TYPE_DATA:
1334 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1337 * Point data at the device buffer and leave dio intact.
1339 chain->data = (void *)bdata;
1344 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1351 oflags = chain->flags;
1352 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1353 HAMMER2_CHAIN_IOSIGNAL);
1354 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1355 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1356 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1357 wakeup(&chain->flags);
1364 * Unlock and deref a chain element.
1366 * Remember that the presence of children under chain prevent the chain's
1367 * destruction but do not add additional references, so the dio will still
1371 hammer2_chain_unlock(hammer2_chain_t *chain)
1377 --curthread->td_tracker;
1380 * If multiple locks are present (or being attempted) on this
1381 * particular chain we can just unlock, drop refs, and return.
1383 * Otherwise fall-through on the 1->0 transition.
1386 lockcnt = chain->lockcnt;
1387 KKASSERT(lockcnt > 0);
1390 if (atomic_cmpset_int(&chain->lockcnt,
1391 lockcnt, lockcnt - 1)) {
1392 hammer2_mtx_unlock(&chain->lock);
1395 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1396 /* while holding the mutex exclusively */
1397 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1401 * This situation can easily occur on SMP due to
1402 * the gap inbetween the 1->0 transition and the
1403 * final unlock. We cannot safely block on the
1404 * mutex because lockcnt might go above 1.
1406 * XXX Sleep for one tick if it takes too long.
1408 if (++iter > 1000) {
1409 if (iter > 1000 + hz) {
1410 kprintf("hammer2: h2race2 %p\n", chain);
1413 tsleep(&iter, 0, "h2race2", 1);
1421 * Last unlock / mutex upgraded to exclusive. Drop the data
1424 dio = hammer2_chain_drop_data(chain);
1426 hammer2_io_bqrelse(&dio);
1427 hammer2_mtx_unlock(&chain->lock);
1431 * Unlock and hold chain data intact
1434 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1436 atomic_add_int(&chain->lockcnt, 1);
1437 hammer2_chain_unlock(chain);
1441 * Helper to obtain the blockref[] array base and count for a chain.
1443 * XXX Not widely used yet, various use cases need to be validated and
1444 * converted to use this function.
1447 hammer2_blockref_t *
1448 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1450 hammer2_blockref_t *base;
1453 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1456 switch(parent->bref.type) {
1457 case HAMMER2_BREF_TYPE_INODE:
1458 count = HAMMER2_SET_COUNT;
1460 case HAMMER2_BREF_TYPE_INDIRECT:
1461 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1462 count = parent->bytes / sizeof(hammer2_blockref_t);
1464 case HAMMER2_BREF_TYPE_VOLUME:
1465 count = HAMMER2_SET_COUNT;
1467 case HAMMER2_BREF_TYPE_FREEMAP:
1468 count = HAMMER2_SET_COUNT;
1471 panic("hammer2_chain_base_and_count: "
1472 "unrecognized blockref type: %d",
1478 switch(parent->bref.type) {
1479 case HAMMER2_BREF_TYPE_INODE:
1480 base = &parent->data->ipdata.u.blockset.blockref[0];
1481 count = HAMMER2_SET_COUNT;
1483 case HAMMER2_BREF_TYPE_INDIRECT:
1484 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1485 base = &parent->data->npdata[0];
1486 count = parent->bytes / sizeof(hammer2_blockref_t);
1488 case HAMMER2_BREF_TYPE_VOLUME:
1489 base = &parent->data->voldata.
1490 sroot_blockset.blockref[0];
1491 count = HAMMER2_SET_COUNT;
1493 case HAMMER2_BREF_TYPE_FREEMAP:
1494 base = &parent->data->blkset.blockref[0];
1495 count = HAMMER2_SET_COUNT;
1498 panic("hammer2_chain_base_and_count: "
1499 "unrecognized blockref type: %d",
1511 * This counts the number of live blockrefs in a block array and
1512 * also calculates the point at which all remaining blockrefs are empty.
1513 * This routine can only be called on a live chain.
1515 * Caller holds the chain locked, but possibly with a shared lock. We
1516 * must use an exclusive spinlock to prevent corruption.
1518 * NOTE: Flag is not set until after the count is complete, allowing
1519 * callers to test the flag without holding the spinlock.
1521 * NOTE: If base is NULL the related chain is still in the INITIAL
1522 * state and there are no blockrefs to count.
1524 * NOTE: live_count may already have some counts accumulated due to
1525 * creation and deletion and could even be initially negative.
1528 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1529 hammer2_blockref_t *base, int count)
1531 hammer2_spin_ex(&chain->core.spin);
1532 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1534 while (--count >= 0) {
1535 if (base[count].type)
1538 chain->core.live_zero = count + 1;
1539 while (count >= 0) {
1540 if (base[count].type)
1541 atomic_add_int(&chain->core.live_count,
1546 chain->core.live_zero = 0;
1548 /* else do not modify live_count */
1549 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1551 hammer2_spin_unex(&chain->core.spin);
1555 * Resize the chain's physical storage allocation in-place. This function does
1556 * not usually adjust the data pointer and must be followed by (typically) a
1557 * hammer2_chain_modify() call to copy any old data over and adjust the
1560 * Chains can be resized smaller without reallocating the storage. Resizing
1561 * larger will reallocate the storage. Excess or prior storage is reclaimed
1562 * asynchronously at a later time.
1564 * An nradix value of 0 is special-cased to mean that the storage should
1565 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1568 * Must be passed an exclusively locked parent and chain.
1570 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1571 * to avoid instantiating a device buffer that conflicts with the vnode data
1572 * buffer. However, because H2 can compress or encrypt data, the chain may
1573 * have a dio assigned to it in those situations, and they do not conflict.
1575 * XXX return error if cannot resize.
1578 hammer2_chain_resize(hammer2_chain_t *chain,
1579 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1580 int nradix, int flags)
1590 * Only data and indirect blocks can be resized for now.
1591 * (The volu root, inodes, and freemap elements use a fixed size).
1593 KKASSERT(chain != &hmp->vchain);
1594 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1595 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1596 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1599 * Nothing to do if the element is already the proper size
1601 obytes = chain->bytes;
1602 nbytes = (nradix) ? (1U << nradix) : 0;
1603 if (obytes == nbytes)
1604 return (chain->error);
1607 * Make sure the old data is instantiated so we can copy it. If this
1608 * is a data block, the device data may be superfluous since the data
1609 * might be in a logical block, but compressed or encrypted data is
1612 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1614 error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1619 * Relocate the block, even if making it smaller (because different
1620 * block sizes may be in different regions).
1622 * NOTE: Operation does not copy the data and may only be used
1623 * to resize data blocks in-place, or directory entry blocks
1624 * which are about to be modified in some manner.
1626 error = hammer2_freemap_alloc(chain, nbytes);
1630 chain->bytes = nbytes;
1633 * We don't want the followup chain_modify() to try to copy data
1634 * from the old (wrong-sized) buffer. It won't know how much to
1635 * copy. This case should only occur during writes when the
1636 * originator already has the data to write in-hand.
1639 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1640 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1641 hammer2_io_brelse(&chain->dio);
1644 return (chain->error);
1648 * Set the chain modified so its data can be changed by the caller, or
1649 * install deduplicated data. The caller must call this routine for each
1650 * set of modifications it makes, even if the chain is already flagged
1653 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1654 * is a CLC (cluster level change) field and is not updated by parent
1655 * propagation during a flush.
1657 * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1658 * chain->error except for HAMMER2_ERROR_ENOSPC. If the allocation fails
1659 * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1660 * remains unmodified with its old data ref intact and chain->error
1665 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1666 * even if the chain is still flagged MODIFIED. In this case the chain's
1667 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1669 * If the caller passes a non-zero dedup_off we will use it to assign the
1670 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1671 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1672 * must not modify the data content upon return.
1675 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1676 hammer2_off_t dedup_off, int flags)
1678 hammer2_blockref_t obref;
1689 obref = chain->bref;
1690 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1691 KKASSERT(chain->lock.mtx_lock & MTX_EXCLUSIVE);
1694 * Data is not optional for freemap chains (we must always be sure
1695 * to copy the data on COW storage allocations).
1697 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1698 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1699 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1700 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1704 * Data must be resolved if already assigned, unless explicitly
1705 * flagged otherwise. If we cannot safety load the data the
1706 * modification fails and we return early.
1708 if (chain->data == NULL && chain->bytes != 0 &&
1709 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1710 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1711 hammer2_chain_load_data(chain);
1713 return (chain->error);
1718 * Set MODIFIED to indicate that the chain has been modified. A new
1719 * allocation is required when modifying a chain.
1721 * Set UPDATE to ensure that the blockref is updated in the parent.
1723 * If MODIFIED is already set determine if we can reuse the assigned
1724 * data block or if we need a new data block.
1726 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1728 * Must set modified bit.
1730 atomic_add_long(&hammer2_count_modified_chains, 1);
1731 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1732 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1736 * We may be able to avoid a copy-on-write if the chain's
1737 * check mode is set to NONE and the chain's current
1738 * modify_tid is beyond the last explicit snapshot tid.
1740 * This implements HAMMER2's overwrite-in-place feature.
1742 * NOTE! This data-block cannot be used as a de-duplication
1743 * source when the check mode is set to NONE.
1745 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1746 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1747 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1748 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1749 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1750 HAMMER2_CHECK_NONE &&
1752 chain->bref.modify_tid >
1753 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1755 * Sector overwrite allowed.
1760 * Sector overwrite not allowed, must copy-on-write.
1764 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1766 * If the modified chain was registered for dedup we need
1767 * a new allocation. This only happens for delayed-flush
1768 * chains (i.e. which run through the front-end buffer
1775 * Already flagged modified, no new allocation is needed.
1782 * Flag parent update required.
1784 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1785 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1792 * The XOP code returns held but unlocked focus chains. This
1793 * prevents the chain from being destroyed but does not prevent
1794 * it from being modified. diolk is used to interlock modifications
1795 * against XOP frontend accesses to the focus.
1797 * This allows us to theoretically avoid deadlocking the frontend
1798 * if one of the backends lock up by not formally locking the
1799 * focused chain in the frontend. In addition, the synchronization
1800 * code relies on this mechanism to avoid deadlocking concurrent
1801 * synchronization threads.
1803 lockmgr(&chain->diolk, LK_EXCLUSIVE);
1806 * The modification or re-modification requires an allocation and
1807 * possible COW. If an error occurs, the previous content and data
1808 * reference is retained and the modification fails.
1810 * If dedup_off is non-zero, the caller is requesting a deduplication
1811 * rather than a modification. The MODIFIED bit is not set and the
1812 * data offset is set to the deduplication offset. The data cannot
1815 * NOTE: The dedup offset is allowed to be in a partially free state
1816 * and we must be sure to reset it to a fully allocated state
1817 * to force two bulkfree passes to free it again.
1819 * NOTE: Only applicable when chain->bytes != 0.
1821 * XXX can a chain already be marked MODIFIED without a data
1822 * assignment? If not, assert here instead of testing the case.
1824 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1826 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1830 * NOTE: We do not have to remove the dedup
1831 * registration because the area is still
1832 * allocated and the underlying DIO will
1836 chain->bref.data_off = dedup_off;
1837 chain->bytes = 1 << (dedup_off &
1838 HAMMER2_OFF_MASK_RADIX);
1840 atomic_clear_int(&chain->flags,
1841 HAMMER2_CHAIN_MODIFIED);
1842 atomic_add_long(&hammer2_count_modified_chains,
1845 hammer2_pfs_memory_wakeup(chain->pmp);
1846 hammer2_freemap_adjust(hmp, &chain->bref,
1847 HAMMER2_FREEMAP_DORECOVER);
1848 atomic_set_int(&chain->flags,
1849 HAMMER2_CHAIN_DEDUPABLE);
1851 error = hammer2_freemap_alloc(chain,
1853 atomic_clear_int(&chain->flags,
1854 HAMMER2_CHAIN_DEDUPABLE);
1860 * Stop here if error. We have to undo any flag bits we might
1865 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1866 atomic_add_long(&hammer2_count_modified_chains, -1);
1868 hammer2_pfs_memory_wakeup(chain->pmp);
1871 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1873 lockmgr(&chain->diolk, LK_RELEASE);
1879 * Update mirror_tid and modify_tid. modify_tid is only updated
1880 * if not passed as zero (during flushes, parent propagation passes
1883 * NOTE: chain->pmp could be the device spmp.
1885 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1887 chain->bref.modify_tid = mtid;
1890 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1891 * requires updating as well as to tell the delete code that the
1892 * chain's blockref might not exactly match (in terms of physical size
1893 * or block offset) the one in the parent's blocktable. The base key
1894 * of course will still match.
1896 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1897 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1900 * Short-cut data blocks which the caller does not need an actual
1901 * data reference to (aka OPTDATA), as long as the chain does not
1902 * already have a data pointer to the data. This generally means
1903 * that the modifications are being done via the logical buffer cache.
1904 * The INITIAL flag relates only to the device data buffer and thus
1905 * remains unchange in this situation.
1907 * This code also handles bytes == 0 (most dirents).
1909 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1910 (flags & HAMMER2_MODIFY_OPTDATA) &&
1911 chain->data == NULL) {
1912 KKASSERT(chain->dio == NULL);
1917 * Clearing the INITIAL flag (for indirect blocks) indicates that
1918 * we've processed the uninitialized storage allocation.
1920 * If this flag is already clear we are likely in a copy-on-write
1921 * situation but we have to be sure NOT to bzero the storage if
1922 * no data is present.
1924 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1925 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1932 * Instantiate data buffer and possibly execute COW operation
1934 switch(chain->bref.type) {
1935 case HAMMER2_BREF_TYPE_VOLUME:
1936 case HAMMER2_BREF_TYPE_FREEMAP:
1938 * The data is embedded, no copy-on-write operation is
1941 KKASSERT(chain->dio == NULL);
1943 case HAMMER2_BREF_TYPE_DIRENT:
1945 * The data might be fully embedded.
1947 if (chain->bytes == 0) {
1948 KKASSERT(chain->dio == NULL);
1952 case HAMMER2_BREF_TYPE_INODE:
1953 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1954 case HAMMER2_BREF_TYPE_DATA:
1955 case HAMMER2_BREF_TYPE_INDIRECT:
1956 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1958 * Perform the copy-on-write operation
1960 * zero-fill or copy-on-write depending on whether
1961 * chain->data exists or not and set the dirty state for
1962 * the new buffer. hammer2_io_new() will handle the
1965 * If a dedup_off was supplied this is an existing block
1966 * and no COW, copy, or further modification is required.
1968 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1970 if (wasinitial && dedup_off == 0) {
1971 error = hammer2_io_new(hmp, chain->bref.type,
1972 chain->bref.data_off,
1973 chain->bytes, &dio);
1975 error = hammer2_io_bread(hmp, chain->bref.type,
1976 chain->bref.data_off,
1977 chain->bytes, &dio);
1979 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1982 * If an I/O error occurs make sure callers cannot accidently
1983 * modify the old buffer's contents and corrupt the filesystem.
1985 * NOTE: hammer2_io_data() call issues bkvasync()
1988 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1990 chain->error = HAMMER2_ERROR_EIO;
1991 hammer2_io_brelse(&dio);
1992 hammer2_io_brelse(&chain->dio);
1997 bdata = hammer2_io_data(dio, chain->bref.data_off);
2001 * COW (unless a dedup).
2003 KKASSERT(chain->dio != NULL);
2004 if (chain->data != (void *)bdata && dedup_off == 0) {
2005 bcopy(chain->data, bdata, chain->bytes);
2007 } else if (wasinitial == 0) {
2009 * We have a problem. We were asked to COW but
2010 * we don't have any data to COW with!
2012 panic("hammer2_chain_modify: having a COW %p\n",
2017 * Retire the old buffer, replace with the new. Dirty or
2018 * redirty the new buffer.
2020 * WARNING! The system buffer cache may have already flushed
2021 * the buffer, so we must be sure to [re]dirty it
2022 * for further modification.
2024 * If dedup_off was supplied, the caller is not
2025 * expected to make any further modification to the
2028 * WARNING! hammer2_get_gdata() assumes dio never transitions
2029 * through NULL in order to optimize away unnecessary
2035 if ((tio = chain->dio) != NULL)
2036 hammer2_io_bqrelse(&tio);
2037 chain->data = (void *)bdata;
2040 hammer2_io_setdirty(dio);
2044 panic("hammer2_chain_modify: illegal non-embedded type %d",
2051 * setflush on parent indicating that the parent must recurse down
2052 * to us. Do not call on chain itself which might already have it
2056 hammer2_chain_setflush(chain->parent);
2057 lockmgr(&chain->diolk, LK_RELEASE);
2059 return (chain->error);
2063 * Modify the chain associated with an inode.
2066 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
2067 hammer2_tid_t mtid, int flags)
2071 hammer2_inode_modify(ip);
2072 error = hammer2_chain_modify(chain, mtid, 0, flags);
2078 * Volume header data locks
2081 hammer2_voldata_lock(hammer2_dev_t *hmp)
2083 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
2087 hammer2_voldata_unlock(hammer2_dev_t *hmp)
2089 lockmgr(&hmp->vollk, LK_RELEASE);
2093 hammer2_voldata_modify(hammer2_dev_t *hmp)
2095 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
2096 atomic_add_long(&hammer2_count_modified_chains, 1);
2097 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
2098 hammer2_pfs_memory_inc(hmp->vchain.pmp);
2103 * This function returns the chain at the nearest key within the specified
2104 * range. The returned chain will be referenced but not locked.
2106 * This function will recurse through chain->rbtree as necessary and will
2107 * return a *key_nextp suitable for iteration. *key_nextp is only set if
2108 * the iteration value is less than the current value of *key_nextp.
2110 * The caller should use (*key_nextp) to calculate the actual range of
2111 * the returned element, which will be (key_beg to *key_nextp - 1), because
2112 * there might be another element which is superior to the returned element
2115 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
2116 * chains continue to be returned. On EOF (*key_nextp) may overflow since
2117 * it will wind up being (key_end + 1).
2119 * WARNING! Must be called with child's spinlock held. Spinlock remains
2120 * held through the operation.
2122 struct hammer2_chain_find_info {
2123 hammer2_chain_t *best;
2124 hammer2_key_t key_beg;
2125 hammer2_key_t key_end;
2126 hammer2_key_t key_next;
2129 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
2130 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
2134 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
2135 hammer2_key_t key_beg, hammer2_key_t key_end)
2137 struct hammer2_chain_find_info info;
2140 info.key_beg = key_beg;
2141 info.key_end = key_end;
2142 info.key_next = *key_nextp;
2144 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
2145 hammer2_chain_find_cmp, hammer2_chain_find_callback,
2147 *key_nextp = info.key_next;
2149 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
2150 parent, key_beg, key_end, *key_nextp);
2158 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
2160 struct hammer2_chain_find_info *info = data;
2161 hammer2_key_t child_beg;
2162 hammer2_key_t child_end;
2164 child_beg = child->bref.key;
2165 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2167 if (child_end < info->key_beg)
2169 if (child_beg > info->key_end)
2176 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2178 struct hammer2_chain_find_info *info = data;
2179 hammer2_chain_t *best;
2180 hammer2_key_t child_end;
2183 * WARNING! Layerq is scanned forwards, exact matches should keep
2184 * the existing info->best.
2186 if ((best = info->best) == NULL) {
2188 * No previous best. Assign best
2191 } else if (best->bref.key <= info->key_beg &&
2192 child->bref.key <= info->key_beg) {
2197 /*info->best = child;*/
2198 } else if (child->bref.key < best->bref.key) {
2200 * Child has a nearer key and best is not flush with key_beg.
2201 * Set best to child. Truncate key_next to the old best key.
2204 if (info->key_next > best->bref.key || info->key_next == 0)
2205 info->key_next = best->bref.key;
2206 } else if (child->bref.key == best->bref.key) {
2208 * If our current best is flush with the child then this
2209 * is an illegal overlap.
2211 * key_next will automatically be limited to the smaller of
2212 * the two end-points.
2218 * Keep the current best but truncate key_next to the child's
2221 * key_next will also automatically be limited to the smaller
2222 * of the two end-points (probably not necessary for this case
2223 * but we do it anyway).
2225 if (info->key_next > child->bref.key || info->key_next == 0)
2226 info->key_next = child->bref.key;
2230 * Always truncate key_next based on child's end-of-range.
2232 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2233 if (child_end && (info->key_next > child_end || info->key_next == 0))
2234 info->key_next = child_end;
2240 * Retrieve the specified chain from a media blockref, creating the
2241 * in-memory chain structure which reflects it. The returned chain is
2242 * held and locked according to (how) (HAMMER2_RESOLVE_*). The caller must
2243 * handle crc-checks and so forth, and should check chain->error before
2244 * assuming that the data is good.
2246 * To handle insertion races pass the INSERT_RACE flag along with the
2247 * generation number of the core. NULL will be returned if the generation
2248 * number changes before we have a chance to insert the chain. Insert
2249 * races can occur because the parent might be held shared.
2251 * Caller must hold the parent locked shared or exclusive since we may
2252 * need the parent's bref array to find our block.
2254 * WARNING! chain->pmp is always set to NULL for any chain representing
2255 * part of the super-root topology.
2258 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2259 hammer2_blockref_t *bref, int how)
2261 hammer2_dev_t *hmp = parent->hmp;
2262 hammer2_chain_t *chain;
2266 * Allocate a chain structure representing the existing media
2267 * entry. Resulting chain has one ref and is not locked.
2269 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2270 chain = hammer2_chain_alloc(hmp, NULL, bref);
2272 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2273 /* ref'd chain returned */
2276 * Flag that the chain is in the parent's blockmap so delete/flush
2277 * knows what to do with it.
2279 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2282 * chain must be locked to avoid unexpected ripouts
2284 hammer2_chain_lock(chain, how);
2287 * Link the chain into its parent. A spinlock is required to safely
2288 * access the RBTREE, and it is possible to collide with another
2289 * hammer2_chain_get() operation because the caller might only hold
2290 * a shared lock on the parent.
2292 * NOTE: Get races can occur quite often when we distribute
2293 * asynchronous read-aheads across multiple threads.
2295 KKASSERT(parent->refs > 0);
2296 error = hammer2_chain_insert(parent, chain,
2297 HAMMER2_CHAIN_INSERT_SPIN |
2298 HAMMER2_CHAIN_INSERT_RACE,
2301 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2302 /*kprintf("chain %p get race\n", chain);*/
2303 hammer2_chain_unlock(chain);
2304 hammer2_chain_drop(chain);
2307 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2311 * Return our new chain referenced but not locked, or NULL if
2318 * Lookup initialization/completion API
2321 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2323 hammer2_chain_ref(parent);
2324 if (flags & HAMMER2_LOOKUP_SHARED) {
2325 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2326 HAMMER2_RESOLVE_SHARED);
2328 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2334 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2337 hammer2_chain_unlock(parent);
2338 hammer2_chain_drop(parent);
2343 * Take the locked chain and return a locked parent. The chain remains
2344 * locked on return, but may have to be temporarily unlocked to acquire
2345 * the parent. Because of this, (chain) must be stable and cannot be
2346 * deleted while it was temporarily unlocked (typically means that (chain)
2349 * Pass HAMMER2_RESOLVE_* flags in flags.
2351 * This will work even if the chain is errored, and the caller can check
2352 * parent->error on return if desired since the parent will be locked.
2354 * This function handles the lock order reversal.
2357 hammer2_chain_getparent(hammer2_chain_t *chain, int flags)
2359 hammer2_chain_t *parent;
2362 * Be careful of order, chain must be unlocked before parent
2363 * is locked below to avoid a deadlock. Try it trivially first.
2365 parent = chain->parent;
2367 panic("hammer2_chain_getparent: no parent");
2368 hammer2_chain_ref(parent);
2369 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0)
2373 hammer2_chain_unlock(chain);
2374 hammer2_chain_lock(parent, flags);
2375 hammer2_chain_lock(chain, flags);
2378 * Parent relinking races are quite common. We have to get
2379 * it right or we will blow up the block table.
2381 if (chain->parent == parent)
2383 hammer2_chain_unlock(parent);
2384 hammer2_chain_drop(parent);
2386 parent = chain->parent;
2388 panic("hammer2_chain_getparent: no parent");
2389 hammer2_chain_ref(parent);
2395 * Take the locked chain and return a locked parent. The chain is unlocked
2396 * and dropped. *chainp is set to the returned parent as a convenience.
2397 * Pass HAMMER2_RESOLVE_* flags in flags.
2399 * This will work even if the chain is errored, and the caller can check
2400 * parent->error on return if desired since the parent will be locked.
2402 * The chain does NOT need to be stable. We use a tracking structure
2403 * to track the expected parent if the chain is deleted out from under us.
2405 * This function handles the lock order reversal.
2408 hammer2_chain_repparent(hammer2_chain_t **chainp, int flags)
2410 hammer2_chain_t *chain;
2411 hammer2_chain_t *parent;
2412 struct hammer2_reptrack reptrack;
2413 struct hammer2_reptrack **repp;
2416 * Be careful of order, chain must be unlocked before parent
2417 * is locked below to avoid a deadlock. Try it trivially first.
2420 parent = chain->parent;
2421 if (parent == NULL) {
2422 hammer2_spin_unex(&chain->core.spin);
2423 panic("hammer2_chain_repparent: no parent");
2425 hammer2_chain_ref(parent);
2426 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0) {
2427 hammer2_chain_unlock(chain);
2428 hammer2_chain_drop(chain);
2435 * Ok, now it gets a bit nasty. There are multiple situations where
2436 * the parent might be in the middle of a deletion, or where the child
2437 * (chain) might be deleted the instant we let go of its lock.
2438 * We can potentially end up in a no-win situation!
2440 * In particular, the indirect_maintenance() case can cause these
2443 * To deal with this we install a reptrack structure in the parent
2444 * This reptrack structure 'owns' the parent ref and will automatically
2445 * migrate to the parent's parent if the parent is deleted permanently.
2447 hammer2_spin_init(&reptrack.spin, "h2reptrk");
2448 reptrack.chain = parent;
2449 hammer2_chain_ref(parent); /* for the reptrack */
2451 hammer2_spin_ex(&parent->core.spin);
2452 reptrack.next = parent->core.reptrack;
2453 parent->core.reptrack = &reptrack;
2454 hammer2_spin_unex(&parent->core.spin);
2456 hammer2_chain_unlock(chain);
2457 hammer2_chain_drop(chain);
2458 chain = NULL; /* gone */
2461 * At the top of this loop, chain is gone and parent is refd both
2462 * by us explicitly AND via our reptrack. We are attempting to
2466 hammer2_chain_lock(parent, flags);
2468 if (reptrack.chain == parent)
2470 hammer2_chain_unlock(parent);
2471 hammer2_chain_drop(parent);
2473 kprintf("hammer2: debug REPTRACK %p->%p\n",
2474 parent, reptrack.chain);
2475 hammer2_spin_ex(&reptrack.spin);
2476 parent = reptrack.chain;
2477 hammer2_chain_ref(parent);
2478 hammer2_spin_unex(&reptrack.spin);
2482 * Once parent is locked and matches our reptrack, our reptrack
2483 * will be stable and we have our parent. We can unlink our
2486 * WARNING! Remember that the chain lock might be shared. Chains
2487 * locked shared have stable parent linkages.
2489 hammer2_spin_ex(&parent->core.spin);
2490 repp = &parent->core.reptrack;
2491 while (*repp != &reptrack)
2492 repp = &(*repp)->next;
2493 *repp = reptrack.next;
2494 hammer2_spin_unex(&parent->core.spin);
2496 hammer2_chain_drop(parent); /* reptrack ref */
2497 *chainp = parent; /* return parent lock+ref */
2503 * Dispose of any linked reptrack structures in (chain) by shifting them to
2504 * (parent). Both (chain) and (parent) must be exclusively locked.
2506 * This is interlocked against any children of (chain) on the other side.
2507 * No children so remain as-of when this is called so we can test
2508 * core.reptrack without holding the spin-lock.
2510 * Used whenever the caller intends to permanently delete chains related
2511 * to topological recursions (BREF_TYPE_INDIRECT, BREF_TYPE_FREEMAP_NODE),
2512 * where the chains underneath the node being deleted are given a new parent
2513 * above the node being deleted.
2517 hammer2_chain_repchange(hammer2_chain_t *parent, hammer2_chain_t *chain)
2519 struct hammer2_reptrack *reptrack;
2521 KKASSERT(chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree));
2522 while (chain->core.reptrack) {
2523 hammer2_spin_ex(&parent->core.spin);
2524 hammer2_spin_ex(&chain->core.spin);
2525 reptrack = chain->core.reptrack;
2526 if (reptrack == NULL) {
2527 hammer2_spin_unex(&chain->core.spin);
2528 hammer2_spin_unex(&parent->core.spin);
2531 hammer2_spin_ex(&reptrack->spin);
2532 chain->core.reptrack = reptrack->next;
2533 reptrack->chain = parent;
2534 reptrack->next = parent->core.reptrack;
2535 parent->core.reptrack = reptrack;
2536 hammer2_chain_ref(parent); /* reptrack */
2538 hammer2_spin_unex(&chain->core.spin);
2539 hammer2_spin_unex(&parent->core.spin);
2540 kprintf("hammer2: debug repchange %p %p->%p\n",
2541 reptrack, chain, parent);
2542 hammer2_chain_drop(chain); /* reptrack */
2547 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2548 * (*parentp) typically points to an inode but can also point to a related
2549 * indirect block and this function will recurse upwards and find the inode
2550 * or the nearest undeleted indirect block covering the key range.
2552 * This function unconditionally sets *errorp, replacing any previous value.
2554 * (*parentp) must be exclusive or shared locked (depending on flags) and
2555 * referenced and can be an inode or an existing indirect block within the
2558 * If (*parent) is errored out, this function will not attempt to recurse
2559 * the radix tree and will return NULL along with an appropriate *errorp.
2560 * If NULL is returned and *errorp is 0, the requested lookup could not be
2563 * On return (*parentp) will be modified to point at the deepest parent chain
2564 * element encountered during the search, as a helper for an insertion or
2567 * The new (*parentp) will be locked shared or exclusive (depending on flags),
2568 * and referenced, and the old will be unlocked and dereferenced (no change
2569 * if they are both the same). This is particularly important if the caller
2570 * wishes to insert a new chain, (*parentp) will be set properly even if NULL
2571 * is returned, as long as no error occurred.
2573 * The matching chain will be returned locked according to flags.
2577 * NULL is returned if no match was found, but (*parentp) will still
2578 * potentially be adjusted.
2580 * On return (*key_nextp) will point to an iterative value for key_beg.
2581 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2583 * This function will also recurse up the chain if the key is not within the
2584 * current parent's range. (*parentp) can never be set to NULL. An iteration
2585 * can simply allow (*parentp) to float inside the loop.
2587 * NOTE! chain->data is not always resolved. By default it will not be
2588 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2589 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2590 * BREF_TYPE_DATA as the device buffer can alias the logical file
2595 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2596 hammer2_key_t key_beg, hammer2_key_t key_end,
2597 int *errorp, int flags)
2600 hammer2_chain_t *parent;
2601 hammer2_chain_t *chain;
2602 hammer2_blockref_t *base;
2603 hammer2_blockref_t *bref;
2604 hammer2_blockref_t bcopy;
2605 hammer2_key_t scan_beg;
2606 hammer2_key_t scan_end;
2608 int how_always = HAMMER2_RESOLVE_ALWAYS;
2609 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2612 int maxloops = 300000;
2613 volatile hammer2_mtx_t save_mtx;
2615 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2616 how_maybe = how_always;
2617 how = HAMMER2_RESOLVE_ALWAYS;
2618 } else if (flags & HAMMER2_LOOKUP_NODATA) {
2619 how = HAMMER2_RESOLVE_NEVER;
2621 how = HAMMER2_RESOLVE_MAYBE;
2623 if (flags & HAMMER2_LOOKUP_SHARED) {
2624 how_maybe |= HAMMER2_RESOLVE_SHARED;
2625 how_always |= HAMMER2_RESOLVE_SHARED;
2626 how |= HAMMER2_RESOLVE_SHARED;
2630 * Recurse (*parentp) upward if necessary until the parent completely
2631 * encloses the key range or we hit the inode.
2633 * Handle races against the flusher deleting indirect nodes on its
2634 * way back up by continuing to recurse upward past the deletion.
2640 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2641 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2642 scan_beg = parent->bref.key;
2643 scan_end = scan_beg +
2644 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2645 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2646 if (key_beg >= scan_beg && key_end <= scan_end)
2649 parent = hammer2_chain_repparent(parentp, how_maybe);
2652 if (--maxloops == 0)
2653 panic("hammer2_chain_lookup: maxloops");
2655 * Locate the blockref array. Currently we do a fully associative
2656 * search through the array.
2658 switch(parent->bref.type) {
2659 case HAMMER2_BREF_TYPE_INODE:
2661 * Special shortcut for embedded data returns the inode
2662 * itself. Callers must detect this condition and access
2663 * the embedded data (the strategy code does this for us).
2665 * This is only applicable to regular files and softlinks.
2667 * We need a second lock on parent. Since we already have
2668 * a lock we must pass LOCKAGAIN to prevent unexpected
2669 * blocking (we don't want to block on a second shared
2670 * ref if an exclusive lock is pending)
2672 if (parent->data->ipdata.meta.op_flags &
2673 HAMMER2_OPFLAG_DIRECTDATA) {
2674 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2676 *key_nextp = key_end + 1;
2679 hammer2_chain_ref(parent);
2680 hammer2_chain_lock(parent, how_always |
2681 HAMMER2_RESOLVE_LOCKAGAIN);
2682 *key_nextp = key_end + 1;
2685 base = &parent->data->ipdata.u.blockset.blockref[0];
2686 count = HAMMER2_SET_COUNT;
2688 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2689 case HAMMER2_BREF_TYPE_INDIRECT:
2691 * Handle MATCHIND on the parent
2693 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2694 scan_beg = parent->bref.key;
2695 scan_end = scan_beg +
2696 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2697 if (key_beg == scan_beg && key_end == scan_end) {
2699 hammer2_chain_ref(chain);
2700 hammer2_chain_lock(chain, how_maybe);
2701 *key_nextp = scan_end + 1;
2707 * Optimize indirect blocks in the INITIAL state to avoid
2710 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2713 if (parent->data == NULL) {
2714 kprintf("parent->data is NULL %p\n", parent);
2716 tsleep(parent, 0, "xxx", 0);
2718 base = &parent->data->npdata[0];
2720 count = parent->bytes / sizeof(hammer2_blockref_t);
2722 case HAMMER2_BREF_TYPE_VOLUME:
2723 base = &parent->data->voldata.sroot_blockset.blockref[0];
2724 count = HAMMER2_SET_COUNT;
2726 case HAMMER2_BREF_TYPE_FREEMAP:
2727 base = &parent->data->blkset.blockref[0];
2728 count = HAMMER2_SET_COUNT;
2731 kprintf("hammer2_chain_lookup: unrecognized "
2732 "blockref(B) type: %d",
2735 tsleep(&base, 0, "dead", 0);
2736 panic("hammer2_chain_lookup: unrecognized "
2737 "blockref(B) type: %d",
2739 base = NULL; /* safety */
2740 count = 0; /* safety */
2744 * No lookup is possible if the parent is errored. We delayed
2745 * this check as long as we could to ensure that the parent backup,
2746 * embedded data, and MATCHIND code could still execute.
2748 if (parent->error) {
2749 *errorp = parent->error;
2754 * Merged scan to find next candidate.
2756 * hammer2_base_*() functions require the parent->core.live_* fields
2757 * to be synchronized.
2759 * We need to hold the spinlock to access the block array and RB tree
2760 * and to interlock chain creation.
2762 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2763 hammer2_chain_countbrefs(parent, base, count);
2768 hammer2_spin_ex(&parent->core.spin);
2769 chain = hammer2_combined_find(parent, base, count,
2773 generation = parent->core.generation;
2776 * Exhausted parent chain, iterate.
2779 KKASSERT(chain == NULL);
2780 hammer2_spin_unex(&parent->core.spin);
2781 if (key_beg == key_end) /* short cut single-key case */
2785 * Stop if we reached the end of the iteration.
2787 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2788 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2793 * Calculate next key, stop if we reached the end of the
2794 * iteration, otherwise go up one level and loop.
2796 key_beg = parent->bref.key +
2797 ((hammer2_key_t)1 << parent->bref.keybits);
2798 if (key_beg == 0 || key_beg > key_end)
2800 parent = hammer2_chain_repparent(parentp, how_maybe);
2805 * Selected from blockref or in-memory chain.
2808 if (chain == NULL) {
2809 hammer2_spin_unex(&parent->core.spin);
2810 if (bcopy.type == HAMMER2_BREF_TYPE_INDIRECT ||
2811 bcopy.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2812 chain = hammer2_chain_get(parent, generation,
2815 chain = hammer2_chain_get(parent, generation,
2821 hammer2_chain_ref(chain);
2822 hammer2_spin_unex(&parent->core.spin);
2825 * chain is referenced but not locked. We must lock the
2826 * chain to obtain definitive state.
2828 if (bcopy.type == HAMMER2_BREF_TYPE_INDIRECT ||
2829 bcopy.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2830 hammer2_chain_lock(chain, how_maybe);
2832 hammer2_chain_lock(chain, how);
2834 KKASSERT(chain->parent == parent);
2836 if (bcmp(&bcopy, &chain->bref, sizeof(bcopy)) ||
2837 chain->parent != parent) {
2838 hammer2_chain_unlock(chain);
2839 hammer2_chain_drop(chain);
2840 chain = NULL; /* SAFETY */
2846 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2848 * NOTE: Chain's key range is not relevant as there might be
2849 * one-offs within the range that are not deleted.
2851 * NOTE: Lookups can race delete-duplicate because
2852 * delete-duplicate does not lock the parent's core
2853 * (they just use the spinlock on the core).
2855 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2856 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2857 chain->bref.data_off, chain->bref.type,
2859 hammer2_chain_unlock(chain);
2860 hammer2_chain_drop(chain);
2861 chain = NULL; /* SAFETY */
2862 key_beg = *key_nextp;
2863 if (key_beg == 0 || key_beg > key_end)
2869 * If the chain element is an indirect block it becomes the new
2870 * parent and we loop on it. We must maintain our top-down locks
2871 * to prevent the flusher from interfering (i.e. doing a
2872 * delete-duplicate and leaving us recursing down a deleted chain).
2874 * The parent always has to be locked with at least RESOLVE_MAYBE
2875 * so we can access its data. It might need a fixup if the caller
2876 * passed incompatible flags. Be careful not to cause a deadlock
2877 * as a data-load requires an exclusive lock.
2879 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2880 * range is within the requested key range we return the indirect
2881 * block and do NOT loop. This is usually only used to acquire
2884 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2885 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2886 save_mtx = parent->lock;
2887 hammer2_chain_unlock(parent);
2888 hammer2_chain_drop(parent);
2889 *parentp = parent = chain;
2890 chain = NULL; /* SAFETY */
2895 * All done, return the locked chain.
2897 * If the caller does not want a locked chain, replace the lock with
2898 * a ref. Perhaps this can eventually be optimized to not obtain the
2899 * lock in the first place for situations where the data does not
2900 * need to be resolved.
2902 * NOTE! A chain->error must be tested by the caller upon return.
2903 * *errorp is only set based on issues which occur while
2904 * trying to reach the chain.
2910 * After having issued a lookup we can iterate all matching keys.
2912 * If chain is non-NULL we continue the iteration from just after it's index.
2914 * If chain is NULL we assume the parent was exhausted and continue the
2915 * iteration at the next parent.
2917 * If a fatal error occurs (typically an I/O error), a dummy chain is
2918 * returned with chain->error and error-identifying information set. This
2919 * chain will assert if you try to do anything fancy with it.
2921 * XXX Depending on where the error occurs we should allow continued iteration.
2923 * parent must be locked on entry and remains locked throughout. chain's
2924 * lock status must match flags. Chain is always at least referenced.
2926 * WARNING! The MATCHIND flag does not apply to this function.
2929 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2930 hammer2_key_t *key_nextp,
2931 hammer2_key_t key_beg, hammer2_key_t key_end,
2932 int *errorp, int flags)
2934 hammer2_chain_t *parent;
2938 * Calculate locking flags for upward recursion.
2940 how_maybe = HAMMER2_RESOLVE_MAYBE;
2941 if (flags & HAMMER2_LOOKUP_SHARED)
2942 how_maybe |= HAMMER2_RESOLVE_SHARED;
2948 * Calculate the next index and recalculate the parent if necessary.
2951 key_beg = chain->bref.key +
2952 ((hammer2_key_t)1 << chain->bref.keybits);
2953 hammer2_chain_unlock(chain);
2954 hammer2_chain_drop(chain);
2957 * chain invalid past this point, but we can still do a
2958 * pointer comparison w/parent.
2960 * Any scan where the lookup returned degenerate data embedded
2961 * in the inode has an invalid index and must terminate.
2963 if (chain == parent)
2965 if (key_beg == 0 || key_beg > key_end)
2968 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2969 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2971 * We reached the end of the iteration.
2976 * Continue iteration with next parent unless the current
2977 * parent covers the range.
2979 * (This also handles the case of a deleted, empty indirect
2982 key_beg = parent->bref.key +
2983 ((hammer2_key_t)1 << parent->bref.keybits);
2984 if (key_beg == 0 || key_beg > key_end)
2986 parent = hammer2_chain_repparent(parentp, how_maybe);
2992 return (hammer2_chain_lookup(parentp, key_nextp,
2998 * Caller wishes to iterate chains under parent, loading new chains into
2999 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
3000 * then call hammer2_chain_scan() repeatedly until a non-zero return.
3001 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
3002 * with the returned chain for the scan. The returned *chainp will be
3003 * locked and referenced. Any prior contents will be unlocked and dropped.
3005 * Caller should check the return value. A normal scan EOF will return
3006 * exactly HAMMER2_ERROR_EOF. Any other non-zero value indicates an
3007 * error trying to access parent data. Any error in the returned chain
3008 * must be tested separately by the caller.
3010 * (*chainp) is dropped on each scan, but will only be set if the returned
3011 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
3012 * returned via *chainp. The caller will get their bref only.
3014 * The raw scan function is similar to lookup/next but does not seek to a key.
3015 * Blockrefs are iterated via first_bref = (parent, NULL) and
3016 * next_chain = (parent, bref).
3018 * The passed-in parent must be locked and its data resolved. The function
3019 * nominally returns a locked and referenced *chainp != NULL for chains
3020 * the caller might need to recurse on (and will dipose of any *chainp passed
3021 * in). The caller must check the chain->bref.type either way.
3024 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
3025 hammer2_blockref_t *bref, int *firstp,
3029 hammer2_blockref_t *base;
3030 hammer2_blockref_t *bref_ptr;
3032 hammer2_key_t next_key;
3033 hammer2_chain_t *chain = NULL;
3035 int how_always = HAMMER2_RESOLVE_ALWAYS;
3036 int how_maybe = HAMMER2_RESOLVE_MAYBE;
3039 int maxloops = 300000;
3046 * Scan flags borrowed from lookup.
3048 if (flags & HAMMER2_LOOKUP_ALWAYS) {
3049 how_maybe = how_always;
3050 how = HAMMER2_RESOLVE_ALWAYS;
3051 } else if (flags & HAMMER2_LOOKUP_NODATA) {
3052 how = HAMMER2_RESOLVE_NEVER;
3054 how = HAMMER2_RESOLVE_MAYBE;
3056 if (flags & HAMMER2_LOOKUP_SHARED) {
3057 how_maybe |= HAMMER2_RESOLVE_SHARED;
3058 how_always |= HAMMER2_RESOLVE_SHARED;
3059 how |= HAMMER2_RESOLVE_SHARED;
3063 * Calculate key to locate first/next element, unlocking the previous
3064 * element as we go. Be careful, the key calculation can overflow.
3066 * (also reset bref to NULL)
3072 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
3073 if ((chain = *chainp) != NULL) {
3075 hammer2_chain_unlock(chain);
3076 hammer2_chain_drop(chain);
3080 error |= HAMMER2_ERROR_EOF;
3086 if (parent->error) {
3087 error = parent->error;
3090 if (--maxloops == 0)
3091 panic("hammer2_chain_scan: maxloops");
3094 * Locate the blockref array. Currently we do a fully associative
3095 * search through the array.
3097 switch(parent->bref.type) {
3098 case HAMMER2_BREF_TYPE_INODE:
3100 * An inode with embedded data has no sub-chains.
3102 * WARNING! Bulk scan code may pass a static chain marked
3103 * as BREF_TYPE_INODE with a copy of the volume
3104 * root blockset to snapshot the volume.
3106 if (parent->data->ipdata.meta.op_flags &
3107 HAMMER2_OPFLAG_DIRECTDATA) {
3108 error |= HAMMER2_ERROR_EOF;
3111 base = &parent->data->ipdata.u.blockset.blockref[0];
3112 count = HAMMER2_SET_COUNT;
3114 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3115 case HAMMER2_BREF_TYPE_INDIRECT:
3117 * Optimize indirect blocks in the INITIAL state to avoid
3120 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3123 if (parent->data == NULL)
3124 panic("parent->data is NULL");
3125 base = &parent->data->npdata[0];
3127 count = parent->bytes / sizeof(hammer2_blockref_t);
3129 case HAMMER2_BREF_TYPE_VOLUME:
3130 base = &parent->data->voldata.sroot_blockset.blockref[0];
3131 count = HAMMER2_SET_COUNT;
3133 case HAMMER2_BREF_TYPE_FREEMAP:
3134 base = &parent->data->blkset.blockref[0];
3135 count = HAMMER2_SET_COUNT;
3138 panic("hammer2_chain_scan: unrecognized blockref type: %d",
3140 base = NULL; /* safety */
3141 count = 0; /* safety */
3145 * Merged scan to find next candidate.
3147 * hammer2_base_*() functions require the parent->core.live_* fields
3148 * to be synchronized.
3150 * We need to hold the spinlock to access the block array and RB tree
3151 * and to interlock chain creation.
3153 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3154 hammer2_chain_countbrefs(parent, base, count);
3158 hammer2_spin_ex(&parent->core.spin);
3159 chain = hammer2_combined_find(parent, base, count,
3161 key, HAMMER2_KEY_MAX,
3163 generation = parent->core.generation;
3166 * Exhausted parent chain, we're done.
3168 if (bref_ptr == NULL) {
3169 hammer2_spin_unex(&parent->core.spin);
3170 KKASSERT(chain == NULL);
3171 error |= HAMMER2_ERROR_EOF;
3176 * Copy into the supplied stack-based blockref.
3181 * Selected from blockref or in-memory chain.
3183 if (chain == NULL) {
3184 switch(bref->type) {
3185 case HAMMER2_BREF_TYPE_INODE:
3186 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3187 case HAMMER2_BREF_TYPE_INDIRECT:
3188 case HAMMER2_BREF_TYPE_VOLUME:
3189 case HAMMER2_BREF_TYPE_FREEMAP:
3191 * Recursion, always get the chain
3193 hammer2_spin_unex(&parent->core.spin);
3194 chain = hammer2_chain_get(parent, generation,
3201 * No recursion, do not waste time instantiating
3202 * a chain, just iterate using the bref.
3204 hammer2_spin_unex(&parent->core.spin);
3209 * Recursion or not we need the chain in order to supply
3212 hammer2_chain_ref(chain);
3213 hammer2_spin_unex(&parent->core.spin);
3214 hammer2_chain_lock(chain, how);
3217 (bcmp(bref, &chain->bref, sizeof(*bref)) ||
3218 chain->parent != parent)) {
3219 hammer2_chain_unlock(chain);
3220 hammer2_chain_drop(chain);
3226 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
3228 * NOTE: chain's key range is not relevant as there might be
3229 * one-offs within the range that are not deleted.
3231 * NOTE: XXX this could create problems with scans used in
3232 * situations other than mount-time recovery.
3234 * NOTE: Lookups can race delete-duplicate because
3235 * delete-duplicate does not lock the parent's core
3236 * (they just use the spinlock on the core).
3238 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3239 hammer2_chain_unlock(chain);
3240 hammer2_chain_drop(chain);
3245 error |= HAMMER2_ERROR_EOF;
3253 * All done, return the bref or NULL, supply chain if necessary.
3261 * Create and return a new hammer2 system memory structure of the specified
3262 * key, type and size and insert it under (*parentp). This is a full
3263 * insertion, based on the supplied key/keybits, and may involve creating
3264 * indirect blocks and moving other chains around via delete/duplicate.
3266 * This call can be made with parent == NULL as long as a non -1 methods
3267 * is supplied. hmp must also be supplied in this situation (otherwise
3268 * hmp is extracted from the supplied parent). The chain will be detached
3269 * from the topology. A later call with both parent and chain can be made
3272 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3273 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3274 * FULL. This typically means that the caller is creating the chain after
3275 * doing a hammer2_chain_lookup().
3277 * (*parentp) must be exclusive locked and may be replaced on return
3278 * depending on how much work the function had to do.
3280 * (*parentp) must not be errored or this function will assert.
3282 * (*chainp) usually starts out NULL and returns the newly created chain,
3283 * but if the caller desires the caller may allocate a disconnected chain
3284 * and pass it in instead.
3286 * This function should NOT be used to insert INDIRECT blocks. It is
3287 * typically used to create/insert inodes and data blocks.
3289 * Caller must pass-in an exclusively locked parent the new chain is to
3290 * be inserted under, and optionally pass-in a disconnected, exclusively
3291 * locked chain to insert (else we create a new chain). The function will
3292 * adjust (*parentp) as necessary, create or connect the chain, and
3293 * return an exclusively locked chain in *chainp.
3295 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3296 * and will be reassigned.
3298 * NOTE: returns HAMMER_ERROR_* flags
3301 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3302 hammer2_dev_t *hmp, hammer2_pfs_t *pmp, int methods,
3303 hammer2_key_t key, int keybits, int type, size_t bytes,
3304 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3306 hammer2_chain_t *chain;
3307 hammer2_chain_t *parent;
3308 hammer2_blockref_t *base;
3309 hammer2_blockref_t dummy;
3313 int maxloops = 300000;
3316 * Topology may be crossing a PFS boundary.
3320 KKASSERT(hammer2_mtx_owned(&parent->lock));
3321 KKASSERT(parent->error == 0);
3326 if (chain == NULL) {
3328 * First allocate media space and construct the dummy bref,
3329 * then allocate the in-memory chain structure. Set the
3330 * INITIAL flag for fresh chains which do not have embedded
3333 * XXX for now set the check mode of the child based on
3334 * the parent or, if the parent is an inode, the
3335 * specification in the inode.
3337 bzero(&dummy, sizeof(dummy));
3340 dummy.keybits = keybits;
3341 dummy.data_off = hammer2_getradix(bytes);
3344 * Inherit methods from parent by default. Primarily used
3345 * for BREF_TYPE_DATA. Non-data types *must* be set to
3346 * a non-NONE check algorithm.
3349 dummy.methods = parent->bref.methods;
3351 dummy.methods = (uint8_t)methods;
3353 if (type != HAMMER2_BREF_TYPE_DATA &&
3354 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3356 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3359 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3362 * Lock the chain manually, chain_lock will load the chain
3363 * which we do NOT want to do. (note: chain->refs is set
3364 * to 1 by chain_alloc() for us, but lockcnt is not).
3367 hammer2_mtx_ex(&chain->lock);
3369 ++curthread->td_tracker;
3372 * Set INITIAL to optimize I/O. The flag will generally be
3373 * processed when we call hammer2_chain_modify().
3375 * Recalculate bytes to reflect the actual media block
3376 * allocation. Handle special case radix 0 == 0 bytes.
3378 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3380 bytes = (hammer2_off_t)1 << bytes;
3381 chain->bytes = bytes;
3384 case HAMMER2_BREF_TYPE_VOLUME:
3385 case HAMMER2_BREF_TYPE_FREEMAP:
3386 panic("hammer2_chain_create: called with volume type");
3388 case HAMMER2_BREF_TYPE_INDIRECT:
3389 panic("hammer2_chain_create: cannot be used to"
3390 "create indirect block");
3392 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3393 panic("hammer2_chain_create: cannot be used to"
3394 "create freemap root or node");
3396 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3397 KKASSERT(bytes == sizeof(chain->data->bmdata));
3399 case HAMMER2_BREF_TYPE_DIRENT:
3400 case HAMMER2_BREF_TYPE_INODE:
3401 case HAMMER2_BREF_TYPE_DATA:
3404 * leave chain->data NULL, set INITIAL
3406 KKASSERT(chain->data == NULL);
3407 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3412 * We are reattaching a previously deleted chain, possibly
3413 * under a new parent and possibly with a new key/keybits.
3414 * The chain does not have to be in a modified state. The
3415 * UPDATE flag will be set later on in this routine.
3417 * Do NOT mess with the current state of the INITIAL flag.
3419 chain->bref.key = key;
3420 chain->bref.keybits = keybits;
3421 if (chain->flags & HAMMER2_CHAIN_DELETED)
3422 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3423 KKASSERT(chain->parent == NULL);
3427 * Set the appropriate bref flag if requested.
3429 * NOTE! Callers can call this function to move chains without
3430 * knowing about special flags, so don't clear bref flags
3433 if (flags & HAMMER2_INSERT_PFSROOT)
3434 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3440 * Calculate how many entries we have in the blockref array and
3441 * determine if an indirect block is required when inserting into
3445 if (--maxloops == 0)
3446 panic("hammer2_chain_create: maxloops");
3448 switch(parent->bref.type) {
3449 case HAMMER2_BREF_TYPE_INODE:
3450 if ((parent->data->ipdata.meta.op_flags &
3451 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3452 kprintf("hammer2: parent set for direct-data! "
3453 "pkey=%016jx ckey=%016jx\n",
3457 KKASSERT((parent->data->ipdata.meta.op_flags &
3458 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3459 KKASSERT(parent->data != NULL);
3460 base = &parent->data->ipdata.u.blockset.blockref[0];
3461 count = HAMMER2_SET_COUNT;
3463 case HAMMER2_BREF_TYPE_INDIRECT:
3464 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3465 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3468 base = &parent->data->npdata[0];
3469 count = parent->bytes / sizeof(hammer2_blockref_t);
3471 case HAMMER2_BREF_TYPE_VOLUME:
3472 KKASSERT(parent->data != NULL);
3473 base = &parent->data->voldata.sroot_blockset.blockref[0];
3474 count = HAMMER2_SET_COUNT;
3476 case HAMMER2_BREF_TYPE_FREEMAP:
3477 KKASSERT(parent->data != NULL);
3478 base = &parent->data->blkset.blockref[0];
3479 count = HAMMER2_SET_COUNT;
3482 panic("hammer2_chain_create: unrecognized blockref type: %d",
3490 * Make sure we've counted the brefs
3492 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3493 hammer2_chain_countbrefs(parent, base, count);
3495 KASSERT(parent->core.live_count >= 0 &&
3496 parent->core.live_count <= count,
3497 ("bad live_count %d/%d (%02x, %d)",
3498 parent->core.live_count, count,
3499 parent->bref.type, parent->bytes));
3502 * If no free blockref could be found we must create an indirect
3503 * block and move a number of blockrefs into it. With the parent
3504 * locked we can safely lock each child in order to delete+duplicate
3505 * it without causing a deadlock.
3507 * This may return the new indirect block or the old parent depending
3508 * on where the key falls. NULL is returned on error.
3510 if (parent->core.live_count == count) {
3511 hammer2_chain_t *nparent;
3513 KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3515 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3516 mtid, type, &error);
3517 if (nparent == NULL) {
3519 hammer2_chain_drop(chain);
3523 if (parent != nparent) {
3524 hammer2_chain_unlock(parent);
3525 hammer2_chain_drop(parent);
3526 parent = *parentp = nparent;
3532 * fall through if parent, or skip to here if no parent.
3535 if (chain->flags & HAMMER2_CHAIN_DELETED)
3536 kprintf("Inserting deleted chain @%016jx\n",
3540 * Link the chain into its parent.
3542 if (chain->parent != NULL)
3543 panic("hammer2: hammer2_chain_create: chain already connected");
3544 KKASSERT(chain->parent == NULL);
3546 KKASSERT(parent->core.live_count < count);
3547 hammer2_chain_insert(parent, chain,
3548 HAMMER2_CHAIN_INSERT_SPIN |
3549 HAMMER2_CHAIN_INSERT_LIVE,
3555 * Mark the newly created chain modified. This will cause
3556 * UPDATE to be set and process the INITIAL flag.
3558 * Device buffers are not instantiated for DATA elements
3559 * as these are handled by logical buffers.
3561 * Indirect and freemap node indirect blocks are handled
3562 * by hammer2_chain_create_indirect() and not by this
3565 * Data for all other bref types is expected to be
3566 * instantiated (INODE, LEAF).
3568 switch(chain->bref.type) {
3569 case HAMMER2_BREF_TYPE_DATA:
3570 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3571 case HAMMER2_BREF_TYPE_DIRENT:
3572 case HAMMER2_BREF_TYPE_INODE:
3573 error = hammer2_chain_modify(chain, mtid, dedup_off,
3574 HAMMER2_MODIFY_OPTDATA);
3578 * Remaining types are not supported by this function.
3579 * In particular, INDIRECT and LEAF_NODE types are
3580 * handled by create_indirect().
3582 panic("hammer2_chain_create: bad type: %d",
3589 * When reconnecting a chain we must set UPDATE and
3590 * setflush so the flush recognizes that it must update
3591 * the bref in the parent.
3593 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3594 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3598 * We must setflush(parent) to ensure that it recurses through to
3599 * chain. setflush(chain) might not work because ONFLUSH is possibly
3600 * already set in the chain (so it won't recurse up to set it in the
3604 hammer2_chain_setflush(parent);
3613 * Move the chain from its old parent to a new parent. The chain must have
3614 * already been deleted or already disconnected (or never associated) with
3615 * a parent. The chain is reassociated with the new parent and the deleted
3616 * flag will be cleared (no longer deleted). The chain's modification state
3619 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3620 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3621 * FULL. This typically means that the caller is creating the chain after
3622 * doing a hammer2_chain_lookup().
3624 * Neither (parent) or (chain) can be errored.
3626 * If (parent) is non-NULL then the chain is inserted under the parent.
3628 * If (parent) is NULL then the newly duplicated chain is not inserted
3629 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3630 * passing into hammer2_chain_create() after this function returns).
3632 * WARNING! This function calls create which means it can insert indirect
3633 * blocks. This can cause other unrelated chains in the parent to
3634 * be moved to a newly inserted indirect block in addition to the
3638 hammer2_chain_rename(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3639 hammer2_tid_t mtid, int flags)
3641 hammer2_blockref_t *bref;
3643 hammer2_chain_t *parent;
3647 * WARNING! We should never resolve DATA to device buffers
3648 * (XXX allow it if the caller did?), and since
3649 * we currently do not have the logical buffer cache
3650 * buffer in-hand to fix its cached physical offset
3651 * we also force the modify code to not COW it. XXX
3653 * NOTE! We allow error'd chains to be renamed. The bref itself
3654 * is good and can be renamed. The content, however, may
3658 KKASSERT(chain->parent == NULL);
3659 /*KKASSERT(chain->error == 0); allow */
3662 * Now create a duplicate of the chain structure, associating
3663 * it with the same core, making it the same size, pointing it
3664 * to the same bref (the same media block).
3666 * NOTE: Handle special radix == 0 case (means 0 bytes).
3668 bref = &chain->bref;
3669 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3671 bytes = (hammer2_off_t)1 << bytes;
3674 * If parent is not NULL the duplicated chain will be entered under
3675 * the parent and the UPDATE bit set to tell flush to update
3678 * We must setflush(parent) to ensure that it recurses through to
3679 * chain. setflush(chain) might not work because ONFLUSH is possibly
3680 * already set in the chain (so it won't recurse up to set it in the
3683 * Having both chains locked is extremely important for atomicy.
3685 if (parentp && (parent = *parentp) != NULL) {
3686 KKASSERT(hammer2_mtx_owned(&parent->lock));
3687 KKASSERT(parent->refs > 0);
3688 KKASSERT(parent->error == 0);
3690 hammer2_chain_create(parentp, &chain, NULL, chain->pmp,
3691 HAMMER2_METH_DEFAULT,
3692 bref->key, bref->keybits, bref->type,
3693 chain->bytes, mtid, 0, flags);
3694 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3695 hammer2_chain_setflush(*parentp);
3700 * This works in tandem with delete_obref() to install a blockref in
3701 * (typically) an indirect block that is associated with the chain being
3702 * moved to *parentp.
3704 * The reason we need this function is that the caller needs to maintain
3705 * the blockref as it was, and not generate a new blockref for what might
3706 * be a modified chain. Otherwise stuff will leak into the flush that
3707 * the flush code's FLUSH_INODE_STOP flag is unable to catch.
3709 * It is EXTREMELY important that we properly set CHAIN_BMAPUPD and
3710 * CHAIN_UPDATE. We must set BMAPUPD if the bref does not match, and
3711 * we must clear CHAIN_UPDATE (that was likely set by the chain_rename) if
3712 * it does. Otherwise we can end up in a situation where H2 is unable to
3713 * clean up the in-memory chain topology.
3715 * The reason for this is that flushes do not generally flush through
3716 * BREF_TYPE_INODE chains and depend on a hammer2_inode_t queued to syncq
3717 * or sideq to properly flush and dispose of the related inode chain's flags.
3718 * Situations where the inode is not actually modified by the frontend,
3719 * but where we have to move the related chains around as we insert or cleanup
3720 * indirect blocks, can leave us with a 'dirty' (non-disposable) in-memory
3721 * inode chain that does not have a hammer2_inode_t associated with it.
3724 hammer2_chain_rename_obref(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3725 hammer2_tid_t mtid, int flags,
3726 hammer2_blockref_t *obref)
3728 hammer2_chain_rename(parentp, chain, mtid, flags);
3731 hammer2_blockref_t *tbase;
3734 KKASSERT((chain->flags & HAMMER2_CHAIN_BMAPPED) == 0);
3735 hammer2_chain_modify(*parentp, mtid, 0, 0);
3736 tbase = hammer2_chain_base_and_count(*parentp, &tcount);
3737 hammer2_base_insert(*parentp, tbase, tcount, chain, obref);
3738 if (bcmp(obref, &chain->bref, sizeof(chain->bref))) {
3739 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD |
3740 HAMMER2_CHAIN_UPDATE);
3742 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3748 * Helper function for deleting chains.
3750 * The chain is removed from the live view (the RBTREE) as well as the parent's
3751 * blockmap. Both chain and its parent must be locked.
3753 * parent may not be errored. chain can be errored.
3756 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3757 hammer2_tid_t mtid, int flags,
3758 hammer2_blockref_t *obref)
3763 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3764 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3765 KKASSERT(chain->parent == parent);
3768 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3770 * Chain is blockmapped, so there must be a parent.
3771 * Atomically remove the chain from the parent and remove
3772 * the blockmap entry. The parent must be set modified
3773 * to remove the blockmap entry.
3775 hammer2_blockref_t *base;
3778 KKASSERT(parent != NULL);
3779 KKASSERT(parent->error == 0);
3780 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3781 error = hammer2_chain_modify(parent, mtid, 0, 0);
3786 * Calculate blockmap pointer
3788 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3789 hammer2_spin_ex(&chain->core.spin);
3790 hammer2_spin_ex(&parent->core.spin);
3792 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3793 atomic_add_int(&parent->core.live_count, -1);
3794 ++parent->core.generation;
3795 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3796 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3797 --parent->core.chain_count;
3798 chain->parent = NULL;
3800 switch(parent->bref.type) {
3801 case HAMMER2_BREF_TYPE_INODE:
3803 * Access the inode's block array. However, there
3804 * is no block array if the inode is flagged
3808 (parent->data->ipdata.meta.op_flags &
3809 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3811 &parent->data->ipdata.u.blockset.blockref[0];
3815 count = HAMMER2_SET_COUNT;
3817 case HAMMER2_BREF_TYPE_INDIRECT:
3818 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3820 base = &parent->data->npdata[0];
3823 count = parent->bytes / sizeof(hammer2_blockref_t);
3825 case HAMMER2_BREF_TYPE_VOLUME:
3826 base = &parent->data->voldata.
3827 sroot_blockset.blockref[0];
3828 count = HAMMER2_SET_COUNT;
3830 case HAMMER2_BREF_TYPE_FREEMAP:
3831 base = &parent->data->blkset.blockref[0];
3832 count = HAMMER2_SET_COUNT;
3837 panic("_hammer2_chain_delete_helper: "
3838 "unrecognized blockref type: %d",
3843 * delete blockmapped chain from its parent.
3845 * The parent is not affected by any statistics in chain
3846 * which are pending synchronization. That is, there is
3847 * nothing to undo in the parent since they have not yet
3848 * been incorporated into the parent.
3850 * The parent is affected by statistics stored in inodes.
3851 * Those have already been synchronized, so they must be
3852 * undone. XXX split update possible w/delete in middle?
3855 hammer2_base_delete(parent, base, count, chain, obref);
3857 hammer2_spin_unex(&parent->core.spin);
3858 hammer2_spin_unex(&chain->core.spin);
3859 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3861 * Chain is not blockmapped but a parent is present.
3862 * Atomically remove the chain from the parent. There is
3863 * no blockmap entry to remove.
3865 * Because chain was associated with a parent but not
3866 * synchronized, the chain's *_count_up fields contain
3867 * inode adjustment statistics which must be undone.
3869 hammer2_spin_ex(&chain->core.spin);
3870 hammer2_spin_ex(&parent->core.spin);
3871 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3872 atomic_add_int(&parent->core.live_count, -1);
3873 ++parent->core.generation;
3874 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3875 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3876 --parent->core.chain_count;
3877 chain->parent = NULL;
3878 hammer2_spin_unex(&parent->core.spin);
3879 hammer2_spin_unex(&chain->core.spin);
3882 * Chain is not blockmapped and has no parent. This
3883 * is a degenerate case.
3885 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3892 * Create an indirect block that covers one or more of the elements in the
3893 * current parent. Either returns the existing parent with no locking or
3894 * ref changes or returns the new indirect block locked and referenced
3895 * and leaving the original parent lock/ref intact as well.
3897 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3899 * The returned chain depends on where the specified key falls.
3901 * The key/keybits for the indirect mode only needs to follow three rules:
3903 * (1) That all elements underneath it fit within its key space and
3905 * (2) That all elements outside it are outside its key space.
3907 * (3) When creating the new indirect block any elements in the current
3908 * parent that fit within the new indirect block's keyspace must be
3909 * moved into the new indirect block.
3911 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3912 * keyspace the the current parent, but lookup/iteration rules will
3913 * ensure (and must ensure) that rule (2) for all parents leading up
3914 * to the nearest inode or the root volume header is adhered to. This
3915 * is accomplished by always recursing through matching keyspaces in
3916 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3918 * The current implementation calculates the current worst-case keyspace by
3919 * iterating the current parent and then divides it into two halves, choosing
3920 * whichever half has the most elements (not necessarily the half containing
3921 * the requested key).
3923 * We can also opt to use the half with the least number of elements. This
3924 * causes lower-numbered keys (aka logical file offsets) to recurse through
3925 * fewer indirect blocks and higher-numbered keys to recurse through more.
3926 * This also has the risk of not moving enough elements to the new indirect
3927 * block and being forced to create several indirect blocks before the element
3930 * Must be called with an exclusively locked parent.
3932 * NOTE: *errorp set to HAMMER_ERROR_* flags
3934 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3935 hammer2_key_t *keyp, int keybits,
3936 hammer2_blockref_t *base, int count);
3937 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3938 hammer2_key_t *keyp, int keybits,
3939 hammer2_blockref_t *base, int count,
3941 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3942 hammer2_key_t *keyp, int keybits,
3943 hammer2_blockref_t *base, int count,
3947 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3948 hammer2_key_t create_key, int create_bits,
3949 hammer2_tid_t mtid, int for_type, int *errorp)
3952 hammer2_blockref_t *base;
3953 hammer2_blockref_t *bref;
3954 hammer2_blockref_t bcopy;
3955 hammer2_chain_t *chain;
3956 hammer2_chain_t *ichain;
3957 hammer2_chain_t dummy;
3958 hammer2_key_t key = create_key;
3959 hammer2_key_t key_beg;
3960 hammer2_key_t key_end;
3961 hammer2_key_t key_next;
3962 int keybits = create_bits;
3970 int maxloops = 300000;
3973 * Calculate the base blockref pointer or NULL if the chain
3974 * is known to be empty. We need to calculate the array count
3975 * for RB lookups either way.
3978 KKASSERT(hammer2_mtx_owned(&parent->lock));
3981 * Pre-modify the parent now to avoid having to deal with error
3982 * processing if we tried to later (in the middle of our loop).
3984 * We are going to be moving bref's around, the indirect blocks
3985 * cannot be in an initial state. Do not pass MODIFY_OPTDATA.
3987 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3989 kprintf("hammer2_create_indirect: error %08x %s\n",
3990 *errorp, hammer2_error_str(*errorp));
3993 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3995 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3996 base = hammer2_chain_base_and_count(parent, &count);
3999 * dummy used in later chain allocation (no longer used for lookups).
4001 bzero(&dummy, sizeof(dummy));
4004 * How big should our new indirect block be? It has to be at least
4005 * as large as its parent for splits to work properly.
4007 * The freemap uses a specific indirect block size. The number of
4008 * levels are built dynamically and ultimately depend on the size
4009 * volume. Because freemap blocks are taken from the reserved areas
4010 * of the volume our goal is efficiency (fewer levels) and not so
4011 * much to save disk space.
4013 * The first indirect block level for a directory usually uses
4014 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
4015 * the hash mechanism, this typically gives us a nominal
4016 * 32 * 4 entries with one level of indirection.
4018 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
4019 * indirect blocks. The initial 4 entries in the inode gives us
4020 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
4021 * of indirection gives us 137GB, and so forth. H2 can support
4022 * huge file sizes but they are not typical, so we try to stick
4023 * with compactness and do not use a larger indirect block size.
4025 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
4026 * due to the way indirect blocks are created this usually winds
4027 * up being extremely inefficient for small files. Even though
4028 * 16KB requires more levels of indirection for very large files,
4029 * the 16KB records can be ganged together into 64KB DIOs.
4031 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4032 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4033 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
4034 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4035 if (parent->data->ipdata.meta.type ==
4036 HAMMER2_OBJTYPE_DIRECTORY)
4037 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
4039 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
4042 nbytes = HAMMER2_IND_BYTES_NOM;
4044 if (nbytes < count * sizeof(hammer2_blockref_t)) {
4045 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
4046 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
4047 nbytes = count * sizeof(hammer2_blockref_t);
4049 ncount = nbytes / sizeof(hammer2_blockref_t);
4052 * When creating an indirect block for a freemap node or leaf
4053 * the key/keybits must be fitted to static radix levels because
4054 * particular radix levels use particular reserved blocks in the
4057 * This routine calculates the key/radix of the indirect block
4058 * we need to create, and whether it is on the high-side or the
4062 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4063 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4064 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
4067 case HAMMER2_BREF_TYPE_DATA:
4068 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
4069 base, count, ncount);
4071 case HAMMER2_BREF_TYPE_DIRENT:
4072 case HAMMER2_BREF_TYPE_INODE:
4073 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
4074 base, count, ncount);
4077 panic("illegal indirect block for bref type %d", for_type);
4082 * Normalize the key for the radix being represented, keeping the
4083 * high bits and throwing away the low bits.
4085 key &= ~(((hammer2_key_t)1 << keybits) - 1);
4088 * Ok, create our new indirect block
4090 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4091 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4092 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
4094 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
4096 dummy.bref.key = key;
4097 dummy.bref.keybits = keybits;
4098 dummy.bref.data_off = hammer2_getradix(nbytes);
4099 dummy.bref.methods =
4100 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
4101 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
4103 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
4104 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
4105 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
4106 /* ichain has one ref at this point */
4109 * We have to mark it modified to allocate its block, but use
4110 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
4111 * it won't be acted upon by the flush code.
4113 * XXX remove OPTDATA, we need a fully initialized indirect block to
4114 * be able to move the original blockref.
4116 *errorp = hammer2_chain_modify(ichain, mtid, 0, 0);
4118 kprintf("hammer2_alloc_indirect: error %08x %s\n",
4119 *errorp, hammer2_error_str(*errorp));
4120 hammer2_chain_unlock(ichain);
4121 hammer2_chain_drop(ichain);
4124 KKASSERT((ichain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4127 * Iterate the original parent and move the matching brefs into
4128 * the new indirect block.
4130 * XXX handle flushes.
4133 key_end = HAMMER2_KEY_MAX;
4134 key_next = 0; /* avoid gcc warnings */
4135 hammer2_spin_ex(&parent->core.spin);
4141 * Parent may have been modified, relocating its block array.
4142 * Reload the base pointer.
4144 base = hammer2_chain_base_and_count(parent, &count);
4146 if (++loops > 100000) {
4147 hammer2_spin_unex(&parent->core.spin);
4148 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
4149 reason, parent, base, count, key_next);
4153 * NOTE: spinlock stays intact, returned chain (if not NULL)
4154 * is not referenced or locked which means that we
4155 * cannot safely check its flagged / deletion status
4158 chain = hammer2_combined_find(parent, base, count,
4162 generation = parent->core.generation;
4165 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4168 * Skip keys that are not within the key/radix of the new
4169 * indirect block. They stay in the parent.
4171 if ((~(((hammer2_key_t)1 << keybits) - 1) &
4172 (key ^ bref->key)) != 0) {
4173 goto next_key_spinlocked;
4177 * Load the new indirect block by acquiring the related
4178 * chains (potentially from media as it might not be
4179 * in-memory). Then move it to the new parent (ichain).
4181 * chain is referenced but not locked. We must lock the
4182 * chain to obtain definitive state.
4187 * Use chain already present in the RBTREE
4189 hammer2_chain_ref(chain);
4190 hammer2_spin_unex(&parent->core.spin);
4191 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
4194 * Get chain for blockref element. _get returns NULL
4195 * on insertion race.
4197 hammer2_spin_unex(&parent->core.spin);
4198 chain = hammer2_chain_get(parent, generation, &bcopy,
4199 HAMMER2_RESOLVE_NEVER);
4200 if (chain == NULL) {
4202 hammer2_spin_ex(&parent->core.spin);
4208 * This is always live so if the chain has been deleted
4209 * we raced someone and we have to retry.
4211 * NOTE: Lookups can race delete-duplicate because
4212 * delete-duplicate does not lock the parent's core
4213 * (they just use the spinlock on the core).
4215 * (note reversed logic for this one)
4217 if (bcmp(&bcopy, &chain->bref, sizeof(bcopy)) ||
4218 chain->parent != parent ||
4219 (chain->flags & HAMMER2_CHAIN_DELETED)) {
4220 hammer2_chain_unlock(chain);
4221 hammer2_chain_drop(chain);
4222 if (hammer2_debug & 0x0040) {
4223 kprintf("LOST PARENT RETRY "
4224 "RETRY (%p,%p)->%p %08x\n",
4225 parent, chain->parent, chain, chain->flags);
4227 hammer2_spin_ex(&parent->core.spin);
4232 * Shift the chain to the indirect block.
4234 * WARNING! No reason for us to load chain data, pass NOSTATS
4235 * to prevent delete/insert from trying to access
4236 * inode stats (and thus asserting if there is no
4237 * chain->data loaded).
4239 * WARNING! The (parent, chain) deletion may modify the parent
4240 * and invalidate the base pointer.
4242 * WARNING! Parent must already be marked modified, so we
4243 * can assume that chain_delete always suceeds.
4245 * WARNING! hammer2_chain_repchange() does not have to be
4246 * called (and doesn't work anyway because we are
4247 * only doing a partial shift). A recursion that is
4248 * in-progress can continue at the current parent
4249 * and will be able to properly find its next key.
4251 error = hammer2_chain_delete_obref(parent, chain, mtid, 0,
4253 KKASSERT(error == 0);
4254 hammer2_chain_rename_obref(&ichain, chain, mtid, 0, &bcopy);
4255 hammer2_chain_unlock(chain);
4256 hammer2_chain_drop(chain);
4257 KKASSERT(parent->refs > 0);
4259 base = NULL; /* safety */
4260 hammer2_spin_ex(&parent->core.spin);
4261 next_key_spinlocked:
4262 if (--maxloops == 0)
4263 panic("hammer2_chain_create_indirect: maxloops");
4265 if (key_next == 0 || key_next > key_end)
4270 hammer2_spin_unex(&parent->core.spin);
4273 * Insert the new indirect block into the parent now that we've
4274 * cleared out some entries in the parent. We calculated a good
4275 * insertion index in the loop above (ichain->index).
4277 * We don't have to set UPDATE here because we mark ichain
4278 * modified down below (so the normal modified -> flush -> set-moved
4279 * sequence applies).
4281 * The insertion shouldn't race as this is a completely new block
4282 * and the parent is locked.
4284 base = NULL; /* safety, parent modify may change address */
4285 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
4286 KKASSERT(parent->core.live_count < count);
4287 hammer2_chain_insert(parent, ichain,
4288 HAMMER2_CHAIN_INSERT_SPIN |
4289 HAMMER2_CHAIN_INSERT_LIVE,
4293 * Make sure flushes propogate after our manual insertion.
4295 hammer2_chain_setflush(ichain);
4296 hammer2_chain_setflush(parent);
4299 * Figure out what to return.
4301 if (~(((hammer2_key_t)1 << keybits) - 1) &
4302 (create_key ^ key)) {
4304 * Key being created is outside the key range,
4305 * return the original parent.
4307 hammer2_chain_unlock(ichain);
4308 hammer2_chain_drop(ichain);
4311 * Otherwise its in the range, return the new parent.
4312 * (leave both the new and old parent locked).
4321 * Do maintenance on an indirect chain. Both parent and chain are locked.
4323 * Returns non-zero if (chain) is deleted, either due to being empty or
4324 * because its children were safely moved into the parent.
4327 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
4328 hammer2_chain_t *chain)
4330 hammer2_blockref_t *chain_base;
4331 hammer2_blockref_t *base;
4332 hammer2_blockref_t *bref;
4333 hammer2_blockref_t bcopy;
4334 hammer2_key_t key_next;
4335 hammer2_key_t key_beg;
4336 hammer2_key_t key_end;
4337 hammer2_chain_t *sub;
4344 * Make sure we have an accurate live_count
4346 if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4347 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4348 base = &chain->data->npdata[0];
4349 count = chain->bytes / sizeof(hammer2_blockref_t);
4350 hammer2_chain_countbrefs(chain, base, count);
4354 * If the indirect block is empty we can delete it.
4355 * (ignore deletion error)
4357 if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4358 hammer2_chain_delete(parent, chain,
4359 chain->bref.modify_tid,
4360 HAMMER2_DELETE_PERMANENT);
4361 hammer2_chain_repchange(parent, chain);
4365 base = hammer2_chain_base_and_count(parent, &count);
4367 if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4368 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4369 hammer2_chain_countbrefs(parent, base, count);
4373 * Determine if we can collapse chain into parent, calculate
4374 * hysteresis for chain emptiness.
4376 if (parent->core.live_count + chain->core.live_count - 1 > count)
4378 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4379 if (chain->core.live_count > chain_count * 3 / 4)
4383 * Ok, theoretically we can collapse chain's contents into
4384 * parent. chain is locked, but any in-memory children of chain
4385 * are not. For this to work, we must be able to dispose of any
4386 * in-memory children of chain.
4388 * For now require that there are no in-memory children of chain.
4390 * WARNING! Both chain and parent must remain locked across this
4395 * Parent must be marked modified. Don't try to collapse it if we
4396 * can't mark it modified. Once modified, destroy chain to make room
4397 * and to get rid of what will be a conflicting key (this is included
4398 * in the calculation above). Finally, move the children of chain
4399 * into chain's parent.
4401 * This order creates an accounting problem for bref.embed.stats
4402 * because we destroy chain before we remove its children. Any
4403 * elements whos blockref is already synchronized will be counted
4404 * twice. To deal with the problem we clean out chain's stats prior
4407 error = hammer2_chain_modify(parent, 0, 0, 0);
4409 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4410 hammer2_error_str(error));
4413 error = hammer2_chain_modify(chain, chain->bref.modify_tid, 0, 0);
4415 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4416 hammer2_error_str(error));
4420 chain->bref.embed.stats.inode_count = 0;
4421 chain->bref.embed.stats.data_count = 0;
4422 error = hammer2_chain_delete(parent, chain,
4423 chain->bref.modify_tid,
4424 HAMMER2_DELETE_PERMANENT);
4425 KKASSERT(error == 0);
4428 * The combined_find call requires core.spin to be held. One would
4429 * think there wouldn't be any conflicts since we hold chain
4430 * exclusively locked, but the caching mechanism for 0-ref children
4431 * does not require a chain lock.
4433 hammer2_spin_ex(&chain->core.spin);
4437 key_end = HAMMER2_KEY_MAX;
4439 chain_base = &chain->data->npdata[0];
4440 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4441 sub = hammer2_combined_find(chain, chain_base, chain_count,
4445 generation = chain->core.generation;
4448 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4452 hammer2_chain_ref(sub);
4453 hammer2_spin_unex(&chain->core.spin);
4454 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4456 hammer2_spin_unex(&chain->core.spin);
4457 sub = hammer2_chain_get(chain, generation, &bcopy,
4458 HAMMER2_RESOLVE_NEVER);
4460 hammer2_spin_ex(&chain->core.spin);
4464 if (bcmp(&bcopy, &sub->bref, sizeof(bcopy)) ||
4465 sub->parent != chain ||
4466 (sub->flags & HAMMER2_CHAIN_DELETED)) {
4467 hammer2_chain_unlock(sub);
4468 hammer2_chain_drop(sub);
4469 hammer2_spin_ex(&chain->core.spin);
4470 sub = NULL; /* safety */
4473 error = hammer2_chain_delete_obref(chain, sub,
4474 sub->bref.modify_tid, 0,
4476 KKASSERT(error == 0);
4477 hammer2_chain_rename_obref(&parent, sub,
4478 sub->bref.modify_tid,
4479 HAMMER2_INSERT_SAMEPARENT, &bcopy);
4480 hammer2_chain_unlock(sub);
4481 hammer2_chain_drop(sub);
4482 hammer2_spin_ex(&chain->core.spin);
4488 hammer2_spin_unex(&chain->core.spin);
4490 hammer2_chain_repchange(parent, chain);
4496 * Freemap indirect blocks
4498 * Calculate the keybits and highside/lowside of the freemap node the
4499 * caller is creating.
4501 * This routine will specify the next higher-level freemap key/radix
4502 * representing the lowest-ordered set. By doing so, eventually all
4503 * low-ordered sets will be moved one level down.
4505 * We have to be careful here because the freemap reserves a limited
4506 * number of blocks for a limited number of levels. So we can't just
4507 * push indiscriminately.
4510 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4511 int keybits, hammer2_blockref_t *base, int count)
4513 hammer2_chain_t *chain;
4514 hammer2_blockref_t *bref;
4516 hammer2_key_t key_beg;
4517 hammer2_key_t key_end;
4518 hammer2_key_t key_next;
4521 int maxloops = 300000;
4529 * Calculate the range of keys in the array being careful to skip
4530 * slots which are overridden with a deletion.
4533 key_end = HAMMER2_KEY_MAX;
4534 hammer2_spin_ex(&parent->core.spin);
4537 if (--maxloops == 0) {
4538 panic("indkey_freemap shit %p %p:%d\n",
4539 parent, base, count);
4541 chain = hammer2_combined_find(parent, base, count,
4553 * Skip deleted chains.
4555 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4556 if (key_next == 0 || key_next > key_end)
4563 * Use the full live (not deleted) element for the scan
4564 * iteration. HAMMER2 does not allow partial replacements.
4566 * XXX should be built into hammer2_combined_find().
4568 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4570 if (keybits > bref->keybits) {
4572 keybits = bref->keybits;
4573 } else if (keybits == bref->keybits && bref->key < key) {
4580 hammer2_spin_unex(&parent->core.spin);
4583 * Return the keybits for a higher-level FREEMAP_NODE covering
4587 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4588 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4590 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4591 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4593 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4594 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4596 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4597 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4599 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4600 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4602 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4603 panic("hammer2_chain_indkey_freemap: level too high");
4606 panic("hammer2_chain_indkey_freemap: bad radix");
4615 * File indirect blocks
4617 * Calculate the key/keybits for the indirect block to create by scanning
4618 * existing keys. The key being created is also passed in *keyp and can be
4619 * inside or outside the indirect block. Regardless, the indirect block
4620 * must hold at least two keys in order to guarantee sufficient space.
4622 * We use a modified version of the freemap's fixed radix tree, but taylored
4623 * for file data. Basically we configure an indirect block encompassing the
4627 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4628 int keybits, hammer2_blockref_t *base, int count,
4631 hammer2_chain_t *chain;
4632 hammer2_blockref_t *bref;
4634 hammer2_key_t key_beg;
4635 hammer2_key_t key_end;
4636 hammer2_key_t key_next;
4640 int maxloops = 300000;
4648 * Calculate the range of keys in the array being careful to skip
4649 * slots which are overridden with a deletion.
4651 * Locate the smallest key.
4654 key_end = HAMMER2_KEY_MAX;
4655 hammer2_spin_ex(&parent->core.spin);
4658 if (--maxloops == 0) {
4659 panic("indkey_freemap shit %p %p:%d\n",
4660 parent, base, count);
4662 chain = hammer2_combined_find(parent, base, count,
4674 * Skip deleted chains.
4676 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4677 if (key_next == 0 || key_next > key_end)
4684 * Use the full live (not deleted) element for the scan
4685 * iteration. HAMMER2 does not allow partial replacements.
4687 * XXX should be built into hammer2_combined_find().
4689 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4691 if (keybits > bref->keybits) {
4693 keybits = bref->keybits;
4694 } else if (keybits == bref->keybits && bref->key < key) {
4701 hammer2_spin_unex(&parent->core.spin);
4704 * Calculate the static keybits for a higher-level indirect block
4705 * that contains the key.
4710 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4711 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4713 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4714 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4716 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4717 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4720 panic("bad ncount %d\n", ncount);
4726 * The largest radix that can be returned for an indirect block is
4727 * 63 bits. (The largest practical indirect block radix is actually
4728 * 62 bits because the top-level inode or volume root contains four
4729 * entries, but allow 63 to be returned).
4734 return keybits + nradix;
4740 * Directory indirect blocks.
4742 * Covers both the inode index (directory of inodes), and directory contents
4743 * (filenames hardlinked to inodes).
4745 * Because directory keys are hashed we generally try to cut the space in
4746 * half. We accomodate the inode index (which tends to have linearly
4747 * increasing inode numbers) by ensuring that the keyspace is at least large
4748 * enough to fill up the indirect block being created.
4751 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4752 int keybits, hammer2_blockref_t *base, int count,
4755 hammer2_blockref_t *bref;
4756 hammer2_chain_t *chain;
4757 hammer2_key_t key_beg;
4758 hammer2_key_t key_end;
4759 hammer2_key_t key_next;
4764 int maxloops = 300000;
4767 * NOTE: We can't take a shortcut here anymore for inodes because
4768 * the root directory can contain a mix of inodes and directory
4769 * entries (we used to just return 63 if parent->bref.type was
4770 * HAMMER2_BREF_TYPE_INODE.
4777 * Calculate the range of keys in the array being careful to skip
4778 * slots which are overridden with a deletion.
4781 key_end = HAMMER2_KEY_MAX;
4782 hammer2_spin_ex(&parent->core.spin);
4785 if (--maxloops == 0) {
4786 panic("indkey_freemap shit %p %p:%d\n",
4787 parent, base, count);
4789 chain = hammer2_combined_find(parent, base, count,
4803 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4804 if (key_next == 0 || key_next > key_end)
4811 * Use the full live (not deleted) element for the scan
4812 * iteration. HAMMER2 does not allow partial replacements.
4814 * XXX should be built into hammer2_combined_find().
4816 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4819 * Expand our calculated key range (key, keybits) to fit
4820 * the scanned key. nkeybits represents the full range
4821 * that we will later cut in half (two halves @ nkeybits - 1).
4824 if (nkeybits < bref->keybits) {
4825 if (bref->keybits > 64) {
4826 kprintf("bad bref chain %p bref %p\n",
4830 nkeybits = bref->keybits;
4832 while (nkeybits < 64 &&
4833 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4834 (key ^ bref->key)) != 0) {
4839 * If the new key range is larger we have to determine
4840 * which side of the new key range the existing keys fall
4841 * under by checking the high bit, then collapsing the
4842 * locount into the hicount or vise-versa.
4844 if (keybits != nkeybits) {
4845 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4856 * The newly scanned key will be in the lower half or the
4857 * upper half of the (new) key range.
4859 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4868 hammer2_spin_unex(&parent->core.spin);
4869 bref = NULL; /* now invalid (safety) */
4872 * Adjust keybits to represent half of the full range calculated
4873 * above (radix 63 max) for our new indirect block.
4878 * Expand keybits to hold at least ncount elements. ncount will be
4879 * a power of 2. This is to try to completely fill leaf nodes (at
4880 * least for keys which are not hashes).
4882 * We aren't counting 'in' or 'out', we are counting 'high side'
4883 * and 'low side' based on the bit at (1LL << keybits). We want
4884 * everything to be inside in these cases so shift it all to
4885 * the low or high side depending on the new high bit.
4887 while (((hammer2_key_t)1 << keybits) < ncount) {
4889 if (key & ((hammer2_key_t)1 << keybits)) {
4898 if (hicount > locount)
4899 key |= (hammer2_key_t)1 << keybits;
4901 key &= ~(hammer2_key_t)1 << keybits;
4911 * Directory indirect blocks.
4913 * Covers both the inode index (directory of inodes), and directory contents
4914 * (filenames hardlinked to inodes).
4916 * Because directory keys are hashed we generally try to cut the space in
4917 * half. We accomodate the inode index (which tends to have linearly
4918 * increasing inode numbers) by ensuring that the keyspace is at least large
4919 * enough to fill up the indirect block being created.
4922 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4923 int keybits, hammer2_blockref_t *base, int count,
4926 hammer2_blockref_t *bref;
4927 hammer2_chain_t *chain;
4928 hammer2_key_t key_beg;
4929 hammer2_key_t key_end;
4930 hammer2_key_t key_next;
4935 int maxloops = 300000;
4938 * Shortcut if the parent is the inode. In this situation the
4939 * parent has 4+1 directory entries and we are creating an indirect
4940 * block capable of holding many more.
4942 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4951 * Calculate the range of keys in the array being careful to skip
4952 * slots which are overridden with a deletion.
4955 key_end = HAMMER2_KEY_MAX;
4956 hammer2_spin_ex(&parent->core.spin);
4959 if (--maxloops == 0) {
4960 panic("indkey_freemap shit %p %p:%d\n",
4961 parent, base, count);
4963 chain = hammer2_combined_find(parent, base, count,
4977 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4978 if (key_next == 0 || key_next > key_end)
4985 * Use the full live (not deleted) element for the scan
4986 * iteration. HAMMER2 does not allow partial replacements.
4988 * XXX should be built into hammer2_combined_find().
4990 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4993 * Expand our calculated key range (key, keybits) to fit
4994 * the scanned key. nkeybits represents the full range
4995 * that we will later cut in half (two halves @ nkeybits - 1).
4998 if (nkeybits < bref->keybits) {
4999 if (bref->keybits > 64) {
5000 kprintf("bad bref chain %p bref %p\n",
5004 nkeybits = bref->keybits;
5006 while (nkeybits < 64 &&
5007 (~(((hammer2_key_t)1 << nkeybits) - 1) &
5008 (key ^ bref->key)) != 0) {
5013 * If the new key range is larger we have to determine
5014 * which side of the new key range the existing keys fall
5015 * under by checking the high bit, then collapsing the
5016 * locount into the hicount or vise-versa.
5018 if (keybits != nkeybits) {
5019 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
5030 * The newly scanned key will be in the lower half or the
5031 * upper half of the (new) key range.
5033 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
5042 hammer2_spin_unex(&parent->core.spin);
5043 bref = NULL; /* now invalid (safety) */
5046 * Adjust keybits to represent half of the full range calculated
5047 * above (radix 63 max) for our new indirect block.
5052 * Expand keybits to hold at least ncount elements. ncount will be
5053 * a power of 2. This is to try to completely fill leaf nodes (at
5054 * least for keys which are not hashes).
5056 * We aren't counting 'in' or 'out', we are counting 'high side'
5057 * and 'low side' based on the bit at (1LL << keybits). We want
5058 * everything to be inside in these cases so shift it all to
5059 * the low or high side depending on the new high bit.
5061 while (((hammer2_key_t)1 << keybits) < ncount) {
5063 if (key & ((hammer2_key_t)1 << keybits)) {
5072 if (hicount > locount)
5073 key |= (hammer2_key_t)1 << keybits;
5075 key &= ~(hammer2_key_t)1 << keybits;
5085 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
5088 * Both parent and chain must be locked exclusively.
5090 * This function will modify the parent if the blockref requires removal
5091 * from the parent's block table.
5093 * This function is NOT recursive. Any entity already pushed into the
5094 * chain (such as an inode) may still need visibility into its contents,
5095 * as well as the ability to read and modify the contents. For example,
5096 * for an unlinked file which is still open.
5098 * Also note that the flusher is responsible for cleaning up empty
5102 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
5103 hammer2_tid_t mtid, int flags)
5107 KKASSERT(hammer2_mtx_owned(&chain->lock));
5110 * Nothing to do if already marked.
5112 * We need the spinlock on the core whos RBTREE contains chain
5113 * to protect against races.
5115 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5116 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5117 chain->parent == parent);
5118 error = _hammer2_chain_delete_helper(parent, chain,
5123 * Permanent deletions mark the chain as destroyed.
5125 * NOTE: We do not setflush the chain unless the deletion is
5126 * permanent, since the deletion of a chain does not actually
5127 * require it to be flushed.
5130 if (flags & HAMMER2_DELETE_PERMANENT) {
5131 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5132 hammer2_chain_setflush(chain);
5140 hammer2_chain_delete_obref(hammer2_chain_t *parent, hammer2_chain_t *chain,
5141 hammer2_tid_t mtid, int flags,
5142 hammer2_blockref_t *obref)
5146 KKASSERT(hammer2_mtx_owned(&chain->lock));
5149 * Nothing to do if already marked.
5151 * We need the spinlock on the core whos RBTREE contains chain
5152 * to protect against races.
5154 obref->type = HAMMER2_BREF_TYPE_EMPTY;
5155 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5156 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5157 chain->parent == parent);
5158 error = _hammer2_chain_delete_helper(parent, chain,
5159 mtid, flags, obref);
5163 * Permanent deletions mark the chain as destroyed.
5165 * NOTE: We do not setflush the chain unless the deletion is
5166 * permanent, since the deletion of a chain does not actually
5167 * require it to be flushed.
5170 if (flags & HAMMER2_DELETE_PERMANENT) {
5171 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5172 hammer2_chain_setflush(chain);
5180 * Returns the index of the nearest element in the blockref array >= elm.
5181 * Returns (count) if no element could be found.
5183 * Sets *key_nextp to the next key for loop purposes but does not modify
5184 * it if the next key would be higher than the current value of *key_nextp.
5185 * Note that *key_nexp can overflow to 0, which should be tested by the
5188 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5189 * held through the operation.
5192 hammer2_base_find(hammer2_chain_t *parent,
5193 hammer2_blockref_t *base, int count,
5194 hammer2_key_t *key_nextp,
5195 hammer2_key_t key_beg, hammer2_key_t key_end)
5197 hammer2_blockref_t *scan;
5198 hammer2_key_t scan_end;
5203 * Require the live chain's already have their core's counted
5204 * so we can optimize operations.
5206 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
5211 if (count == 0 || base == NULL)
5215 * Sequential optimization using parent->cache_index. This is
5216 * the most likely scenario.
5218 * We can avoid trailing empty entries on live chains, otherwise
5219 * we might have to check the whole block array.
5221 i = parent->cache_index; /* SMP RACE OK */
5223 limit = parent->core.live_zero;
5228 KKASSERT(i < count);
5234 while (i > 0 && (scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5235 scan->key > key_beg)) {
5239 parent->cache_index = i;
5242 * Search forwards, stop when we find a scan element which
5243 * encloses the key or until we know that there are no further
5247 if (scan->type != HAMMER2_BREF_TYPE_EMPTY) {
5248 scan_end = scan->key +
5249 ((hammer2_key_t)1 << scan->keybits) - 1;
5250 if (scan->key > key_beg || scan_end >= key_beg)
5259 parent->cache_index = i;
5263 scan_end = scan->key +
5264 ((hammer2_key_t)1 << scan->keybits);
5265 if (scan_end && (*key_nextp > scan_end ||
5267 *key_nextp = scan_end;
5275 * Do a combined search and return the next match either from the blockref
5276 * array or from the in-memory chain. Sets *bresp to the returned bref in
5277 * both cases, or sets it to NULL if the search exhausted. Only returns
5278 * a non-NULL chain if the search matched from the in-memory chain.
5280 * When no in-memory chain has been found and a non-NULL bref is returned
5284 * The returned chain is not locked or referenced. Use the returned bref
5285 * to determine if the search exhausted or not. Iterate if the base find
5286 * is chosen but matches a deleted chain.
5288 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5289 * held through the operation.
5292 hammer2_combined_find(hammer2_chain_t *parent,
5293 hammer2_blockref_t *base, int count,
5294 hammer2_key_t *key_nextp,
5295 hammer2_key_t key_beg, hammer2_key_t key_end,
5296 hammer2_blockref_t **bresp)
5298 hammer2_blockref_t *bref;
5299 hammer2_chain_t *chain;
5303 * Lookup in block array and in rbtree.
5305 *key_nextp = key_end + 1;
5306 i = hammer2_base_find(parent, base, count, key_nextp,
5308 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
5313 if (i == count && chain == NULL) {
5319 * Only chain matched.
5322 bref = &chain->bref;
5327 * Only blockref matched.
5329 if (chain == NULL) {
5335 * Both in-memory and blockref matched, select the nearer element.
5337 * If both are flush with the left-hand side or both are the
5338 * same distance away, select the chain. In this situation the
5339 * chain must have been loaded from the matching blockmap.
5341 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
5342 chain->bref.key == base[i].key) {
5343 KKASSERT(chain->bref.key == base[i].key);
5344 bref = &chain->bref;
5349 * Select the nearer key
5351 if (chain->bref.key < base[i].key) {
5352 bref = &chain->bref;
5359 * If the bref is out of bounds we've exhausted our search.
5362 if (bref->key > key_end) {
5372 * Locate the specified block array element and delete it. The element
5375 * The spin lock on the related chain must be held.
5377 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5378 * need to be adjusted when we commit the media change.
5381 hammer2_base_delete(hammer2_chain_t *parent,
5382 hammer2_blockref_t *base, int count,
5383 hammer2_chain_t *chain,
5384 hammer2_blockref_t *obref)
5386 hammer2_blockref_t *elm = &chain->bref;
5387 hammer2_blockref_t *scan;
5388 hammer2_key_t key_next;
5392 * Delete element. Expect the element to exist.
5394 * XXX see caller, flush code not yet sophisticated enough to prevent
5395 * re-flushed in some cases.
5397 key_next = 0; /* max range */
5398 i = hammer2_base_find(parent, base, count, &key_next,
5399 elm->key, elm->key);
5401 if (i == count || scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5402 scan->key != elm->key ||
5403 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
5404 scan->keybits != elm->keybits)) {
5405 hammer2_spin_unex(&parent->core.spin);
5406 panic("delete base %p element not found at %d/%d elm %p\n",
5407 base, i, count, elm);
5412 * Update stats and zero the entry.
5414 * NOTE: Handle radix == 0 (0 bytes) case.
5416 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5417 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5418 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5420 switch(scan->type) {
5421 case HAMMER2_BREF_TYPE_INODE:
5422 --parent->bref.embed.stats.inode_count;
5424 case HAMMER2_BREF_TYPE_DATA:
5425 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5426 atomic_set_int(&chain->flags,
5427 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5429 if (parent->bref.leaf_count)
5430 --parent->bref.leaf_count;
5433 case HAMMER2_BREF_TYPE_INDIRECT:
5434 if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5435 parent->bref.embed.stats.data_count -=
5436 scan->embed.stats.data_count;
5437 parent->bref.embed.stats.inode_count -=
5438 scan->embed.stats.inode_count;
5440 if (scan->type == HAMMER2_BREF_TYPE_INODE)
5442 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5443 atomic_set_int(&chain->flags,
5444 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5446 if (parent->bref.leaf_count <= scan->leaf_count)
5447 parent->bref.leaf_count = 0;
5449 parent->bref.leaf_count -= scan->leaf_count;
5452 case HAMMER2_BREF_TYPE_DIRENT:
5453 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5454 atomic_set_int(&chain->flags,
5455 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5457 if (parent->bref.leaf_count)
5458 --parent->bref.leaf_count;
5466 bzero(scan, sizeof(*scan));
5469 * We can only optimize parent->core.live_zero for live chains.
5471 if (parent->core.live_zero == i + 1) {
5472 while (--i >= 0 && base[i].type == HAMMER2_BREF_TYPE_EMPTY)
5474 parent->core.live_zero = i + 1;
5478 * Clear appropriate blockmap flags in chain.
5480 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
5481 HAMMER2_CHAIN_BMAPUPD);
5485 * Insert the specified element. The block array must not already have the
5486 * element and must have space available for the insertion.
5488 * The spin lock on the related chain must be held.
5490 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5491 * need to be adjusted when we commit the media change.
5494 hammer2_base_insert(hammer2_chain_t *parent,
5495 hammer2_blockref_t *base, int count,
5496 hammer2_chain_t *chain, hammer2_blockref_t *elm)
5498 hammer2_key_t key_next;
5507 * Insert new element. Expect the element to not already exist
5508 * unless we are replacing it.
5510 * XXX see caller, flush code not yet sophisticated enough to prevent
5511 * re-flushed in some cases.
5513 key_next = 0; /* max range */
5514 i = hammer2_base_find(parent, base, count, &key_next,
5515 elm->key, elm->key);
5518 * Shortcut fill optimization, typical ordered insertion(s) may not
5521 KKASSERT(i >= 0 && i <= count);
5524 * Set appropriate blockmap flags in chain (if not NULL)
5527 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
5530 * Update stats and zero the entry
5532 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5533 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5534 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5537 case HAMMER2_BREF_TYPE_INODE:
5538 ++parent->bref.embed.stats.inode_count;
5540 case HAMMER2_BREF_TYPE_DATA:
5541 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5542 ++parent->bref.leaf_count;
5544 case HAMMER2_BREF_TYPE_INDIRECT:
5545 if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5546 parent->bref.embed.stats.data_count +=
5547 elm->embed.stats.data_count;
5548 parent->bref.embed.stats.inode_count +=
5549 elm->embed.stats.inode_count;
5551 if (elm->type == HAMMER2_BREF_TYPE_INODE)
5553 if (parent->bref.leaf_count + elm->leaf_count <
5554 HAMMER2_BLOCKREF_LEAF_MAX) {
5555 parent->bref.leaf_count += elm->leaf_count;
5557 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5560 case HAMMER2_BREF_TYPE_DIRENT:
5561 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5562 ++parent->bref.leaf_count;
5570 * We can only optimize parent->core.live_zero for live chains.
5572 if (i == count && parent->core.live_zero < count) {
5573 i = parent->core.live_zero++;
5578 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5579 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5580 hammer2_spin_unex(&parent->core.spin);
5581 panic("insert base %p overlapping elements at %d elm %p\n",
5586 * Try to find an empty slot before or after.
5590 while (j > 0 || k < count) {
5592 if (j >= 0 && base[j].type == HAMMER2_BREF_TYPE_EMPTY) {
5596 bcopy(&base[j+1], &base[j],
5597 (i - j - 1) * sizeof(*base));
5603 if (k < count && base[k].type == HAMMER2_BREF_TYPE_EMPTY) {
5604 bcopy(&base[i], &base[i+1],
5605 (k - i) * sizeof(hammer2_blockref_t));
5609 * We can only update parent->core.live_zero for live
5612 if (parent->core.live_zero <= k)
5613 parent->core.live_zero = k + 1;
5618 panic("hammer2_base_insert: no room!");
5625 for (l = 0; l < count; ++l) {
5627 key_next = base[l].key +
5628 ((hammer2_key_t)1 << base[l].keybits) - 1;
5632 while (++l < count) {
5634 if (base[l].key <= key_next)
5635 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5636 key_next = base[l].key +
5637 ((hammer2_key_t)1 << base[l].keybits) - 1;
5647 * Sort the blockref array for the chain. Used by the flush code to
5648 * sort the blockref[] array.
5650 * The chain must be exclusively locked AND spin-locked.
5652 typedef hammer2_blockref_t *hammer2_blockref_p;
5656 hammer2_base_sort_callback(const void *v1, const void *v2)
5658 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5659 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5662 * Make sure empty elements are placed at the end of the array
5664 if (bref1->type == HAMMER2_BREF_TYPE_EMPTY) {
5665 if (bref2->type == HAMMER2_BREF_TYPE_EMPTY)
5668 } else if (bref2->type == HAMMER2_BREF_TYPE_EMPTY) {
5675 if (bref1->key < bref2->key)
5677 if (bref1->key > bref2->key)
5683 hammer2_base_sort(hammer2_chain_t *chain)
5685 hammer2_blockref_t *base;
5688 switch(chain->bref.type) {
5689 case HAMMER2_BREF_TYPE_INODE:
5691 * Special shortcut for embedded data returns the inode
5692 * itself. Callers must detect this condition and access
5693 * the embedded data (the strategy code does this for us).
5695 * This is only applicable to regular files and softlinks.
5697 if (chain->data->ipdata.meta.op_flags &
5698 HAMMER2_OPFLAG_DIRECTDATA) {
5701 base = &chain->data->ipdata.u.blockset.blockref[0];
5702 count = HAMMER2_SET_COUNT;
5704 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5705 case HAMMER2_BREF_TYPE_INDIRECT:
5707 * Optimize indirect blocks in the INITIAL state to avoid
5710 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5711 base = &chain->data->npdata[0];
5712 count = chain->bytes / sizeof(hammer2_blockref_t);
5714 case HAMMER2_BREF_TYPE_VOLUME:
5715 base = &chain->data->voldata.sroot_blockset.blockref[0];
5716 count = HAMMER2_SET_COUNT;
5718 case HAMMER2_BREF_TYPE_FREEMAP:
5719 base = &chain->data->blkset.blockref[0];
5720 count = HAMMER2_SET_COUNT;
5723 kprintf("hammer2_chain_lookup: unrecognized "
5724 "blockref(A) type: %d",
5727 tsleep(&base, 0, "dead", 0);
5728 panic("hammer2_base_sort: unrecognized "
5729 "blockref(A) type: %d",
5731 base = NULL; /* safety */
5732 count = 0; /* safety */
5734 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5740 * Chain memory management
5743 hammer2_chain_wait(hammer2_chain_t *chain)
5745 tsleep(chain, 0, "chnflw", 1);
5748 const hammer2_media_data_t *
5749 hammer2_chain_rdata(hammer2_chain_t *chain)
5751 KKASSERT(chain->data != NULL);
5752 return (chain->data);
5755 hammer2_media_data_t *
5756 hammer2_chain_wdata(hammer2_chain_t *chain)
5758 KKASSERT(chain->data != NULL);
5759 return (chain->data);
5763 * Set the check data for a chain. This can be a heavy-weight operation
5764 * and typically only runs on-flush. For file data check data is calculated
5765 * when the logical buffers are flushed.
5768 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5770 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5772 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5773 case HAMMER2_CHECK_NONE:
5775 case HAMMER2_CHECK_DISABLED:
5777 case HAMMER2_CHECK_ISCSI32:
5778 chain->bref.check.iscsi32.value =
5779 hammer2_icrc32(bdata, chain->bytes);
5781 case HAMMER2_CHECK_XXHASH64:
5782 chain->bref.check.xxhash64.value =
5783 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5785 case HAMMER2_CHECK_SHA192:
5787 SHA256_CTX hash_ctx;
5789 uint8_t digest[SHA256_DIGEST_LENGTH];
5790 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5793 SHA256_Init(&hash_ctx);
5794 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5795 SHA256_Final(u.digest, &hash_ctx);
5796 u.digest64[2] ^= u.digest64[3];
5798 chain->bref.check.sha192.data,
5799 sizeof(chain->bref.check.sha192.data));
5802 case HAMMER2_CHECK_FREEMAP:
5803 chain->bref.check.freemap.icrc32 =
5804 hammer2_icrc32(bdata, chain->bytes);
5807 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5808 chain->bref.methods);
5814 * Characterize a failed check code and try to trace back to the inode.
5817 hammer2_characterize_failed_chain(hammer2_chain_t *chain, uint64_t check,
5820 hammer2_chain_t *lchain;
5821 hammer2_chain_t *ochain;
5823 kprintf("chain %016jx.%02x (%s) meth=%02x CHECK FAIL "
5824 "(flags=%08x, bref/data ",
5825 chain->bref.data_off,
5827 hammer2_bref_type_str(&chain->bref),
5828 chain->bref.methods,
5831 kprintf("%08x/%08x)\n",
5832 chain->bref.check.iscsi32.value,
5835 kprintf("%016jx/%016jx)\n",
5836 chain->bref.check.xxhash64.value,
5841 * Run up the chains to try to find the governing inode so we
5844 * XXX This error reporting is not really MPSAFE
5848 while (chain && chain->bref.type != HAMMER2_BREF_TYPE_INODE) {
5850 chain = chain->parent;
5853 if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
5854 ((chain->bref.flags & HAMMER2_BREF_FLAG_PFSROOT) == 0 ||
5855 (lchain->bref.key & HAMMER2_DIRHASH_VISIBLE))) {
5856 kprintf(" Resides at/in inode %ld\n",
5858 } else if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5859 kprintf(" Resides in inode index - CRITICAL!!!\n");
5861 kprintf(" Resides in root index - CRITICAL!!!\n");
5864 const char *pfsname = "UNKNOWN";
5868 for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
5869 if (ochain->pmp->pfs_hmps[i] == ochain->hmp &&
5870 ochain->pmp->pfs_names[i]) {
5871 pfsname = ochain->pmp->pfs_names[i];
5876 kprintf(" In pfs %s on device %s\n",
5877 pfsname, ochain->hmp->devrepname);
5882 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5888 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5891 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5892 case HAMMER2_CHECK_NONE:
5895 case HAMMER2_CHECK_DISABLED:
5898 case HAMMER2_CHECK_ISCSI32:
5899 check32 = hammer2_icrc32(bdata, chain->bytes);
5900 r = (chain->bref.check.iscsi32.value == check32);
5902 hammer2_characterize_failed_chain(chain, check32, 32);
5904 hammer2_process_icrc32 += chain->bytes;
5906 case HAMMER2_CHECK_XXHASH64:
5907 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5908 r = (chain->bref.check.xxhash64.value == check64);
5910 hammer2_characterize_failed_chain(chain, check64, 64);
5912 hammer2_process_xxhash64 += chain->bytes;
5914 case HAMMER2_CHECK_SHA192:
5916 SHA256_CTX hash_ctx;
5918 uint8_t digest[SHA256_DIGEST_LENGTH];
5919 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5922 SHA256_Init(&hash_ctx);
5923 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5924 SHA256_Final(u.digest, &hash_ctx);
5925 u.digest64[2] ^= u.digest64[3];
5927 chain->bref.check.sha192.data,
5928 sizeof(chain->bref.check.sha192.data)) == 0) {
5932 kprintf("chain %016jx.%02x meth=%02x "
5934 chain->bref.data_off,
5936 chain->bref.methods);
5940 case HAMMER2_CHECK_FREEMAP:
5941 r = (chain->bref.check.freemap.icrc32 ==
5942 hammer2_icrc32(bdata, chain->bytes));
5944 kprintf("chain %016jx.%02x meth=%02x "
5946 chain->bref.data_off,
5948 chain->bref.methods);
5949 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5950 chain->bref.check.freemap.icrc32,
5951 hammer2_icrc32(bdata, chain->bytes),
5954 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5955 chain->dio, chain->dio->bp->b_loffset,
5956 chain->dio->bp->b_bufsize, bdata,
5957 chain->dio->bp->b_data);
5962 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5963 chain->bref.methods);
5971 * Acquire the chain and parent representing the specified inode for the
5972 * device at the specified cluster index.
5974 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5976 * If we are unable to locate the inode, HAMMER2_ERROR_EIO is returned and
5977 * *chainp will be NULL. *parentp may still be set error or not, or NULL
5978 * if the parent itself could not be resolved.
5980 * The caller may pass-in a locked *parentp and/or *chainp, or neither.
5981 * They will be unlocked and released by this function. The *parentp and
5982 * *chainp representing the located inode are returned locked.
5985 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5986 int clindex, int flags,
5987 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5989 hammer2_chain_t *parent;
5990 hammer2_chain_t *rchain;
5991 hammer2_key_t key_dummy;
5992 hammer2_inode_t *ip;
5996 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5997 HAMMER2_RESOLVE_SHARED : 0;
6000 * Caller expects us to replace these.
6003 hammer2_chain_unlock(*chainp);
6004 hammer2_chain_drop(*chainp);
6008 hammer2_chain_unlock(*parentp);
6009 hammer2_chain_drop(*parentp);
6014 * Be very careful, this is a backend function and we CANNOT
6015 * lock any frontend inode structure we find. But we have to
6016 * look the inode up this way first in case it exists but is
6017 * detached from the radix tree.
6019 ip = hammer2_inode_lookup(pmp, inum);
6021 *chainp = hammer2_inode_chain_and_parent(ip, clindex,
6024 hammer2_inode_drop(ip);
6027 hammer2_chain_unlock(*chainp);
6028 hammer2_chain_drop(*chainp);
6031 hammer2_chain_unlock(*parentp);
6032 hammer2_chain_drop(*parentp);
6038 * Inodes hang off of the iroot (bit 63 is clear, differentiating
6039 * inodes from root directory entries in the key lookup).
6041 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
6044 rchain = hammer2_chain_lookup(&parent, &key_dummy,
6048 error = HAMMER2_ERROR_EIO;
6057 * Used by the bulkscan code to snapshot the synchronized storage for
6058 * a volume, allowing it to be scanned concurrently against normal
6062 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
6064 hammer2_chain_t *copy;
6066 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
6067 copy->data = kmalloc(sizeof(copy->data->voldata),
6070 hammer2_voldata_lock(hmp);
6071 copy->data->voldata = hmp->volsync;
6072 hammer2_voldata_unlock(hmp);
6078 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
6080 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
6081 KKASSERT(copy->data);
6082 kfree(copy->data, copy->hmp->mchain);
6084 atomic_add_long(&hammer2_chain_allocs, -1);
6085 hammer2_chain_drop(copy);
6089 * Returns non-zero if the chain (INODE or DIRENT) matches the
6093 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
6096 const hammer2_inode_data_t *ripdata;
6097 const hammer2_dirent_head_t *den;
6099 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
6100 ripdata = &chain->data->ipdata;
6101 if (ripdata->meta.name_len == name_len &&
6102 bcmp(ripdata->filename, name, name_len) == 0) {
6106 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
6107 chain->bref.embed.dirent.namlen == name_len) {
6108 den = &chain->bref.embed.dirent;
6109 if (name_len > sizeof(chain->bref.check.buf) &&
6110 bcmp(chain->data->buf, name, name_len) == 0) {
6113 if (name_len <= sizeof(chain->bref.check.buf) &&
6114 bcmp(chain->bref.check.buf, name, name_len) == 0) {