2 * Copyright (c) 2011-2015 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 hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain);
72 static hammer2_chain_t *hammer2_combined_find(
73 hammer2_chain_t *parent,
74 hammer2_blockref_t *base, int count,
75 hammer2_key_t *key_nextp,
76 hammer2_key_t key_beg, hammer2_key_t key_end,
77 hammer2_blockref_t **bresp);
80 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
81 * overlap in the RB trees. Deleted chains are moved from rbtree to either
84 * Chains in delete-duplicate sequences can always iterate through core_entry
85 * to locate the live version of the chain.
87 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
90 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
98 * Compare chains. Overlaps are not supposed to happen and catch
99 * any software issues early we count overlaps as a match.
101 c1_beg = chain1->bref.key;
102 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
103 c2_beg = chain2->bref.key;
104 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
106 if (c1_end < c2_beg) /* fully to the left */
108 if (c1_beg > c2_end) /* fully to the right */
110 return(0); /* overlap (must not cross edge boundary) */
114 * Assert that a chain has no media data associated with it.
117 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
119 KKASSERT(chain->dio == NULL);
120 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
121 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
123 panic("hammer2_assert_no_data: chain %p still has data", chain);
128 * Make a chain visible to the flusher. The flusher needs to be able to
129 * do flushes of subdirectory chains or single files so it does a top-down
130 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
131 * or UPDATE chains and flushes back up the chain to the volume root.
133 * This routine sets ONFLUSH upward until it hits the volume root. For
134 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
135 * Extra ONFLUSH flagging doesn't hurt the filesystem.
138 hammer2_chain_setflush(hammer2_chain_t *chain)
140 hammer2_chain_t *parent;
142 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
143 hammer2_spin_sh(&chain->core.spin);
144 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
146 if ((parent = chain->parent) == NULL)
148 hammer2_spin_sh(&parent->core.spin);
149 hammer2_spin_unsh(&chain->core.spin);
152 hammer2_spin_unsh(&chain->core.spin);
157 * Allocate a new disconnected chain element representing the specified
158 * bref. chain->refs is set to 1 and the passed bref is copied to
159 * chain->bref. chain->bytes is derived from the bref.
161 * chain->pmp inherits pmp unless the chain is an inode (other than the
164 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
167 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
168 hammer2_blockref_t *bref)
170 hammer2_chain_t *chain;
174 * Special case - radix of 0 indicates a chain that does not
175 * need a data reference (context is completely embedded in the
178 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
179 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
183 atomic_add_long(&hammer2_chain_allocs, 1);
186 * Construct the appropriate system structure.
189 case HAMMER2_BREF_TYPE_DIRENT:
190 case HAMMER2_BREF_TYPE_INODE:
191 case HAMMER2_BREF_TYPE_INDIRECT:
192 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
193 case HAMMER2_BREF_TYPE_DATA:
194 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
196 * Chain's are really only associated with the hmp but we
197 * maintain a pmp association for per-mount memory tracking
198 * purposes. The pmp can be NULL.
200 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
202 case HAMMER2_BREF_TYPE_VOLUME:
203 case HAMMER2_BREF_TYPE_FREEMAP:
205 * Only hammer2_chain_bulksnap() calls this function with these
208 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
212 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
217 * Initialize the new chain structure. pmp must be set to NULL for
218 * chains belonging to the super-root topology of a device mount.
220 if (pmp == hmp->spmp)
226 chain->bytes = bytes;
228 chain->flags = HAMMER2_CHAIN_ALLOCATED;
231 * Set the PFS boundary flag if this chain represents a PFS root.
233 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
234 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
235 hammer2_chain_core_init(chain);
241 * Initialize a chain's core structure. This structure used to be allocated
242 * but is now embedded.
244 * The core is not locked. No additional refs on the chain are made.
245 * (trans) must not be NULL if (core) is not NULL.
248 hammer2_chain_core_init(hammer2_chain_t *chain)
251 * Fresh core under nchain (no multi-homing of ochain's
254 RB_INIT(&chain->core.rbtree); /* live chains */
255 hammer2_mtx_init(&chain->lock, "h2chain");
259 * Add a reference to a chain element, preventing its destruction.
261 * (can be called with spinlock held)
264 hammer2_chain_ref(hammer2_chain_t *chain)
266 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
268 * 0->non-zero transition must ensure that chain is removed
271 * NOTE: Already holding lru_spin here so we cannot call
272 * hammer2_chain_ref() to get it off lru_list, do
275 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
276 hammer2_pfs_t *pmp = chain->pmp;
277 hammer2_spin_ex(&pmp->lru_spin);
278 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
279 atomic_add_int(&pmp->lru_count, -1);
280 atomic_clear_int(&chain->flags,
281 HAMMER2_CHAIN_ONLRU);
282 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
284 hammer2_spin_unex(&pmp->lru_spin);
288 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
294 * Ref a locked chain and force the data to be held across an unlock.
295 * Chain must be currently locked. The user of the chain who desires
296 * to release the hold must call hammer2_chain_lock_unhold() to relock
297 * and unhold the chain, then unlock normally, or may simply call
298 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
301 hammer2_chain_ref_hold(hammer2_chain_t *chain)
303 atomic_add_int(&chain->lockcnt, 1);
304 hammer2_chain_ref(chain);
308 * Insert the chain in the core rbtree.
310 * Normal insertions are placed in the live rbtree. Insertion of a deleted
311 * chain is a special case used by the flush code that is placed on the
312 * unstaged deleted list to avoid confusing the live view.
314 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
315 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
316 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
320 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
321 int flags, int generation)
323 hammer2_chain_t *xchain;
326 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
327 hammer2_spin_ex(&parent->core.spin);
330 * Interlocked by spinlock, check for race
332 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
333 parent->core.generation != generation) {
334 error = HAMMER2_ERROR_EAGAIN;
341 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
342 KASSERT(xchain == NULL,
343 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
344 chain, xchain, chain->bref.key));
345 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
346 chain->parent = parent;
347 ++parent->core.chain_count;
348 ++parent->core.generation; /* XXX incs for _get() too, XXX */
351 * We have to keep track of the effective live-view blockref count
352 * so the create code knows when to push an indirect block.
354 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
355 atomic_add_int(&parent->core.live_count, 1);
357 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
358 hammer2_spin_unex(&parent->core.spin);
363 * Drop the caller's reference to the chain. When the ref count drops to
364 * zero this function will try to disassociate the chain from its parent and
365 * deallocate it, then recursely drop the parent using the implied ref
366 * from the chain's chain->parent.
368 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
369 * races an acquisition by another cpu. Therefore we can loop if we are
370 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
371 * race against another drop.
373 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
376 hammer2_chain_drop(hammer2_chain_t *chain)
380 if (hammer2_debug & 0x200000)
383 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
387 KKASSERT(chain->refs > 0);
395 if (mtx_lock_ex_try(&chain->lock) == 0)
396 chain = hammer2_chain_lastdrop(chain);
397 /* retry the same chain */
399 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
401 /* retry the same chain */
408 * Unhold a held and probably not-locked chain, ensure that the data is
409 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
410 * lock and then simply unlocking the chain.
413 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
419 lockcnt = chain->lockcnt;
422 if (atomic_cmpset_int(&chain->lockcnt,
423 lockcnt, lockcnt - 1)) {
426 } else if (mtx_lock_ex_try(&chain->lock) == 0) {
427 hammer2_chain_unlock(chain);
431 * This situation can easily occur on SMP due to
432 * the gap inbetween the 1->0 transition and the
433 * final unlock. We cannot safely block on the
434 * mutex because lockcnt might go above 1.
436 * XXX Sleep for one tick if it takes too long.
439 if (iter > 1000 + hz) {
440 kprintf("hammer2: h2race1 %p\n", chain);
443 tsleep(&iter, 0, "h2race1", 1);
448 hammer2_chain_drop(chain);
452 * Handles the (potential) last drop of chain->refs from 1->0. Called with
453 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
454 * possible against refs and lockcnt. We must dispose of the mutex on chain.
456 * This function returns an unlocked chain for recursive drop or NULL. It
457 * can return the same chain if it determines it has raced another ref.
461 * When two chains need to be recursively dropped we use the chain we
462 * would otherwise free to placehold the additional chain. It's a bit
463 * convoluted but we can't just recurse without potentially blowing out
466 * The chain cannot be freed if it has any children.
467 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
468 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
469 * Any dedup registration can remain intact.
471 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
475 hammer2_chain_lastdrop(hammer2_chain_t *chain)
479 hammer2_chain_t *parent;
480 hammer2_chain_t *rdrop;
487 * On last drop if there is no parent and data_off is good (at
488 * least does not represent the volume root), the modified chain
489 * is probably going to be destroyed. We have to make sure that
490 * the data area is not registered for dedup.
492 * XXX removed. In fact, we do not have to make sure that the
493 * data area is not registered for dedup. The data area
494 * can, in fact, still be used for dedup because it is
495 * still allocated in the freemap and the underlying I/O
496 * will still be flushed.
498 if (chain->parent == NULL &&
499 (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
500 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
502 hammer2_io_dedup_delete(hmp, chain->bref.type,
503 chain->bref.data_off, chain->bytes);
507 * We need chain's spinlock to interlock the sub-tree test.
508 * We already have chain's mutex, protecting chain->parent.
510 * Remember that chain->refs can be in flux.
512 hammer2_spin_ex(&chain->core.spin);
514 if ((parent = chain->parent) != NULL) {
516 * If the chain has a parent the UPDATE bit prevents scrapping
517 * as the chain is needed to properly flush the parent. Try
518 * to complete the 1->0 transition and return NULL. Retry
519 * (return chain) if we are unable to complete the 1->0
520 * transition, else return NULL (nothing more to do).
522 * If the chain has a parent the MODIFIED bit prevents
525 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
527 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
528 HAMMER2_CHAIN_MODIFIED)) {
529 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
530 hammer2_spin_unex(&chain->core.spin);
532 dio = hammer2_chain_drop_data(chain, 0);
534 hammer2_io_bqrelse(&dio);
536 hammer2_chain_assert_no_data(chain);
537 hammer2_mtx_unlock(&chain->lock);
540 hammer2_spin_unex(&chain->core.spin);
541 hammer2_mtx_unlock(&chain->lock);
545 /* spinlock still held */
548 * The chain has no parent and can be flagged for destruction.
549 * Since it has no parent, UPDATE can also be cleared.
551 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
552 if (chain->flags & HAMMER2_CHAIN_UPDATE)
553 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
556 * If the chain has children we must still flush the chain.
557 * Any dedup is already handled by the underlying DIO, so
558 * we do not have to specifically flush it here.
560 * In the case where it has children, the DESTROY flag test
561 * in the flush code will prevent unnecessary flushes of
562 * MODIFIED chains that are not flagged DEDUP so don't worry
565 if (chain->core.chain_count) {
567 * Put on flushq (should ensure refs > 1), retry
570 hammer2_spin_unex(&chain->core.spin);
571 hammer2_delayed_flush(chain);
572 hammer2_mtx_unlock(&chain->lock);
574 return(chain); /* retry drop */
578 * Otherwise we can scrap the MODIFIED bit if it is set,
579 * and continue along the freeing path.
581 * Be sure to clean-out any dedup bits. Without a parent
582 * this chain will no longer be visible to the flush code.
583 * Easy check data_off to avoid the volume root.
585 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
586 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
587 atomic_add_long(&hammer2_count_modified_chains, -1);
589 hammer2_pfs_memory_wakeup(chain->pmp);
591 /* spinlock still held */
594 /* spinlock still held */
600 * If any children exist we must leave the chain intact with refs == 0.
601 * They exist because chains are retained below us which have refs or
602 * may require flushing.
604 * Retry (return chain) if we fail to transition the refs to 0, else
605 * return NULL indication nothing more to do.
607 * Chains with children are NOT put on the LRU list.
609 if (chain->core.chain_count) {
610 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
611 hammer2_spin_unex(&chain->core.spin);
612 hammer2_chain_assert_no_data(chain);
613 hammer2_mtx_unlock(&chain->lock);
616 hammer2_spin_unex(&chain->core.spin);
617 hammer2_mtx_unlock(&chain->lock);
621 /* spinlock still held */
622 /* no chains left under us */
625 * chain->core has no children left so no accessors can get to our
626 * chain from there. Now we have to lock the parent core to interlock
627 * remaining possible accessors that might bump chain's refs before
628 * we can safely drop chain's refs with intent to free the chain.
631 pmp = chain->pmp; /* can be NULL */
634 parent = chain->parent;
637 * WARNING! chain's spin lock is still held here, and other spinlocks
638 * will be acquired and released in the code below. We
639 * cannot be making fancy procedure calls!
643 * We can cache the chain if it is associated with a pmp
644 * and not flagged as being destroyed or requesting a full
645 * release. In this situation the chain is not removed
646 * from its parent, i.e. it can still be looked up.
648 * We intentionally do not cache DATA chains because these
649 * were likely used to load data into the logical buffer cache
650 * and will not be accessed again for some time.
653 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
655 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
657 hammer2_spin_ex(&parent->core.spin);
658 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
660 * 1->0 transition failed, retry. Do not drop
661 * the chain's data yet!
664 hammer2_spin_unex(&parent->core.spin);
665 hammer2_spin_unex(&chain->core.spin);
666 hammer2_mtx_unlock(&chain->lock);
675 dio = hammer2_chain_drop_data(chain, 1);
677 hammer2_chain_assert_no_data(chain);
679 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
680 hammer2_spin_ex(&pmp->lru_spin);
681 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
682 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
685 * If we are over the LRU limit we need to drop something.
687 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
688 rdrop = TAILQ_FIRST(&pmp->lru_list);
689 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
690 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
691 atomic_add_int(&rdrop->refs, 1);
692 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
694 atomic_add_int(&pmp->lru_count, 1);
696 hammer2_spin_unex(&pmp->lru_spin);
698 hammer2_spin_unex(&parent->core.spin);
699 parent = NULL; /* safety */
701 hammer2_spin_unex(&chain->core.spin);
702 hammer2_mtx_unlock(&chain->lock);
705 hammer2_io_bqrelse(&dio);
713 * Spinlock the parent and try to drop the last ref on chain.
714 * On success determine if we should dispose of the chain
715 * (remove the chain from its parent, etc).
717 * (normal core locks are top-down recursive but we define
718 * core spinlocks as bottom-up recursive, so this is safe).
721 hammer2_spin_ex(&parent->core.spin);
722 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
724 /* XXX remove, don't try to drop data on fail */
725 hammer2_spin_unex(&parent->core.spin);
726 dio = hammer2_chain_drop_data(chain, 0);
727 hammer2_spin_unex(&chain->core.spin);
729 hammer2_io_bqrelse(&dio);
732 * 1->0 transition failed, retry.
734 hammer2_spin_unex(&parent->core.spin);
735 hammer2_spin_unex(&chain->core.spin);
736 hammer2_mtx_unlock(&chain->lock);
742 * 1->0 transition successful, parent spin held to prevent
743 * new lookups, chain spinlock held to protect parent field.
744 * Remove chain from the parent.
746 * If the chain is being removed from the parent's btree but
747 * is not bmapped, we have to adjust live_count downward. If
748 * it is bmapped then the blockref is retained in the parent
749 * as is its associated live_count. This case can occur when
750 * a chain added to the topology is unable to flush and is
751 * then later deleted.
753 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
754 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
755 (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
756 atomic_add_int(&parent->core.live_count, -1);
758 RB_REMOVE(hammer2_chain_tree,
759 &parent->core.rbtree, chain);
760 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
761 --parent->core.chain_count;
762 chain->parent = NULL;
766 * If our chain was the last chain in the parent's core the
767 * core is now empty and its parent might have to be
768 * re-dropped if it has 0 refs.
770 if (parent->core.chain_count == 0) {
772 atomic_add_int(&rdrop->refs, 1);
774 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
778 hammer2_spin_unex(&parent->core.spin);
779 parent = NULL; /* safety */
785 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
787 * 1->0 transition failed, retry.
789 hammer2_spin_unex(&parent->core.spin);
790 hammer2_spin_unex(&chain->core.spin);
791 hammer2_mtx_unlock(&chain->lock);
798 * Successful 1->0 transition, no parent, no children... no way for
799 * anyone to ref this chain any more. We can clean-up and free it.
801 * We still have the core spinlock, and core's chain_count is 0.
802 * Any parent spinlock is gone.
804 hammer2_spin_unex(&chain->core.spin);
805 hammer2_chain_assert_no_data(chain);
806 hammer2_mtx_unlock(&chain->lock);
807 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
808 chain->core.chain_count == 0);
811 * All locks are gone, no pointers remain to the chain, finish
814 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
815 HAMMER2_CHAIN_MODIFIED)) == 0);
817 dio = hammer2_chain_drop_data(chain, 1);
819 hammer2_io_bqrelse(&dio);
823 * Once chain resources are gone we can use the now dead chain
824 * structure to placehold what might otherwise require a recursive
825 * drop, because we have potentially two things to drop and can only
826 * return one directly.
828 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
829 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
831 kfree(chain, hmp->mchain);
835 * Possible chaining loop when parent re-drop needed.
841 * On last lock release.
843 static hammer2_io_t *
844 hammer2_chain_drop_data(hammer2_chain_t *chain)
848 if ((dio = chain->dio) != NULL) {
852 switch(chain->bref.type) {
853 case HAMMER2_BREF_TYPE_VOLUME:
854 case HAMMER2_BREF_TYPE_FREEMAP:
857 if (chain->data != NULL) {
858 hammer2_spin_unex(&chain->core.spin);
859 panic("chain data not null: "
860 "chain %p bref %016jx.%02x "
861 "refs %d parent %p dio %p data %p",
862 chain, chain->bref.data_off,
863 chain->bref.type, chain->refs,
865 chain->dio, chain->data);
867 KKASSERT(chain->data == NULL);
875 * Lock a referenced chain element, acquiring its data with I/O if necessary,
876 * and specify how you would like the data to be resolved.
878 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
880 * The lock is allowed to recurse, multiple locking ops will aggregate
881 * the requested resolve types. Once data is assigned it will not be
882 * removed until the last unlock.
884 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
885 * (typically used to avoid device/logical buffer
888 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
889 * the INITIAL-create state (indirect blocks only).
891 * Do not resolve data elements for DATA chains.
892 * (typically used to avoid device/logical buffer
895 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
897 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
898 * it will be locked exclusive.
900 * NOTE: Embedded elements (volume header, inodes) are always resolved
903 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
904 * element will instantiate and zero its buffer, and flush it on
907 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
908 * so as not to instantiate a device buffer, which could alias against
909 * a logical file buffer. However, if ALWAYS is specified the
910 * device buffer will be instantiated anyway.
912 * WARNING! This function blocks on I/O if data needs to be fetched. This
913 * blocking can run concurrent with other compatible lock holders
914 * who do not need data returning. The lock is not upgraded to
915 * exclusive during a data fetch, a separate bit is used to
916 * interlock I/O. However, an exclusive lock holder can still count
917 * on being interlocked against an I/O fetch managed by a shared
921 hammer2_chain_lock(hammer2_chain_t *chain, int how)
924 * Ref and lock the element. Recursive locks are allowed.
926 KKASSERT(chain->refs > 0);
927 atomic_add_int(&chain->lockcnt, 1);
930 * Get the appropriate lock. If LOCKAGAIN is flagged with SHARED
931 * the caller expects a shared lock to already be present and we
932 * are giving it another ref. This case must importantly not block
933 * if there is a pending exclusive lock request.
935 if (how & HAMMER2_RESOLVE_SHARED) {
936 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
937 hammer2_mtx_sh_again(&chain->lock);
939 hammer2_mtx_sh(&chain->lock);
942 hammer2_mtx_ex(&chain->lock);
944 ++curthread->td_tracker;
947 * If we already have a valid data pointer no further action is
954 * Do we have to resolve the data? This is generally only
955 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
956 * Other BREF types expects the data to be there.
958 switch(how & HAMMER2_RESOLVE_MASK) {
959 case HAMMER2_RESOLVE_NEVER:
961 case HAMMER2_RESOLVE_MAYBE:
962 if (chain->flags & HAMMER2_CHAIN_INITIAL)
964 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
967 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
969 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
973 case HAMMER2_RESOLVE_ALWAYS:
979 * Caller requires data
981 hammer2_chain_load_data(chain);
985 * Lock the chain, retain the hold, and drop the data persistence count.
986 * The data should remain valid because we never transitioned lockcnt
990 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
992 hammer2_chain_lock(chain, how);
993 atomic_add_int(&chain->lockcnt, -1);
998 * Downgrade an exclusive chain lock to a shared chain lock.
1000 * NOTE: There is no upgrade equivalent due to the ease of
1001 * deadlocks in that direction.
1004 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1006 hammer2_mtx_downgrade(&chain->lock);
1012 * Obtains a second shared lock on the chain, does not account the second
1013 * shared lock as being owned by the current thread.
1015 * Caller must already own a shared lock on this chain.
1017 * The lock function is required to obtain the second shared lock without
1018 * blocking on pending exclusive requests.
1021 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
1023 hammer2_mtx_sh_again(&chain->lock);
1024 atomic_add_int(&chain->lockcnt, 1);
1025 /* do not count in td_tracker for this thread */
1029 * Accounts for a shared lock that was pushed to us as being owned by our
1033 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
1035 ++curthread->td_tracker;
1040 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1041 * may be of any type.
1043 * Once chain->data is set it cannot be disposed of until all locks are
1047 hammer2_chain_load_data(hammer2_chain_t *chain)
1049 hammer2_blockref_t *bref;
1056 * Degenerate case, data already present, or chain has no media
1057 * reference to load.
1061 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1065 KKASSERT(hmp != NULL);
1068 * Gain the IOINPROG bit, interlocked block.
1074 oflags = chain->flags;
1076 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1077 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1078 tsleep_interlock(&chain->flags, 0);
1079 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1080 tsleep(&chain->flags, PINTERLOCKED,
1085 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1086 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1094 * We own CHAIN_IOINPROG
1096 * Degenerate case if we raced another load.
1102 * We must resolve to a device buffer, either by issuing I/O or
1103 * by creating a zero-fill element. We do not mark the buffer
1104 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1105 * API must still be used to do that).
1107 * The device buffer is variable-sized in powers of 2 down
1108 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1109 * chunk always contains buffers of the same size. (XXX)
1111 * The minimum physical IO size may be larger than the variable
1114 bref = &chain->bref;
1117 * The getblk() optimization can only be used on newly created
1118 * elements if the physical block size matches the request.
1120 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1121 error = hammer2_io_new(hmp, bref->type,
1122 bref->data_off, chain->bytes,
1125 error = hammer2_io_bread(hmp, bref->type,
1126 bref->data_off, chain->bytes,
1128 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1131 chain->error = HAMMER2_ERROR_EIO;
1132 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1133 (intmax_t)bref->data_off, error);
1134 hammer2_io_bqrelse(&chain->dio);
1140 * This isn't perfect and can be ignored on OSs which do not have
1141 * an indication as to whether a buffer is coming from cache or
1142 * if I/O was actually issued for the read. TESTEDGOOD will work
1143 * pretty well without the B_IOISSUED logic because chains are
1144 * cached, but in that situation (without B_IOISSUED) it will not
1145 * detect whether a re-read via I/O is corrupted verses the original
1148 * We can't re-run the CRC on every fresh lock. That would be
1149 * insanely expensive.
1151 * If the underlying kernel buffer covers the entire chain we can
1152 * use the B_IOISSUED indication to determine if we have to re-run
1153 * the CRC on chain data for chains that managed to stay cached
1154 * across the kernel disposal of the original buffer.
1156 if ((dio = chain->dio) != NULL && dio->bp) {
1157 struct buf *bp = dio->bp;
1159 if (dio->psize == chain->bytes &&
1160 (bp->b_flags & B_IOISSUED)) {
1161 atomic_clear_int(&chain->flags,
1162 HAMMER2_CHAIN_TESTEDGOOD);
1163 bp->b_flags &= ~B_IOISSUED;
1168 * NOTE: A locked chain's data cannot be modified without first
1169 * calling hammer2_chain_modify().
1173 * Clear INITIAL. In this case we used io_new() and the buffer has
1174 * been zero'd and marked dirty.
1176 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1178 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1179 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1180 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1181 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1183 * check data not currently synchronized due to
1184 * modification. XXX assumes data stays in the buffer
1185 * cache, which might not be true (need biodep on flush
1186 * to calculate crc? or simple crc?).
1188 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1189 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1190 chain->error = HAMMER2_ERROR_CHECK;
1192 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1197 * Setup the data pointer, either pointing it to an embedded data
1198 * structure and copying the data from the buffer, or pointing it
1201 * The buffer is not retained when copying to an embedded data
1202 * structure in order to avoid potential deadlocks or recursions
1203 * on the same physical buffer.
1205 * WARNING! Other threads can start using the data the instant we
1206 * set chain->data non-NULL.
1208 switch (bref->type) {
1209 case HAMMER2_BREF_TYPE_VOLUME:
1210 case HAMMER2_BREF_TYPE_FREEMAP:
1212 * Copy data from bp to embedded buffer
1214 panic("hammer2_chain_load_data: unresolved volume header");
1216 case HAMMER2_BREF_TYPE_DIRENT:
1217 KKASSERT(chain->bytes != 0);
1219 case HAMMER2_BREF_TYPE_INODE:
1220 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1221 case HAMMER2_BREF_TYPE_INDIRECT:
1222 case HAMMER2_BREF_TYPE_DATA:
1223 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1226 * Point data at the device buffer and leave dio intact.
1228 chain->data = (void *)bdata;
1233 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1240 oflags = chain->flags;
1241 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1242 HAMMER2_CHAIN_IOSIGNAL);
1243 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1244 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1245 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1246 wakeup(&chain->flags);
1253 * Unlock and deref a chain element.
1255 * Remember that the presence of children under chain prevent the chain's
1256 * destruction but do not add additional references, so the dio will still
1260 hammer2_chain_unlock(hammer2_chain_t *chain)
1266 --curthread->td_tracker;
1269 * If multiple locks are present (or being attempted) on this
1270 * particular chain we can just unlock, drop refs, and return.
1272 * Otherwise fall-through on the 1->0 transition.
1275 lockcnt = chain->lockcnt;
1276 KKASSERT(lockcnt > 0);
1279 if (atomic_cmpset_int(&chain->lockcnt,
1280 lockcnt, lockcnt - 1)) {
1281 hammer2_mtx_unlock(&chain->lock);
1284 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1285 /* while holding the mutex exclusively */
1286 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1290 * This situation can easily occur on SMP due to
1291 * the gap inbetween the 1->0 transition and the
1292 * final unlock. We cannot safely block on the
1293 * mutex because lockcnt might go above 1.
1295 * XXX Sleep for one tick if it takes too long.
1297 if (++iter > 1000) {
1298 if (iter > 1000 + hz) {
1299 kprintf("hammer2: h2race2 %p\n", chain);
1302 tsleep(&iter, 0, "h2race2", 1);
1310 * Last unlock / mutex upgraded to exclusive. Drop the data
1313 dio = hammer2_chain_drop_data(chain);
1315 hammer2_io_bqrelse(&dio);
1316 hammer2_mtx_unlock(&chain->lock);
1320 * Unlock and hold chain data intact
1323 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1325 atomic_add_int(&chain->lockcnt, 1);
1326 hammer2_chain_unlock(chain);
1330 * Helper to obtain the blockref[] array base and count for a chain.
1332 * XXX Not widely used yet, various use cases need to be validated and
1333 * converted to use this function.
1336 hammer2_blockref_t *
1337 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1339 hammer2_blockref_t *base;
1342 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1345 switch(parent->bref.type) {
1346 case HAMMER2_BREF_TYPE_INODE:
1347 count = HAMMER2_SET_COUNT;
1349 case HAMMER2_BREF_TYPE_INDIRECT:
1350 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1351 count = parent->bytes / sizeof(hammer2_blockref_t);
1353 case HAMMER2_BREF_TYPE_VOLUME:
1354 count = HAMMER2_SET_COUNT;
1356 case HAMMER2_BREF_TYPE_FREEMAP:
1357 count = HAMMER2_SET_COUNT;
1360 panic("hammer2_chain_create_indirect: "
1361 "unrecognized blockref type: %d",
1367 switch(parent->bref.type) {
1368 case HAMMER2_BREF_TYPE_INODE:
1369 base = &parent->data->ipdata.u.blockset.blockref[0];
1370 count = HAMMER2_SET_COUNT;
1372 case HAMMER2_BREF_TYPE_INDIRECT:
1373 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1374 base = &parent->data->npdata[0];
1375 count = parent->bytes / sizeof(hammer2_blockref_t);
1377 case HAMMER2_BREF_TYPE_VOLUME:
1378 base = &parent->data->voldata.
1379 sroot_blockset.blockref[0];
1380 count = HAMMER2_SET_COUNT;
1382 case HAMMER2_BREF_TYPE_FREEMAP:
1383 base = &parent->data->blkset.blockref[0];
1384 count = HAMMER2_SET_COUNT;
1387 panic("hammer2_chain_create_indirect: "
1388 "unrecognized blockref type: %d",
1400 * This counts the number of live blockrefs in a block array and
1401 * also calculates the point at which all remaining blockrefs are empty.
1402 * This routine can only be called on a live chain.
1404 * Caller holds the chain locked, but possibly with a shared lock. We
1405 * must use an exclusive spinlock to prevent corruption.
1407 * NOTE: Flag is not set until after the count is complete, allowing
1408 * callers to test the flag without holding the spinlock.
1410 * NOTE: If base is NULL the related chain is still in the INITIAL
1411 * state and there are no blockrefs to count.
1413 * NOTE: live_count may already have some counts accumulated due to
1414 * creation and deletion and could even be initially negative.
1417 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1418 hammer2_blockref_t *base, int count)
1420 hammer2_spin_ex(&chain->core.spin);
1421 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1423 while (--count >= 0) {
1424 if (base[count].type)
1427 chain->core.live_zero = count + 1;
1428 while (count >= 0) {
1429 if (base[count].type)
1430 atomic_add_int(&chain->core.live_count,
1435 chain->core.live_zero = 0;
1437 /* else do not modify live_count */
1438 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1440 hammer2_spin_unex(&chain->core.spin);
1444 * Resize the chain's physical storage allocation in-place. This function does
1445 * not usually adjust the data pointer and must be followed by (typically) a
1446 * hammer2_chain_modify() call to copy any old data over and adjust the
1449 * Chains can be resized smaller without reallocating the storage. Resizing
1450 * larger will reallocate the storage. Excess or prior storage is reclaimed
1451 * asynchronously at a later time.
1453 * An nradix value of 0 is special-cased to mean that the storage should
1454 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1457 * Must be passed an exclusively locked parent and chain.
1459 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1460 * to avoid instantiating a device buffer that conflicts with the vnode data
1461 * buffer. However, because H2 can compress or encrypt data, the chain may
1462 * have a dio assigned to it in those situations, and they do not conflict.
1464 * XXX return error if cannot resize.
1467 hammer2_chain_resize(hammer2_chain_t *chain,
1468 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1469 int nradix, int flags)
1479 * Only data and indirect blocks can be resized for now.
1480 * (The volu root, inodes, and freemap elements use a fixed size).
1482 KKASSERT(chain != &hmp->vchain);
1483 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1484 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1485 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1488 * Nothing to do if the element is already the proper size
1490 obytes = chain->bytes;
1491 nbytes = (nradix) ? (1U << nradix) : 0;
1492 if (obytes == nbytes)
1493 return (chain->error);
1496 * Make sure the old data is instantiated so we can copy it. If this
1497 * is a data block, the device data may be superfluous since the data
1498 * might be in a logical block, but compressed or encrypted data is
1501 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1503 error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1508 * Relocate the block, even if making it smaller (because different
1509 * block sizes may be in different regions).
1511 * NOTE: Operation does not copy the data and may only be used
1512 * to resize data blocks in-place, or directory entry blocks
1513 * which are about to be modified in some manner.
1515 error = hammer2_freemap_alloc(chain, nbytes);
1519 chain->bytes = nbytes;
1522 * We don't want the followup chain_modify() to try to copy data
1523 * from the old (wrong-sized) buffer. It won't know how much to
1524 * copy. This case should only occur during writes when the
1525 * originator already has the data to write in-hand.
1528 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1529 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1530 hammer2_io_brelse(&chain->dio);
1533 return (chain->error);
1537 * Set the chain modified so its data can be changed by the caller, or
1538 * install deduplicated data. The caller must call this routine for each
1539 * set of modifications it makes, even if the chain is already flagged
1542 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1543 * is a CLC (cluster level change) field and is not updated by parent
1544 * propagation during a flush.
1546 * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1547 * chain->error except for HAMMER2_ERROR_ENOSPC. If the allocation fails
1548 * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1549 * remains unmodified with its old data ref intact and chain->error
1554 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1555 * even if the chain is still flagged MODIFIED. In this case the chain's
1556 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1558 * If the caller passes a non-zero dedup_off we will use it to assign the
1559 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1560 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1561 * must not modify the data content upon return.
1564 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1565 hammer2_off_t dedup_off, int flags)
1567 hammer2_blockref_t obref;
1578 obref = chain->bref;
1579 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1582 * Data is not optional for freemap chains (we must always be sure
1583 * to copy the data on COW storage allocations).
1585 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1586 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1587 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1588 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1592 * Data must be resolved if already assigned, unless explicitly
1593 * flagged otherwise. If we cannot safety load the data the
1594 * modification fails and we return early.
1596 if (chain->data == NULL && chain->bytes != 0 &&
1597 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1598 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1599 hammer2_chain_load_data(chain);
1601 return (chain->error);
1606 * Set MODIFIED to indicate that the chain has been modified. A new
1607 * allocation is required when modifying a chain.
1609 * Set UPDATE to ensure that the blockref is updated in the parent.
1611 * If MODIFIED is already set determine if we can reuse the assigned
1612 * data block or if we need a new data block.
1614 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1616 * Must set modified bit.
1618 atomic_add_long(&hammer2_count_modified_chains, 1);
1619 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1620 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1624 * We may be able to avoid a copy-on-write if the chain's
1625 * check mode is set to NONE and the chain's current
1626 * modify_tid is beyond the last explicit snapshot tid.
1628 * This implements HAMMER2's overwrite-in-place feature.
1630 * NOTE! This data-block cannot be used as a de-duplication
1631 * source when the check mode is set to NONE.
1633 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1634 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1635 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1636 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1637 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1638 HAMMER2_CHECK_NONE &&
1640 chain->bref.modify_tid >
1641 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1643 * Sector overwrite allowed.
1648 * Sector overwrite not allowed, must copy-on-write.
1652 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1654 * If the modified chain was registered for dedup we need
1655 * a new allocation. This only happens for delayed-flush
1656 * chains (i.e. which run through the front-end buffer
1663 * Already flagged modified, no new allocation is needed.
1670 * Flag parent update required.
1672 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1673 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1680 * The modification or re-modification requires an allocation and
1681 * possible COW. If an error occurs, the previous content and data
1682 * reference is retained and the modification fails.
1684 * If dedup_off is non-zero, the caller is requesting a deduplication
1685 * rather than a modification. The MODIFIED bit is not set and the
1686 * data offset is set to the deduplication offset. The data cannot
1689 * NOTE: The dedup offset is allowed to be in a partially free state
1690 * and we must be sure to reset it to a fully allocated state
1691 * to force two bulkfree passes to free it again.
1693 * NOTE: Only applicable when chain->bytes != 0.
1695 * XXX can a chain already be marked MODIFIED without a data
1696 * assignment? If not, assert here instead of testing the case.
1698 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1700 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1704 * NOTE: We do not have to remove the dedup
1705 * registration because the area is still
1706 * allocated and the underlying DIO will
1710 chain->bref.data_off = dedup_off;
1711 chain->bytes = 1 << (dedup_off &
1712 HAMMER2_OFF_MASK_RADIX);
1714 atomic_clear_int(&chain->flags,
1715 HAMMER2_CHAIN_MODIFIED);
1716 atomic_add_long(&hammer2_count_modified_chains,
1719 hammer2_pfs_memory_wakeup(chain->pmp);
1720 hammer2_freemap_adjust(hmp, &chain->bref,
1721 HAMMER2_FREEMAP_DORECOVER);
1722 atomic_set_int(&chain->flags,
1723 HAMMER2_CHAIN_DEDUPABLE);
1725 error = hammer2_freemap_alloc(chain,
1727 atomic_clear_int(&chain->flags,
1728 HAMMER2_CHAIN_DEDUPABLE);
1734 * Stop here if error. We have to undo any flag bits we might
1739 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1740 atomic_add_long(&hammer2_count_modified_chains, -1);
1742 hammer2_pfs_memory_wakeup(chain->pmp);
1745 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1751 * Update mirror_tid and modify_tid. modify_tid is only updated
1752 * if not passed as zero (during flushes, parent propagation passes
1755 * NOTE: chain->pmp could be the device spmp.
1757 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1759 chain->bref.modify_tid = mtid;
1762 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1763 * requires updating as well as to tell the delete code that the
1764 * chain's blockref might not exactly match (in terms of physical size
1765 * or block offset) the one in the parent's blocktable. The base key
1766 * of course will still match.
1768 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1769 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1772 * Short-cut data blocks which the caller does not need an actual
1773 * data reference to (aka OPTDATA), as long as the chain does not
1774 * already have a data pointer to the data. This generally means
1775 * that the modifications are being done via the logical buffer cache.
1776 * The INITIAL flag relates only to the device data buffer and thus
1777 * remains unchange in this situation.
1779 * This code also handles bytes == 0 (most dirents).
1781 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1782 (flags & HAMMER2_MODIFY_OPTDATA) &&
1783 chain->data == NULL) {
1784 KKASSERT(chain->dio == NULL);
1789 * Clearing the INITIAL flag (for indirect blocks) indicates that
1790 * we've processed the uninitialized storage allocation.
1792 * If this flag is already clear we are likely in a copy-on-write
1793 * situation but we have to be sure NOT to bzero the storage if
1794 * no data is present.
1796 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1797 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1804 * Instantiate data buffer and possibly execute COW operation
1806 switch(chain->bref.type) {
1807 case HAMMER2_BREF_TYPE_VOLUME:
1808 case HAMMER2_BREF_TYPE_FREEMAP:
1810 * The data is embedded, no copy-on-write operation is
1813 KKASSERT(chain->dio == NULL);
1815 case HAMMER2_BREF_TYPE_DIRENT:
1817 * The data might be fully embedded.
1819 if (chain->bytes == 0) {
1820 KKASSERT(chain->dio == NULL);
1824 case HAMMER2_BREF_TYPE_INODE:
1825 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1826 case HAMMER2_BREF_TYPE_DATA:
1827 case HAMMER2_BREF_TYPE_INDIRECT:
1828 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1830 * Perform the copy-on-write operation
1832 * zero-fill or copy-on-write depending on whether
1833 * chain->data exists or not and set the dirty state for
1834 * the new buffer. hammer2_io_new() will handle the
1837 * If a dedup_off was supplied this is an existing block
1838 * and no COW, copy, or further modification is required.
1840 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1842 if (wasinitial && dedup_off == 0) {
1843 error = hammer2_io_new(hmp, chain->bref.type,
1844 chain->bref.data_off,
1845 chain->bytes, &dio);
1847 error = hammer2_io_bread(hmp, chain->bref.type,
1848 chain->bref.data_off,
1849 chain->bytes, &dio);
1851 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1854 * If an I/O error occurs make sure callers cannot accidently
1855 * modify the old buffer's contents and corrupt the filesystem.
1858 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1860 chain->error = HAMMER2_ERROR_EIO;
1861 hammer2_io_brelse(&dio);
1862 hammer2_io_brelse(&chain->dio);
1867 bdata = hammer2_io_data(dio, chain->bref.data_off);
1871 * COW (unless a dedup).
1873 KKASSERT(chain->dio != NULL);
1874 if (chain->data != (void *)bdata && dedup_off == 0) {
1875 bcopy(chain->data, bdata, chain->bytes);
1877 } else if (wasinitial == 0) {
1879 * We have a problem. We were asked to COW but
1880 * we don't have any data to COW with!
1882 panic("hammer2_chain_modify: having a COW %p\n",
1887 * Retire the old buffer, replace with the new. Dirty or
1888 * redirty the new buffer.
1890 * WARNING! The system buffer cache may have already flushed
1891 * the buffer, so we must be sure to [re]dirty it
1892 * for further modification.
1894 * If dedup_off was supplied, the caller is not
1895 * expected to make any further modification to the
1899 hammer2_io_bqrelse(&chain->dio);
1900 chain->data = (void *)bdata;
1903 hammer2_io_setdirty(dio);
1906 panic("hammer2_chain_modify: illegal non-embedded type %d",
1913 * setflush on parent indicating that the parent must recurse down
1914 * to us. Do not call on chain itself which might already have it
1918 hammer2_chain_setflush(chain->parent);
1919 return (chain->error);
1923 * Modify the chain associated with an inode.
1926 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1927 hammer2_tid_t mtid, int flags)
1931 hammer2_inode_modify(ip);
1932 error = hammer2_chain_modify(chain, mtid, 0, flags);
1938 * Volume header data locks
1941 hammer2_voldata_lock(hammer2_dev_t *hmp)
1943 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1947 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1949 lockmgr(&hmp->vollk, LK_RELEASE);
1953 hammer2_voldata_modify(hammer2_dev_t *hmp)
1955 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1956 atomic_add_long(&hammer2_count_modified_chains, 1);
1957 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1958 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1963 * This function returns the chain at the nearest key within the specified
1964 * range. The returned chain will be referenced but not locked.
1966 * This function will recurse through chain->rbtree as necessary and will
1967 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1968 * the iteration value is less than the current value of *key_nextp.
1970 * The caller should use (*key_nextp) to calculate the actual range of
1971 * the returned element, which will be (key_beg to *key_nextp - 1), because
1972 * there might be another element which is superior to the returned element
1975 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1976 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1977 * it will wind up being (key_end + 1).
1979 * WARNING! Must be called with child's spinlock held. Spinlock remains
1980 * held through the operation.
1982 struct hammer2_chain_find_info {
1983 hammer2_chain_t *best;
1984 hammer2_key_t key_beg;
1985 hammer2_key_t key_end;
1986 hammer2_key_t key_next;
1989 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1990 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1994 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1995 hammer2_key_t key_beg, hammer2_key_t key_end)
1997 struct hammer2_chain_find_info info;
2000 info.key_beg = key_beg;
2001 info.key_end = key_end;
2002 info.key_next = *key_nextp;
2004 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
2005 hammer2_chain_find_cmp, hammer2_chain_find_callback,
2007 *key_nextp = info.key_next;
2009 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
2010 parent, key_beg, key_end, *key_nextp);
2018 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
2020 struct hammer2_chain_find_info *info = data;
2021 hammer2_key_t child_beg;
2022 hammer2_key_t child_end;
2024 child_beg = child->bref.key;
2025 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2027 if (child_end < info->key_beg)
2029 if (child_beg > info->key_end)
2036 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2038 struct hammer2_chain_find_info *info = data;
2039 hammer2_chain_t *best;
2040 hammer2_key_t child_end;
2043 * WARNING! Layerq is scanned forwards, exact matches should keep
2044 * the existing info->best.
2046 if ((best = info->best) == NULL) {
2048 * No previous best. Assign best
2051 } else if (best->bref.key <= info->key_beg &&
2052 child->bref.key <= info->key_beg) {
2057 /*info->best = child;*/
2058 } else if (child->bref.key < best->bref.key) {
2060 * Child has a nearer key and best is not flush with key_beg.
2061 * Set best to child. Truncate key_next to the old best key.
2064 if (info->key_next > best->bref.key || info->key_next == 0)
2065 info->key_next = best->bref.key;
2066 } else if (child->bref.key == best->bref.key) {
2068 * If our current best is flush with the child then this
2069 * is an illegal overlap.
2071 * key_next will automatically be limited to the smaller of
2072 * the two end-points.
2078 * Keep the current best but truncate key_next to the child's
2081 * key_next will also automatically be limited to the smaller
2082 * of the two end-points (probably not necessary for this case
2083 * but we do it anyway).
2085 if (info->key_next > child->bref.key || info->key_next == 0)
2086 info->key_next = child->bref.key;
2090 * Always truncate key_next based on child's end-of-range.
2092 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2093 if (child_end && (info->key_next > child_end || info->key_next == 0))
2094 info->key_next = child_end;
2100 * Retrieve the specified chain from a media blockref, creating the
2101 * in-memory chain structure which reflects it. The returned chain is
2102 * held but not locked. The caller must lock it to crc-check and
2103 * dereference its data, and should check chain->error after locking
2104 * before assuming that the data is good.
2106 * To handle insertion races pass the INSERT_RACE flag along with the
2107 * generation number of the core. NULL will be returned if the generation
2108 * number changes before we have a chance to insert the chain. Insert
2109 * races can occur because the parent might be held shared.
2111 * Caller must hold the parent locked shared or exclusive since we may
2112 * need the parent's bref array to find our block.
2114 * WARNING! chain->pmp is always set to NULL for any chain representing
2115 * part of the super-root topology.
2118 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2119 hammer2_blockref_t *bref)
2121 hammer2_dev_t *hmp = parent->hmp;
2122 hammer2_chain_t *chain;
2126 * Allocate a chain structure representing the existing media
2127 * entry. Resulting chain has one ref and is not locked.
2129 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2130 chain = hammer2_chain_alloc(hmp, NULL, bref);
2132 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2133 /* ref'd chain returned */
2136 * Flag that the chain is in the parent's blockmap so delete/flush
2137 * knows what to do with it.
2139 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2142 * Link the chain into its parent. A spinlock is required to safely
2143 * access the RBTREE, and it is possible to collide with another
2144 * hammer2_chain_get() operation because the caller might only hold
2145 * a shared lock on the parent.
2147 * NOTE: Get races can occur quite often when we distribute
2148 * asynchronous read-aheads across multiple threads.
2150 KKASSERT(parent->refs > 0);
2151 error = hammer2_chain_insert(parent, chain,
2152 HAMMER2_CHAIN_INSERT_SPIN |
2153 HAMMER2_CHAIN_INSERT_RACE,
2156 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2157 /*kprintf("chain %p get race\n", chain);*/
2158 hammer2_chain_drop(chain);
2161 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2165 * Return our new chain referenced but not locked, or NULL if
2172 * Lookup initialization/completion API
2175 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2177 hammer2_chain_ref(parent);
2178 if (flags & HAMMER2_LOOKUP_SHARED) {
2179 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2180 HAMMER2_RESOLVE_SHARED);
2182 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2188 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2191 hammer2_chain_unlock(parent);
2192 hammer2_chain_drop(parent);
2197 * Take the locked chain and return a locked parent. The chain remains
2200 * This will work even if the chain is errored, and the caller can check
2201 * parent->error on return if desired since the parent will be locked.
2203 * This function handles the lock order reversal.
2206 hammer2_chain_getparent(hammer2_chain_t *chain, int how)
2208 hammer2_chain_t *parent;
2211 * Be careful of order, chain must be unlocked before parent
2212 * is locked below to avoid a deadlock.
2214 * Safe access to fu->parent requires fu's core spinlock.
2217 hammer2_spin_ex(&chain->core.spin);
2218 parent = chain->parent;
2219 if (parent == NULL) {
2220 hammer2_spin_unex(&chain->core.spin);
2221 panic("hammer2_chain_getparent: no parent");
2223 hammer2_chain_ref(parent);
2224 hammer2_spin_unex(&chain->core.spin);
2226 hammer2_chain_unlock(chain);
2227 hammer2_chain_lock(parent, how);
2228 hammer2_chain_lock(chain, how);
2231 * Parent relinking races are quite common. We have to get it right
2232 * or we will blow up the block table.
2234 if (chain->parent != parent) {
2235 hammer2_chain_unlock(parent);
2236 hammer2_chain_drop(parent);
2243 * Take the locked chain and return a locked parent. The chain is unlocked
2244 * and dropped. *chainp is set to the returned parent as a convenience.
2246 * This will work even if the chain is errored, and the caller can check
2247 * parent->error on return if desired since the parent will be locked.
2249 * This function handles the lock order reversal.
2252 hammer2_chain_repparent(hammer2_chain_t **chainp, int how)
2254 hammer2_chain_t *chain;
2255 hammer2_chain_t *parent;
2258 * Be careful of order, chain must be unlocked before parent
2259 * is locked below to avoid a deadlock.
2261 * Safe access to fu->parent requires fu's core spinlock.
2265 hammer2_spin_ex(&chain->core.spin);
2266 parent = chain->parent;
2267 if (parent == NULL) {
2268 hammer2_spin_unex(&chain->core.spin);
2269 panic("hammer2_chain_getparent: no parent");
2271 hammer2_chain_ref(parent);
2272 hammer2_spin_unex(&chain->core.spin);
2274 hammer2_chain_unlock(chain);
2275 hammer2_chain_lock(parent, how);
2278 * Parent relinking races are quite common. We have to get it right
2279 * or we will blow up the block table.
2281 if (chain->parent != parent) {
2282 hammer2_chain_lock(chain, how);
2283 hammer2_chain_unlock(parent);
2284 hammer2_chain_drop(parent);
2287 hammer2_chain_drop(chain);
2294 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2295 * (*parentp) typically points to an inode but can also point to a related
2296 * indirect block and this function will recurse upwards and find the inode
2299 * This function unconditionally sets *errorp, replacing any previous value.
2301 * (*parentp) must be exclusively locked and referenced and can be an inode
2302 * or an existing indirect block within the inode. If (*parent) is errored
2303 * out, this function will not attempt to recurse the radix tree and
2304 * will return NULL along with an appropriate *errorp. If NULL is returned
2305 * and *errorp is 0, the requested lookup could not be located.
2307 * On return (*parentp) will be modified to point at the deepest parent chain
2308 * element encountered during the search, as a helper for an insertion or
2309 * deletion. The new (*parentp) will be locked and referenced and the old
2310 * will be unlocked and dereferenced (no change if they are both the same).
2311 * This is particularly important if the caller wishes to insert a new chain,
2312 * (*parentp) will be set properly even if NULL is returned, as long as no
2315 * The matching chain will be returned exclusively locked. If NOLOCK is
2316 * requested the chain will be returned only referenced. Note that the
2317 * parent chain must always be locked shared or exclusive, matching the
2318 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2319 * when NOLOCK is specified but that complicates matters if *parentp must
2320 * inherit the chain.
2322 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2323 * data pointer or can otherwise be in flux.
2325 * NULL is returned if no match was found, but (*parentp) will still
2326 * potentially be adjusted.
2328 * On return (*key_nextp) will point to an iterative value for key_beg.
2329 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2331 * This function will also recurse up the chain if the key is not within the
2332 * current parent's range. (*parentp) can never be set to NULL. An iteration
2333 * can simply allow (*parentp) to float inside the loop.
2335 * NOTE! chain->data is not always resolved. By default it will not be
2336 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2337 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2338 * BREF_TYPE_DATA as the device buffer can alias the logical file
2343 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2344 hammer2_key_t key_beg, hammer2_key_t key_end,
2345 int *errorp, int flags)
2348 hammer2_chain_t *parent;
2349 hammer2_chain_t *chain;
2350 hammer2_blockref_t *base;
2351 hammer2_blockref_t *bref;
2352 hammer2_blockref_t bcopy;
2353 hammer2_key_t scan_beg;
2354 hammer2_key_t scan_end;
2356 int how_always = HAMMER2_RESOLVE_ALWAYS;
2357 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2360 int maxloops = 300000;
2362 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2363 how_maybe = how_always;
2364 how = HAMMER2_RESOLVE_ALWAYS;
2365 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2366 how = HAMMER2_RESOLVE_NEVER;
2368 how = HAMMER2_RESOLVE_MAYBE;
2370 if (flags & HAMMER2_LOOKUP_SHARED) {
2371 how_maybe |= HAMMER2_RESOLVE_SHARED;
2372 how_always |= HAMMER2_RESOLVE_SHARED;
2373 how |= HAMMER2_RESOLVE_SHARED;
2377 * Recurse (*parentp) upward if necessary until the parent completely
2378 * encloses the key range or we hit the inode.
2380 * Handle races against the flusher deleting indirect nodes on its
2381 * way back up by continuing to recurse upward past the deletion.
2387 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2388 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2389 scan_beg = parent->bref.key;
2390 scan_end = scan_beg +
2391 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2392 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2393 if (key_beg >= scan_beg && key_end <= scan_end)
2396 parent = hammer2_chain_repparent(parentp, how_maybe);
2400 if (--maxloops == 0)
2401 panic("hammer2_chain_lookup: maxloops");
2403 * Locate the blockref array. Currently we do a fully associative
2404 * search through the array.
2406 switch(parent->bref.type) {
2407 case HAMMER2_BREF_TYPE_INODE:
2409 * Special shortcut for embedded data returns the inode
2410 * itself. Callers must detect this condition and access
2411 * the embedded data (the strategy code does this for us).
2413 * This is only applicable to regular files and softlinks.
2415 * We need a second lock on parent. Since we already have
2416 * a lock we must pass LOCKAGAIN to prevent unexpected
2417 * blocking (we don't want to block on a second shared
2418 * ref if an exclusive lock is pending)
2420 if (parent->data->ipdata.meta.op_flags &
2421 HAMMER2_OPFLAG_DIRECTDATA) {
2422 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2424 *key_nextp = key_end + 1;
2427 hammer2_chain_ref(parent);
2428 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2429 hammer2_chain_lock(parent,
2431 HAMMER2_RESOLVE_LOCKAGAIN);
2432 *key_nextp = key_end + 1;
2435 base = &parent->data->ipdata.u.blockset.blockref[0];
2436 count = HAMMER2_SET_COUNT;
2438 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2439 case HAMMER2_BREF_TYPE_INDIRECT:
2441 * Handle MATCHIND on the parent
2443 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2444 scan_beg = parent->bref.key;
2445 scan_end = scan_beg +
2446 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2447 if (key_beg == scan_beg && key_end == scan_end) {
2449 hammer2_chain_ref(chain);
2450 hammer2_chain_lock(chain, how_maybe);
2451 *key_nextp = scan_end + 1;
2457 * Optimize indirect blocks in the INITIAL state to avoid
2460 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2463 if (parent->data == NULL) {
2464 kprintf("parent->data is NULL %p\n", parent);
2466 tsleep(parent, 0, "xxx", 0);
2468 base = &parent->data->npdata[0];
2470 count = parent->bytes / sizeof(hammer2_blockref_t);
2472 case HAMMER2_BREF_TYPE_VOLUME:
2473 base = &parent->data->voldata.sroot_blockset.blockref[0];
2474 count = HAMMER2_SET_COUNT;
2476 case HAMMER2_BREF_TYPE_FREEMAP:
2477 base = &parent->data->blkset.blockref[0];
2478 count = HAMMER2_SET_COUNT;
2481 kprintf("hammer2_chain_lookup: unrecognized "
2482 "blockref(B) type: %d",
2485 tsleep(&base, 0, "dead", 0);
2486 panic("hammer2_chain_lookup: unrecognized "
2487 "blockref(B) type: %d",
2489 base = NULL; /* safety */
2490 count = 0; /* safety */
2494 * No lookup is possible if the parent is errored. We delayed
2495 * this check as long as we could to ensure that the parent backup,
2496 * embedded data, and MATCHIND code could still execute.
2498 if (parent->error) {
2499 *errorp = parent->error;
2504 * Merged scan to find next candidate.
2506 * hammer2_base_*() functions require the parent->core.live_* fields
2507 * to be synchronized.
2509 * We need to hold the spinlock to access the block array and RB tree
2510 * and to interlock chain creation.
2512 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2513 hammer2_chain_countbrefs(parent, base, count);
2518 hammer2_spin_ex(&parent->core.spin);
2519 chain = hammer2_combined_find(parent, base, count,
2523 generation = parent->core.generation;
2526 * Exhausted parent chain, iterate.
2529 hammer2_spin_unex(&parent->core.spin);
2530 if (key_beg == key_end) /* short cut single-key case */
2534 * Stop if we reached the end of the iteration.
2536 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2537 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2542 * Calculate next key, stop if we reached the end of the
2543 * iteration, otherwise go up one level and loop.
2545 key_beg = parent->bref.key +
2546 ((hammer2_key_t)1 << parent->bref.keybits);
2547 if (key_beg == 0 || key_beg > key_end)
2549 parent = hammer2_chain_repparent(parentp, how_maybe);
2554 * Selected from blockref or in-memory chain.
2556 if (chain == NULL) {
2558 hammer2_spin_unex(&parent->core.spin);
2559 chain = hammer2_chain_get(parent, generation,
2561 if (chain == NULL) {
2563 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2564 parent, key_beg, key_end);
2568 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2569 hammer2_chain_drop(chain);
2573 hammer2_chain_ref(chain);
2574 hammer2_spin_unex(&parent->core.spin);
2578 * chain is referenced but not locked. We must lock the chain
2579 * to obtain definitive state.
2581 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2582 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2583 hammer2_chain_lock(chain, how_maybe);
2585 hammer2_chain_lock(chain, how);
2587 KKASSERT(chain->parent == parent);
2590 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2592 * NOTE: Chain's key range is not relevant as there might be
2593 * one-offs within the range that are not deleted.
2595 * NOTE: Lookups can race delete-duplicate because
2596 * delete-duplicate does not lock the parent's core
2597 * (they just use the spinlock on the core).
2599 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2600 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2601 chain->bref.data_off, chain->bref.type,
2603 hammer2_chain_unlock(chain);
2604 hammer2_chain_drop(chain);
2605 key_beg = *key_nextp;
2606 if (key_beg == 0 || key_beg > key_end)
2612 * If the chain element is an indirect block it becomes the new
2613 * parent and we loop on it. We must maintain our top-down locks
2614 * to prevent the flusher from interfering (i.e. doing a
2615 * delete-duplicate and leaving us recursing down a deleted chain).
2617 * The parent always has to be locked with at least RESOLVE_MAYBE
2618 * so we can access its data. It might need a fixup if the caller
2619 * passed incompatible flags. Be careful not to cause a deadlock
2620 * as a data-load requires an exclusive lock.
2622 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2623 * range is within the requested key range we return the indirect
2624 * block and do NOT loop. This is usually only used to acquire
2627 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2628 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2629 hammer2_chain_unlock(parent);
2630 hammer2_chain_drop(parent);
2631 *parentp = parent = chain;
2636 * All done, return the chain.
2638 * If the caller does not want a locked chain, replace the lock with
2639 * a ref. Perhaps this can eventually be optimized to not obtain the
2640 * lock in the first place for situations where the data does not
2641 * need to be resolved.
2643 * NOTE! A chain->error must be tested by the caller upon return.
2644 * *errorp is only set based on issues which occur while
2645 * trying to reach the chain.
2648 if (flags & HAMMER2_LOOKUP_NOLOCK)
2649 hammer2_chain_unlock(chain);
2655 * After having issued a lookup we can iterate all matching keys.
2657 * If chain is non-NULL we continue the iteration from just after it's index.
2659 * If chain is NULL we assume the parent was exhausted and continue the
2660 * iteration at the next parent.
2662 * If a fatal error occurs (typically an I/O error), a dummy chain is
2663 * returned with chain->error and error-identifying information set. This
2664 * chain will assert if you try to do anything fancy with it.
2666 * XXX Depending on where the error occurs we should allow continued iteration.
2668 * parent must be locked on entry and remains locked throughout. chain's
2669 * lock status must match flags. Chain is always at least referenced.
2671 * WARNING! The MATCHIND flag does not apply to this function.
2674 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2675 hammer2_key_t *key_nextp,
2676 hammer2_key_t key_beg, hammer2_key_t key_end,
2677 int *errorp, int flags)
2679 hammer2_chain_t *parent;
2683 * Calculate locking flags for upward recursion.
2685 how_maybe = HAMMER2_RESOLVE_MAYBE;
2686 if (flags & HAMMER2_LOOKUP_SHARED)
2687 how_maybe |= HAMMER2_RESOLVE_SHARED;
2693 * Calculate the next index and recalculate the parent if necessary.
2696 key_beg = chain->bref.key +
2697 ((hammer2_key_t)1 << chain->bref.keybits);
2698 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2699 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2700 hammer2_chain_unlock(chain);
2702 hammer2_chain_drop(chain);
2705 * chain invalid past this point, but we can still do a
2706 * pointer comparison w/parent.
2708 * Any scan where the lookup returned degenerate data embedded
2709 * in the inode has an invalid index and must terminate.
2711 if (chain == parent)
2713 if (key_beg == 0 || key_beg > key_end)
2716 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2717 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2719 * We reached the end of the iteration.
2724 * Continue iteration with next parent unless the current
2725 * parent covers the range.
2727 * (This also handles the case of a deleted, empty indirect
2730 key_beg = parent->bref.key +
2731 ((hammer2_key_t)1 << parent->bref.keybits);
2732 if (key_beg == 0 || key_beg > key_end)
2734 parent = hammer2_chain_repparent(parentp, how_maybe);
2740 return (hammer2_chain_lookup(parentp, key_nextp,
2746 * Caller wishes to iterate chains under parent, loading new chains into
2747 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
2748 * then call hammer2_chain_scan() repeatedly until a non-zero return.
2749 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
2750 * with the returned chain for the scan. The returned *chainp will be
2751 * locked and referenced. Any prior contents will be unlocked and dropped.
2753 * Caller should check the return value. A normal scan EOF will return
2754 * exactly HAMMER2_ERROR_EOF. Any other non-zero value indicates an
2755 * error trying to access parent data. Any error in the returned chain
2756 * must be tested separately by the caller.
2758 * (*chainp) is dropped on each scan, but will only be set if the returned
2759 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
2760 * returned via *chainp. The caller will get their bref only.
2762 * The raw scan function is similar to lookup/next but does not seek to a key.
2763 * Blockrefs are iterated via first_bref = (parent, NULL) and
2764 * next_chain = (parent, bref).
2766 * The passed-in parent must be locked and its data resolved. The function
2767 * nominally returns a locked and referenced *chainp != NULL for chains
2768 * the caller might need to recurse on (and will dipose of any *chainp passed
2769 * in). The caller must check the chain->bref.type either way.
2772 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2773 hammer2_blockref_t *bref, int *firstp,
2777 hammer2_blockref_t *base;
2778 hammer2_blockref_t *bref_ptr;
2780 hammer2_key_t next_key;
2781 hammer2_chain_t *chain = NULL;
2783 int how_always = HAMMER2_RESOLVE_ALWAYS;
2784 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2787 int maxloops = 300000;
2794 * Scan flags borrowed from lookup.
2796 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2797 how_maybe = how_always;
2798 how = HAMMER2_RESOLVE_ALWAYS;
2799 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2800 how = HAMMER2_RESOLVE_NEVER;
2802 how = HAMMER2_RESOLVE_MAYBE;
2804 if (flags & HAMMER2_LOOKUP_SHARED) {
2805 how_maybe |= HAMMER2_RESOLVE_SHARED;
2806 how_always |= HAMMER2_RESOLVE_SHARED;
2807 how |= HAMMER2_RESOLVE_SHARED;
2811 * Calculate key to locate first/next element, unlocking the previous
2812 * element as we go. Be careful, the key calculation can overflow.
2814 * (also reset bref to NULL)
2820 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2821 if ((chain = *chainp) != NULL) {
2823 hammer2_chain_unlock(chain);
2824 hammer2_chain_drop(chain);
2828 error |= HAMMER2_ERROR_EOF;
2834 if (parent->error) {
2835 error = parent->error;
2838 if (--maxloops == 0)
2839 panic("hammer2_chain_scan: maxloops");
2842 * Locate the blockref array. Currently we do a fully associative
2843 * search through the array.
2845 switch(parent->bref.type) {
2846 case HAMMER2_BREF_TYPE_INODE:
2848 * An inode with embedded data has no sub-chains.
2850 * WARNING! Bulk scan code may pass a static chain marked
2851 * as BREF_TYPE_INODE with a copy of the volume
2852 * root blockset to snapshot the volume.
2854 if (parent->data->ipdata.meta.op_flags &
2855 HAMMER2_OPFLAG_DIRECTDATA) {
2856 error |= HAMMER2_ERROR_EOF;
2859 base = &parent->data->ipdata.u.blockset.blockref[0];
2860 count = HAMMER2_SET_COUNT;
2862 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2863 case HAMMER2_BREF_TYPE_INDIRECT:
2865 * Optimize indirect blocks in the INITIAL state to avoid
2868 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2871 if (parent->data == NULL)
2872 panic("parent->data is NULL");
2873 base = &parent->data->npdata[0];
2875 count = parent->bytes / sizeof(hammer2_blockref_t);
2877 case HAMMER2_BREF_TYPE_VOLUME:
2878 base = &parent->data->voldata.sroot_blockset.blockref[0];
2879 count = HAMMER2_SET_COUNT;
2881 case HAMMER2_BREF_TYPE_FREEMAP:
2882 base = &parent->data->blkset.blockref[0];
2883 count = HAMMER2_SET_COUNT;
2886 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2888 base = NULL; /* safety */
2889 count = 0; /* safety */
2893 * Merged scan to find next candidate.
2895 * hammer2_base_*() functions require the parent->core.live_* fields
2896 * to be synchronized.
2898 * We need to hold the spinlock to access the block array and RB tree
2899 * and to interlock chain creation.
2901 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2902 hammer2_chain_countbrefs(parent, base, count);
2906 hammer2_spin_ex(&parent->core.spin);
2907 chain = hammer2_combined_find(parent, base, count,
2909 key, HAMMER2_KEY_MAX,
2911 generation = parent->core.generation;
2914 * Exhausted parent chain, we're done.
2916 if (bref_ptr == NULL) {
2917 hammer2_spin_unex(&parent->core.spin);
2918 KKASSERT(chain == NULL);
2919 error |= HAMMER2_ERROR_EOF;
2924 * Copy into the supplied stack-based blockref.
2929 * Selected from blockref or in-memory chain.
2931 if (chain == NULL) {
2932 switch(bref->type) {
2933 case HAMMER2_BREF_TYPE_INODE:
2934 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2935 case HAMMER2_BREF_TYPE_INDIRECT:
2936 case HAMMER2_BREF_TYPE_VOLUME:
2937 case HAMMER2_BREF_TYPE_FREEMAP:
2939 * Recursion, always get the chain
2941 hammer2_spin_unex(&parent->core.spin);
2942 chain = hammer2_chain_get(parent, generation, bref);
2943 if (chain == NULL) {
2944 kprintf("retry scan parent %p keys %016jx\n",
2948 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2949 hammer2_chain_drop(chain);
2956 * No recursion, do not waste time instantiating
2957 * a chain, just iterate using the bref.
2959 hammer2_spin_unex(&parent->core.spin);
2964 * Recursion or not we need the chain in order to supply
2967 hammer2_chain_ref(chain);
2968 hammer2_spin_unex(&parent->core.spin);
2972 * chain is referenced but not locked. We must lock the chain
2973 * to obtain definitive state.
2976 hammer2_chain_lock(chain, how);
2979 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2981 * NOTE: chain's key range is not relevant as there might be
2982 * one-offs within the range that are not deleted.
2984 * NOTE: XXX this could create problems with scans used in
2985 * situations other than mount-time recovery.
2987 * NOTE: Lookups can race delete-duplicate because
2988 * delete-duplicate does not lock the parent's core
2989 * (they just use the spinlock on the core).
2991 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2992 hammer2_chain_unlock(chain);
2993 hammer2_chain_drop(chain);
2998 error |= HAMMER2_ERROR_EOF;
3006 * All done, return the bref or NULL, supply chain if necessary.
3014 * Create and return a new hammer2 system memory structure of the specified
3015 * key, type and size and insert it under (*parentp). This is a full
3016 * insertion, based on the supplied key/keybits, and may involve creating
3017 * indirect blocks and moving other chains around via delete/duplicate.
3019 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3020 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3021 * FULL. This typically means that the caller is creating the chain after
3022 * doing a hammer2_chain_lookup().
3024 * (*parentp) must be exclusive locked and may be replaced on return
3025 * depending on how much work the function had to do.
3027 * (*parentp) must not be errored or this function will assert.
3029 * (*chainp) usually starts out NULL and returns the newly created chain,
3030 * but if the caller desires the caller may allocate a disconnected chain
3031 * and pass it in instead.
3033 * This function should NOT be used to insert INDIRECT blocks. It is
3034 * typically used to create/insert inodes and data blocks.
3036 * Caller must pass-in an exclusively locked parent the new chain is to
3037 * be inserted under, and optionally pass-in a disconnected, exclusively
3038 * locked chain to insert (else we create a new chain). The function will
3039 * adjust (*parentp) as necessary, create or connect the chain, and
3040 * return an exclusively locked chain in *chainp.
3042 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3043 * and will be reassigned.
3045 * NOTE: returns HAMMER_ERROR_* flags
3048 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3049 hammer2_pfs_t *pmp, int methods,
3050 hammer2_key_t key, int keybits, int type, size_t bytes,
3051 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3054 hammer2_chain_t *chain;
3055 hammer2_chain_t *parent;
3056 hammer2_blockref_t *base;
3057 hammer2_blockref_t dummy;
3061 int maxloops = 300000;
3064 * Topology may be crossing a PFS boundary.
3067 KKASSERT(hammer2_mtx_owned(&parent->lock));
3068 KKASSERT(parent->error == 0);
3072 if (chain == NULL) {
3074 * First allocate media space and construct the dummy bref,
3075 * then allocate the in-memory chain structure. Set the
3076 * INITIAL flag for fresh chains which do not have embedded
3079 * XXX for now set the check mode of the child based on
3080 * the parent or, if the parent is an inode, the
3081 * specification in the inode.
3083 bzero(&dummy, sizeof(dummy));
3086 dummy.keybits = keybits;
3087 dummy.data_off = hammer2_getradix(bytes);
3090 * Inherit methods from parent by default. Primarily used
3091 * for BREF_TYPE_DATA. Non-data types *must* be set to
3092 * a non-NONE check algorithm.
3095 dummy.methods = parent->bref.methods;
3097 dummy.methods = (uint8_t)methods;
3099 if (type != HAMMER2_BREF_TYPE_DATA &&
3100 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3102 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3105 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3108 * Lock the chain manually, chain_lock will load the chain
3109 * which we do NOT want to do. (note: chain->refs is set
3110 * to 1 by chain_alloc() for us, but lockcnt is not).
3113 hammer2_mtx_ex(&chain->lock);
3115 ++curthread->td_tracker;
3118 * Set INITIAL to optimize I/O. The flag will generally be
3119 * processed when we call hammer2_chain_modify().
3121 * Recalculate bytes to reflect the actual media block
3122 * allocation. Handle special case radix 0 == 0 bytes.
3124 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3126 bytes = (hammer2_off_t)1 << bytes;
3127 chain->bytes = bytes;
3130 case HAMMER2_BREF_TYPE_VOLUME:
3131 case HAMMER2_BREF_TYPE_FREEMAP:
3132 panic("hammer2_chain_create: called with volume type");
3134 case HAMMER2_BREF_TYPE_INDIRECT:
3135 panic("hammer2_chain_create: cannot be used to"
3136 "create indirect block");
3138 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3139 panic("hammer2_chain_create: cannot be used to"
3140 "create freemap root or node");
3142 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3143 KKASSERT(bytes == sizeof(chain->data->bmdata));
3145 case HAMMER2_BREF_TYPE_DIRENT:
3146 case HAMMER2_BREF_TYPE_INODE:
3147 case HAMMER2_BREF_TYPE_DATA:
3150 * leave chain->data NULL, set INITIAL
3152 KKASSERT(chain->data == NULL);
3153 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3158 * We are reattaching a previously deleted chain, possibly
3159 * under a new parent and possibly with a new key/keybits.
3160 * The chain does not have to be in a modified state. The
3161 * UPDATE flag will be set later on in this routine.
3163 * Do NOT mess with the current state of the INITIAL flag.
3165 chain->bref.key = key;
3166 chain->bref.keybits = keybits;
3167 if (chain->flags & HAMMER2_CHAIN_DELETED)
3168 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3169 KKASSERT(chain->parent == NULL);
3171 if (flags & HAMMER2_INSERT_PFSROOT)
3172 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3174 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3177 * Calculate how many entries we have in the blockref array and
3178 * determine if an indirect block is required.
3181 if (--maxloops == 0)
3182 panic("hammer2_chain_create: maxloops");
3184 switch(parent->bref.type) {
3185 case HAMMER2_BREF_TYPE_INODE:
3186 if ((parent->data->ipdata.meta.op_flags &
3187 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3188 kprintf("hammer2: parent set for direct-data! "
3189 "pkey=%016jx ckey=%016jx\n",
3193 KKASSERT((parent->data->ipdata.meta.op_flags &
3194 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3195 KKASSERT(parent->data != NULL);
3196 base = &parent->data->ipdata.u.blockset.blockref[0];
3197 count = HAMMER2_SET_COUNT;
3199 case HAMMER2_BREF_TYPE_INDIRECT:
3200 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3201 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3204 base = &parent->data->npdata[0];
3205 count = parent->bytes / sizeof(hammer2_blockref_t);
3207 case HAMMER2_BREF_TYPE_VOLUME:
3208 KKASSERT(parent->data != NULL);
3209 base = &parent->data->voldata.sroot_blockset.blockref[0];
3210 count = HAMMER2_SET_COUNT;
3212 case HAMMER2_BREF_TYPE_FREEMAP:
3213 KKASSERT(parent->data != NULL);
3214 base = &parent->data->blkset.blockref[0];
3215 count = HAMMER2_SET_COUNT;
3218 panic("hammer2_chain_create: unrecognized blockref type: %d",
3226 * Make sure we've counted the brefs
3228 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3229 hammer2_chain_countbrefs(parent, base, count);
3231 KASSERT(parent->core.live_count >= 0 &&
3232 parent->core.live_count <= count,
3233 ("bad live_count %d/%d (%02x, %d)",
3234 parent->core.live_count, count,
3235 parent->bref.type, parent->bytes));
3238 * If no free blockref could be found we must create an indirect
3239 * block and move a number of blockrefs into it. With the parent
3240 * locked we can safely lock each child in order to delete+duplicate
3241 * it without causing a deadlock.
3243 * This may return the new indirect block or the old parent depending
3244 * on where the key falls. NULL is returned on error.
3246 if (parent->core.live_count == count) {
3247 hammer2_chain_t *nparent;
3249 KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3251 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3252 mtid, type, &error);
3253 if (nparent == NULL) {
3255 hammer2_chain_drop(chain);
3259 if (parent != nparent) {
3260 hammer2_chain_unlock(parent);
3261 hammer2_chain_drop(parent);
3262 parent = *parentp = nparent;
3267 if (chain->flags & HAMMER2_CHAIN_DELETED)
3268 kprintf("Inserting deleted chain @%016jx\n",
3272 * Link the chain into its parent.
3274 if (chain->parent != NULL)
3275 panic("hammer2: hammer2_chain_create: chain already connected");
3276 KKASSERT(chain->parent == NULL);
3277 KKASSERT(parent->core.live_count < count);
3278 hammer2_chain_insert(parent, chain,
3279 HAMMER2_CHAIN_INSERT_SPIN |
3280 HAMMER2_CHAIN_INSERT_LIVE,
3285 * Mark the newly created chain modified. This will cause
3286 * UPDATE to be set and process the INITIAL flag.
3288 * Device buffers are not instantiated for DATA elements
3289 * as these are handled by logical buffers.
3291 * Indirect and freemap node indirect blocks are handled
3292 * by hammer2_chain_create_indirect() and not by this
3295 * Data for all other bref types is expected to be
3296 * instantiated (INODE, LEAF).
3298 switch(chain->bref.type) {
3299 case HAMMER2_BREF_TYPE_DATA:
3300 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3301 case HAMMER2_BREF_TYPE_DIRENT:
3302 case HAMMER2_BREF_TYPE_INODE:
3303 error = hammer2_chain_modify(chain, mtid, dedup_off,
3304 HAMMER2_MODIFY_OPTDATA);
3308 * Remaining types are not supported by this function.
3309 * In particular, INDIRECT and LEAF_NODE types are
3310 * handled by create_indirect().
3312 panic("hammer2_chain_create: bad type: %d",
3319 * When reconnecting a chain we must set UPDATE and
3320 * setflush so the flush recognizes that it must update
3321 * the bref in the parent.
3323 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3324 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3328 * We must setflush(parent) to ensure that it recurses through to
3329 * chain. setflush(chain) might not work because ONFLUSH is possibly
3330 * already set in the chain (so it won't recurse up to set it in the
3333 hammer2_chain_setflush(parent);
3342 * Move the chain from its old parent to a new parent. The chain must have
3343 * already been deleted or already disconnected (or never associated) with
3344 * a parent. The chain is reassociated with the new parent and the deleted
3345 * flag will be cleared (no longer deleted). The chain's modification state
3348 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3349 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3350 * FULL. This typically means that the caller is creating the chain after
3351 * doing a hammer2_chain_lookup().
3353 * A non-NULL bref is typically passed when key and keybits must be overridden.
3354 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3355 * from a passed-in bref and uses the old chain's bref for everything else.
3357 * Neither (parent) or (chain) can be errored.
3359 * If (parent) is non-NULL then the chain is inserted under the parent.
3361 * If (parent) is NULL then the newly duplicated chain is not inserted
3362 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3363 * passing into hammer2_chain_create() after this function returns).
3365 * WARNING! This function calls create which means it can insert indirect
3366 * blocks. This can cause other unrelated chains in the parent to
3367 * be moved to a newly inserted indirect block in addition to the
3371 hammer2_chain_rename(hammer2_blockref_t *bref,
3372 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3373 hammer2_tid_t mtid, int flags)
3376 hammer2_chain_t *parent;
3380 * WARNING! We should never resolve DATA to device buffers
3381 * (XXX allow it if the caller did?), and since
3382 * we currently do not have the logical buffer cache
3383 * buffer in-hand to fix its cached physical offset
3384 * we also force the modify code to not COW it. XXX
3387 KKASSERT(chain->parent == NULL);
3388 KKASSERT(chain->error == 0);
3391 * Now create a duplicate of the chain structure, associating
3392 * it with the same core, making it the same size, pointing it
3393 * to the same bref (the same media block).
3395 * NOTE: Handle special radix == 0 case (means 0 bytes).
3398 bref = &chain->bref;
3399 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3401 bytes = (hammer2_off_t)1 << bytes;
3404 * If parent is not NULL the duplicated chain will be entered under
3405 * the parent and the UPDATE bit set to tell flush to update
3408 * We must setflush(parent) to ensure that it recurses through to
3409 * chain. setflush(chain) might not work because ONFLUSH is possibly
3410 * already set in the chain (so it won't recurse up to set it in the
3413 * Having both chains locked is extremely important for atomicy.
3415 if (parentp && (parent = *parentp) != NULL) {
3416 KKASSERT(hammer2_mtx_owned(&parent->lock));
3417 KKASSERT(parent->refs > 0);
3418 KKASSERT(parent->error == 0);
3420 hammer2_chain_create(parentp, &chain,
3421 chain->pmp, HAMMER2_METH_DEFAULT,
3422 bref->key, bref->keybits, bref->type,
3423 chain->bytes, mtid, 0, flags);
3424 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3425 hammer2_chain_setflush(*parentp);
3430 * Helper function for deleting chains.
3432 * The chain is removed from the live view (the RBTREE) as well as the parent's
3433 * blockmap. Both chain and its parent must be locked.
3435 * parent may not be errored. chain can be errored.
3438 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3439 hammer2_tid_t mtid, int flags)
3444 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3445 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3446 KKASSERT(chain->parent == parent);
3449 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3451 * Chain is blockmapped, so there must be a parent.
3452 * Atomically remove the chain from the parent and remove
3453 * the blockmap entry. The parent must be set modified
3454 * to remove the blockmap entry.
3456 hammer2_blockref_t *base;
3459 KKASSERT(parent != NULL);
3460 KKASSERT(parent->error == 0);
3461 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3462 error = hammer2_chain_modify(parent, mtid, 0, 0);
3467 * Calculate blockmap pointer
3469 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3470 hammer2_spin_ex(&chain->core.spin);
3471 hammer2_spin_ex(&parent->core.spin);
3473 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3474 atomic_add_int(&parent->core.live_count, -1);
3475 ++parent->core.generation;
3476 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3477 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3478 --parent->core.chain_count;
3479 chain->parent = NULL;
3481 switch(parent->bref.type) {
3482 case HAMMER2_BREF_TYPE_INODE:
3484 * Access the inode's block array. However, there
3485 * is no block array if the inode is flagged
3489 (parent->data->ipdata.meta.op_flags &
3490 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3492 &parent->data->ipdata.u.blockset.blockref[0];
3496 count = HAMMER2_SET_COUNT;
3498 case HAMMER2_BREF_TYPE_INDIRECT:
3499 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3501 base = &parent->data->npdata[0];
3504 count = parent->bytes / sizeof(hammer2_blockref_t);
3506 case HAMMER2_BREF_TYPE_VOLUME:
3507 base = &parent->data->voldata.
3508 sroot_blockset.blockref[0];
3509 count = HAMMER2_SET_COUNT;
3511 case HAMMER2_BREF_TYPE_FREEMAP:
3512 base = &parent->data->blkset.blockref[0];
3513 count = HAMMER2_SET_COUNT;
3518 panic("hammer2_flush_pass2: "
3519 "unrecognized blockref type: %d",
3524 * delete blockmapped chain from its parent.
3526 * The parent is not affected by any statistics in chain
3527 * which are pending synchronization. That is, there is
3528 * nothing to undo in the parent since they have not yet
3529 * been incorporated into the parent.
3531 * The parent is affected by statistics stored in inodes.
3532 * Those have already been synchronized, so they must be
3533 * undone. XXX split update possible w/delete in middle?
3536 hammer2_base_delete(parent, base, count, chain);
3538 hammer2_spin_unex(&parent->core.spin);
3539 hammer2_spin_unex(&chain->core.spin);
3540 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3542 * Chain is not blockmapped but a parent is present.
3543 * Atomically remove the chain from the parent. There is
3544 * no blockmap entry to remove.
3546 * Because chain was associated with a parent but not
3547 * synchronized, the chain's *_count_up fields contain
3548 * inode adjustment statistics which must be undone.
3550 hammer2_spin_ex(&chain->core.spin);
3551 hammer2_spin_ex(&parent->core.spin);
3552 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3553 atomic_add_int(&parent->core.live_count, -1);
3554 ++parent->core.generation;
3555 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3556 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3557 --parent->core.chain_count;
3558 chain->parent = NULL;
3559 hammer2_spin_unex(&parent->core.spin);
3560 hammer2_spin_unex(&chain->core.spin);
3563 * Chain is not blockmapped and has no parent. This
3564 * is a degenerate case.
3566 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3573 * Create an indirect block that covers one or more of the elements in the
3574 * current parent. Either returns the existing parent with no locking or
3575 * ref changes or returns the new indirect block locked and referenced
3576 * and leaving the original parent lock/ref intact as well.
3578 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3580 * The returned chain depends on where the specified key falls.
3582 * The key/keybits for the indirect mode only needs to follow three rules:
3584 * (1) That all elements underneath it fit within its key space and
3586 * (2) That all elements outside it are outside its key space.
3588 * (3) When creating the new indirect block any elements in the current
3589 * parent that fit within the new indirect block's keyspace must be
3590 * moved into the new indirect block.
3592 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3593 * keyspace the the current parent, but lookup/iteration rules will
3594 * ensure (and must ensure) that rule (2) for all parents leading up
3595 * to the nearest inode or the root volume header is adhered to. This
3596 * is accomplished by always recursing through matching keyspaces in
3597 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3599 * The current implementation calculates the current worst-case keyspace by
3600 * iterating the current parent and then divides it into two halves, choosing
3601 * whichever half has the most elements (not necessarily the half containing
3602 * the requested key).
3604 * We can also opt to use the half with the least number of elements. This
3605 * causes lower-numbered keys (aka logical file offsets) to recurse through
3606 * fewer indirect blocks and higher-numbered keys to recurse through more.
3607 * This also has the risk of not moving enough elements to the new indirect
3608 * block and being forced to create several indirect blocks before the element
3611 * Must be called with an exclusively locked parent.
3613 * NOTE: *errorp set to HAMMER_ERROR_* flags
3615 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3616 hammer2_key_t *keyp, int keybits,
3617 hammer2_blockref_t *base, int count);
3618 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3619 hammer2_key_t *keyp, int keybits,
3620 hammer2_blockref_t *base, int count,
3622 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3623 hammer2_key_t *keyp, int keybits,
3624 hammer2_blockref_t *base, int count,
3628 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3629 hammer2_key_t create_key, int create_bits,
3630 hammer2_tid_t mtid, int for_type, int *errorp)
3633 hammer2_blockref_t *base;
3634 hammer2_blockref_t *bref;
3635 hammer2_blockref_t bcopy;
3636 hammer2_chain_t *chain;
3637 hammer2_chain_t *ichain;
3638 hammer2_chain_t dummy;
3639 hammer2_key_t key = create_key;
3640 hammer2_key_t key_beg;
3641 hammer2_key_t key_end;
3642 hammer2_key_t key_next;
3643 int keybits = create_bits;
3651 int maxloops = 300000;
3654 * Calculate the base blockref pointer or NULL if the chain
3655 * is known to be empty. We need to calculate the array count
3656 * for RB lookups either way.
3659 KKASSERT(hammer2_mtx_owned(&parent->lock));
3662 * Pre-modify the parent now to avoid having to deal with error
3663 * processing if we tried to later (in the middle of our loop).
3665 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3667 kprintf("hammer2_create_indirect: error %08x %s\n",
3668 *errorp, hammer2_error_str(*errorp));
3672 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3673 base = hammer2_chain_base_and_count(parent, &count);
3676 * dummy used in later chain allocation (no longer used for lookups).
3678 bzero(&dummy, sizeof(dummy));
3681 * How big should our new indirect block be? It has to be at least
3682 * as large as its parent for splits to work properly.
3684 * The freemap uses a specific indirect block size. The number of
3685 * levels are built dynamically and ultimately depend on the size
3686 * volume. Because freemap blocks are taken from the reserved areas
3687 * of the volume our goal is efficiency (fewer levels) and not so
3688 * much to save disk space.
3690 * The first indirect block level for a directory usually uses
3691 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3692 * the hash mechanism, this typically gives us a nominal
3693 * 32 * 4 entries with one level of indirection.
3695 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3696 * indirect blocks. The initial 4 entries in the inode gives us
3697 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3698 * of indirection gives us 137GB, and so forth. H2 can support
3699 * huge file sizes but they are not typical, so we try to stick
3700 * with compactness and do not use a larger indirect block size.
3702 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3703 * due to the way indirect blocks are created this usually winds
3704 * up being extremely inefficient for small files. Even though
3705 * 16KB requires more levels of indirection for very large files,
3706 * the 16KB records can be ganged together into 64KB DIOs.
3708 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3709 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3710 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3711 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3712 if (parent->data->ipdata.meta.type ==
3713 HAMMER2_OBJTYPE_DIRECTORY)
3714 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3716 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3719 nbytes = HAMMER2_IND_BYTES_NOM;
3721 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3722 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3723 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3724 nbytes = count * sizeof(hammer2_blockref_t);
3726 ncount = nbytes / sizeof(hammer2_blockref_t);
3729 * When creating an indirect block for a freemap node or leaf
3730 * the key/keybits must be fitted to static radix levels because
3731 * particular radix levels use particular reserved blocks in the
3734 * This routine calculates the key/radix of the indirect block
3735 * we need to create, and whether it is on the high-side or the
3739 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3740 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3741 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3744 case HAMMER2_BREF_TYPE_DATA:
3745 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3746 base, count, ncount);
3748 case HAMMER2_BREF_TYPE_DIRENT:
3749 case HAMMER2_BREF_TYPE_INODE:
3750 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3751 base, count, ncount);
3754 panic("illegal indirect block for bref type %d", for_type);
3759 * Normalize the key for the radix being represented, keeping the
3760 * high bits and throwing away the low bits.
3762 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3765 * Ok, create our new indirect block
3767 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3768 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3769 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3771 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3773 dummy.bref.key = key;
3774 dummy.bref.keybits = keybits;
3775 dummy.bref.data_off = hammer2_getradix(nbytes);
3776 dummy.bref.methods =
3777 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3778 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3780 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3781 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3782 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3783 /* ichain has one ref at this point */
3786 * We have to mark it modified to allocate its block, but use
3787 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3788 * it won't be acted upon by the flush code.
3790 *errorp = hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3792 kprintf("hammer2_alloc_indirect: error %08x %s\n",
3793 *errorp, hammer2_error_str(*errorp));
3794 hammer2_chain_unlock(ichain);
3795 hammer2_chain_drop(ichain);
3800 * Iterate the original parent and move the matching brefs into
3801 * the new indirect block.
3803 * XXX handle flushes.
3806 key_end = HAMMER2_KEY_MAX;
3807 key_next = 0; /* avoid gcc warnings */
3808 hammer2_spin_ex(&parent->core.spin);
3814 * Parent may have been modified, relocating its block array.
3815 * Reload the base pointer.
3817 base = hammer2_chain_base_and_count(parent, &count);
3819 if (++loops > 100000) {
3820 hammer2_spin_unex(&parent->core.spin);
3821 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3822 reason, parent, base, count, key_next);
3826 * NOTE: spinlock stays intact, returned chain (if not NULL)
3827 * is not referenced or locked which means that we
3828 * cannot safely check its flagged / deletion status
3831 chain = hammer2_combined_find(parent, base, count,
3835 generation = parent->core.generation;
3838 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3841 * Skip keys that are not within the key/radix of the new
3842 * indirect block. They stay in the parent.
3844 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3845 (key ^ bref->key)) != 0) {
3846 goto next_key_spinlocked;
3850 * Load the new indirect block by acquiring the related
3851 * chains (potentially from media as it might not be
3852 * in-memory). Then move it to the new parent (ichain).
3854 * chain is referenced but not locked. We must lock the
3855 * chain to obtain definitive state.
3859 * Use chain already present in the RBTREE
3861 hammer2_chain_ref(chain);
3862 hammer2_spin_unex(&parent->core.spin);
3863 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3866 * Get chain for blockref element. _get returns NULL
3867 * on insertion race.
3870 hammer2_spin_unex(&parent->core.spin);
3871 chain = hammer2_chain_get(parent, generation, &bcopy);
3872 if (chain == NULL) {
3874 hammer2_spin_ex(&parent->core.spin);
3877 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3878 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3880 hammer2_chain_unlock(chain);
3881 hammer2_chain_drop(chain);
3882 hammer2_spin_ex(&parent->core.spin);
3888 * This is always live so if the chain has been deleted
3889 * we raced someone and we have to retry.
3891 * NOTE: Lookups can race delete-duplicate because
3892 * delete-duplicate does not lock the parent's core
3893 * (they just use the spinlock on the core).
3895 * (note reversed logic for this one)
3897 if (chain->parent != parent ||
3898 (chain->flags & HAMMER2_CHAIN_DELETED)) {
3899 hammer2_chain_unlock(chain);
3900 hammer2_chain_drop(chain);
3901 kprintf("hammer2_chain_create_indirect "
3902 "RETRY (%p,%p)->%p %08x\n",
3903 parent, chain->parent, chain, chain->flags);
3904 hammer2_spin_ex(&parent->core.spin);
3909 * Shift the chain to the indirect block.
3911 * WARNING! No reason for us to load chain data, pass NOSTATS
3912 * to prevent delete/insert from trying to access
3913 * inode stats (and thus asserting if there is no
3914 * chain->data loaded).
3916 * WARNING! The (parent, chain) deletion may modify the parent
3917 * and invalidate the base pointer.
3919 * WARNING! Parent must already be marked modified, so we
3920 * can assume that chain_delete always suceeds.
3922 error = hammer2_chain_delete(parent, chain, mtid, 0);
3923 KKASSERT(error == 0);
3924 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3925 hammer2_chain_unlock(chain);
3926 hammer2_chain_drop(chain);
3927 KKASSERT(parent->refs > 0);
3929 base = NULL; /* safety */
3930 hammer2_spin_ex(&parent->core.spin);
3931 next_key_spinlocked:
3932 if (--maxloops == 0)
3933 panic("hammer2_chain_create_indirect: maxloops");
3935 if (key_next == 0 || key_next > key_end)
3940 hammer2_spin_unex(&parent->core.spin);
3943 * Insert the new indirect block into the parent now that we've
3944 * cleared out some entries in the parent. We calculated a good
3945 * insertion index in the loop above (ichain->index).
3947 * We don't have to set UPDATE here because we mark ichain
3948 * modified down below (so the normal modified -> flush -> set-moved
3949 * sequence applies).
3951 * The insertion shouldn't race as this is a completely new block
3952 * and the parent is locked.
3954 base = NULL; /* safety, parent modify may change address */
3955 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3956 KKASSERT(parent->core.live_count < count);
3957 hammer2_chain_insert(parent, ichain,
3958 HAMMER2_CHAIN_INSERT_SPIN |
3959 HAMMER2_CHAIN_INSERT_LIVE,
3963 * Make sure flushes propogate after our manual insertion.
3965 hammer2_chain_setflush(ichain);
3966 hammer2_chain_setflush(parent);
3969 * Figure out what to return.
3971 if (~(((hammer2_key_t)1 << keybits) - 1) &
3972 (create_key ^ key)) {
3974 * Key being created is outside the key range,
3975 * return the original parent.
3977 hammer2_chain_unlock(ichain);
3978 hammer2_chain_drop(ichain);
3981 * Otherwise its in the range, return the new parent.
3982 * (leave both the new and old parent locked).
3991 * Do maintenance on an indirect chain. Both parent and chain are locked.
3993 * Returns non-zero if (chain) is deleted, either due to being empty or
3994 * because its children were safely moved into the parent.
3997 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
3998 hammer2_chain_t *chain)
4000 hammer2_blockref_t *chain_base;
4001 hammer2_blockref_t *base;
4002 hammer2_blockref_t *bref;
4003 hammer2_blockref_t bcopy;
4004 hammer2_key_t key_next;
4005 hammer2_key_t key_beg;
4006 hammer2_key_t key_end;
4007 hammer2_chain_t *sub;
4013 * Make sure we have an accurate live_count
4015 if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4016 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4017 base = &chain->data->npdata[0];
4018 count = chain->bytes / sizeof(hammer2_blockref_t);
4019 hammer2_chain_countbrefs(chain, base, count);
4023 * If the indirect block is empty we can delete it.
4025 if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4026 hammer2_chain_delete(parent, chain,
4027 chain->bref.modify_tid,
4028 HAMMER2_DELETE_PERMANENT);
4032 base = hammer2_chain_base_and_count(parent, &count);
4034 if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4035 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4036 hammer2_chain_countbrefs(parent, base, count);
4040 * Determine if we can collapse chain into parent, calculate
4041 * hysteresis for chain emptiness.
4043 if (parent->core.live_count + chain->core.live_count - 1 > count)
4045 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4046 if (chain->core.live_count > chain_count * 3 / 4)
4050 * Ok, theoretically we can collapse chain's contents into
4051 * parent. chain is locked, but any in-memory children of chain
4052 * are not. For this to work, we must be able to dispose of any
4053 * in-memory children of chain.
4055 * For now require that there are no in-memory children of chain.
4057 * WARNING! Both chain and parent must remain locked across this
4062 * Parent must be marked modified. Don't try to collapse it if we
4063 * can't mark it modified. Once modified, destroy chain to make room
4064 * and to get rid of what will be a conflicting key (this is included
4065 * in the calculation above). Finally, move the children of chain
4066 * into chain's parent.
4068 * This order creates an accounting problem for bref.embed.stats
4069 * because we destroy chain before we remove its children. Any
4070 * elements whos blockref is already synchronized will be counted
4071 * twice. To deal with the problem we clean out chain's stats prior
4074 if (hammer2_chain_modify(parent, 0, 0, 0)) {
4078 chain->bref.embed.stats.inode_count = 0;
4079 chain->bref.embed.stats.data_count = 0;
4080 hammer2_chain_delete(parent, chain,
4081 chain->bref.modify_tid,
4082 HAMMER2_DELETE_PERMANENT);
4085 * The combined_find call requires core.spin to be held. One would
4086 * think there wouldn't be any conflicts since we hold chain
4087 * exclusively locked, but the caching mechanism for 0-ref children
4088 * does not require a chain lock.
4090 hammer2_spin_ex(&chain->core.spin);
4094 key_end = HAMMER2_KEY_MAX;
4096 chain_base = &chain->data->npdata[0];
4097 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4098 sub = hammer2_combined_find(chain, chain_base, chain_count,
4102 generation = chain->core.generation;
4105 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4108 hammer2_chain_ref(sub);
4109 hammer2_spin_unex(&chain->core.spin);
4110 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4111 if (sub->parent != chain ||
4112 (sub->flags & HAMMER2_CHAIN_DELETED)) {
4113 hammer2_chain_unlock(sub);
4114 hammer2_chain_drop(sub);
4115 hammer2_spin_ex(&chain->core.spin);
4120 hammer2_spin_unex(&chain->core.spin);
4121 sub = hammer2_chain_get(chain, generation, &bcopy);
4123 hammer2_spin_ex(&chain->core.spin);
4126 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4127 if (bcmp(&bcopy, bref, sizeof(bcopy)) != 0) {
4128 hammer2_chain_unlock(sub);
4129 hammer2_chain_drop(sub);
4130 hammer2_spin_ex(&chain->core.spin);
4134 hammer2_chain_delete(chain, sub,
4135 sub->bref.modify_tid, 0);
4136 hammer2_chain_rename(NULL, &parent, sub,
4137 sub->bref.modify_tid,
4138 HAMMER2_INSERT_SAMEPARENT);
4139 hammer2_chain_unlock(sub);
4140 hammer2_chain_drop(sub);
4141 hammer2_spin_ex(&chain->core.spin);
4147 hammer2_spin_unex(&chain->core.spin);
4153 * Freemap indirect blocks
4155 * Calculate the keybits and highside/lowside of the freemap node the
4156 * caller is creating.
4158 * This routine will specify the next higher-level freemap key/radix
4159 * representing the lowest-ordered set. By doing so, eventually all
4160 * low-ordered sets will be moved one level down.
4162 * We have to be careful here because the freemap reserves a limited
4163 * number of blocks for a limited number of levels. So we can't just
4164 * push indiscriminately.
4167 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4168 int keybits, hammer2_blockref_t *base, int count)
4170 hammer2_chain_t *chain;
4171 hammer2_blockref_t *bref;
4173 hammer2_key_t key_beg;
4174 hammer2_key_t key_end;
4175 hammer2_key_t key_next;
4178 int maxloops = 300000;
4186 * Calculate the range of keys in the array being careful to skip
4187 * slots which are overridden with a deletion.
4190 key_end = HAMMER2_KEY_MAX;
4191 hammer2_spin_ex(&parent->core.spin);
4194 if (--maxloops == 0) {
4195 panic("indkey_freemap shit %p %p:%d\n",
4196 parent, base, count);
4198 chain = hammer2_combined_find(parent, base, count,
4210 * Skip deleted chains.
4212 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4213 if (key_next == 0 || key_next > key_end)
4220 * Use the full live (not deleted) element for the scan
4221 * iteration. HAMMER2 does not allow partial replacements.
4223 * XXX should be built into hammer2_combined_find().
4225 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4227 if (keybits > bref->keybits) {
4229 keybits = bref->keybits;
4230 } else if (keybits == bref->keybits && bref->key < key) {
4237 hammer2_spin_unex(&parent->core.spin);
4240 * Return the keybits for a higher-level FREEMAP_NODE covering
4244 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4245 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4247 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4248 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4250 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4251 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4253 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4254 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4256 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4257 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4259 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4260 panic("hammer2_chain_indkey_freemap: level too high");
4263 panic("hammer2_chain_indkey_freemap: bad radix");
4272 * File indirect blocks
4274 * Calculate the key/keybits for the indirect block to create by scanning
4275 * existing keys. The key being created is also passed in *keyp and can be
4276 * inside or outside the indirect block. Regardless, the indirect block
4277 * must hold at least two keys in order to guarantee sufficient space.
4279 * We use a modified version of the freemap's fixed radix tree, but taylored
4280 * for file data. Basically we configure an indirect block encompassing the
4284 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4285 int keybits, hammer2_blockref_t *base, int count,
4288 hammer2_chain_t *chain;
4289 hammer2_blockref_t *bref;
4291 hammer2_key_t key_beg;
4292 hammer2_key_t key_end;
4293 hammer2_key_t key_next;
4297 int maxloops = 300000;
4305 * Calculate the range of keys in the array being careful to skip
4306 * slots which are overridden with a deletion.
4308 * Locate the smallest key.
4311 key_end = HAMMER2_KEY_MAX;
4312 hammer2_spin_ex(&parent->core.spin);
4315 if (--maxloops == 0) {
4316 panic("indkey_freemap shit %p %p:%d\n",
4317 parent, base, count);
4319 chain = hammer2_combined_find(parent, base, count,
4331 * Skip deleted chains.
4333 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4334 if (key_next == 0 || key_next > key_end)
4341 * Use the full live (not deleted) element for the scan
4342 * iteration. HAMMER2 does not allow partial replacements.
4344 * XXX should be built into hammer2_combined_find().
4346 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4348 if (keybits > bref->keybits) {
4350 keybits = bref->keybits;
4351 } else if (keybits == bref->keybits && bref->key < key) {
4358 hammer2_spin_unex(&parent->core.spin);
4361 * Calculate the static keybits for a higher-level indirect block
4362 * that contains the key.
4367 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4368 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4370 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4371 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4373 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4374 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4377 panic("bad ncount %d\n", ncount);
4383 * The largest radix that can be returned for an indirect block is
4384 * 63 bits. (The largest practical indirect block radix is actually
4385 * 62 bits because the top-level inode or volume root contains four
4386 * entries, but allow 63 to be returned).
4391 return keybits + nradix;
4397 * Directory indirect blocks.
4399 * Covers both the inode index (directory of inodes), and directory contents
4400 * (filenames hardlinked to inodes).
4402 * Because directory keys are hashed we generally try to cut the space in
4403 * half. We accomodate the inode index (which tends to have linearly
4404 * increasing inode numbers) by ensuring that the keyspace is at least large
4405 * enough to fill up the indirect block being created.
4408 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4409 int keybits, hammer2_blockref_t *base, int count,
4412 hammer2_blockref_t *bref;
4413 hammer2_chain_t *chain;
4414 hammer2_key_t key_beg;
4415 hammer2_key_t key_end;
4416 hammer2_key_t key_next;
4421 int maxloops = 300000;
4424 * Shortcut if the parent is the inode. In this situation the
4425 * parent has 4+1 directory entries and we are creating an indirect
4426 * block capable of holding many more.
4428 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4437 * Calculate the range of keys in the array being careful to skip
4438 * slots which are overridden with a deletion.
4441 key_end = HAMMER2_KEY_MAX;
4442 hammer2_spin_ex(&parent->core.spin);
4445 if (--maxloops == 0) {
4446 panic("indkey_freemap shit %p %p:%d\n",
4447 parent, base, count);
4449 chain = hammer2_combined_find(parent, base, count,
4463 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4464 if (key_next == 0 || key_next > key_end)
4471 * Use the full live (not deleted) element for the scan
4472 * iteration. HAMMER2 does not allow partial replacements.
4474 * XXX should be built into hammer2_combined_find().
4476 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4479 * Expand our calculated key range (key, keybits) to fit
4480 * the scanned key. nkeybits represents the full range
4481 * that we will later cut in half (two halves @ nkeybits - 1).
4484 if (nkeybits < bref->keybits) {
4485 if (bref->keybits > 64) {
4486 kprintf("bad bref chain %p bref %p\n",
4490 nkeybits = bref->keybits;
4492 while (nkeybits < 64 &&
4493 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4494 (key ^ bref->key)) != 0) {
4499 * If the new key range is larger we have to determine
4500 * which side of the new key range the existing keys fall
4501 * under by checking the high bit, then collapsing the
4502 * locount into the hicount or vise-versa.
4504 if (keybits != nkeybits) {
4505 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4516 * The newly scanned key will be in the lower half or the
4517 * upper half of the (new) key range.
4519 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4528 hammer2_spin_unex(&parent->core.spin);
4529 bref = NULL; /* now invalid (safety) */
4532 * Adjust keybits to represent half of the full range calculated
4533 * above (radix 63 max) for our new indirect block.
4538 * Expand keybits to hold at least ncount elements. ncount will be
4539 * a power of 2. This is to try to completely fill leaf nodes (at
4540 * least for keys which are not hashes).
4542 * We aren't counting 'in' or 'out', we are counting 'high side'
4543 * and 'low side' based on the bit at (1LL << keybits). We want
4544 * everything to be inside in these cases so shift it all to
4545 * the low or high side depending on the new high bit.
4547 while (((hammer2_key_t)1 << keybits) < ncount) {
4549 if (key & ((hammer2_key_t)1 << keybits)) {
4558 if (hicount > locount)
4559 key |= (hammer2_key_t)1 << keybits;
4561 key &= ~(hammer2_key_t)1 << keybits;
4571 * Directory indirect blocks.
4573 * Covers both the inode index (directory of inodes), and directory contents
4574 * (filenames hardlinked to inodes).
4576 * Because directory keys are hashed we generally try to cut the space in
4577 * half. We accomodate the inode index (which tends to have linearly
4578 * increasing inode numbers) by ensuring that the keyspace is at least large
4579 * enough to fill up the indirect block being created.
4582 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4583 int keybits, hammer2_blockref_t *base, int count,
4586 hammer2_blockref_t *bref;
4587 hammer2_chain_t *chain;
4588 hammer2_key_t key_beg;
4589 hammer2_key_t key_end;
4590 hammer2_key_t key_next;
4595 int maxloops = 300000;
4598 * Shortcut if the parent is the inode. In this situation the
4599 * parent has 4+1 directory entries and we are creating an indirect
4600 * block capable of holding many more.
4602 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4611 * Calculate the range of keys in the array being careful to skip
4612 * slots which are overridden with a deletion.
4615 key_end = HAMMER2_KEY_MAX;
4616 hammer2_spin_ex(&parent->core.spin);
4619 if (--maxloops == 0) {
4620 panic("indkey_freemap shit %p %p:%d\n",
4621 parent, base, count);
4623 chain = hammer2_combined_find(parent, base, count,
4637 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4638 if (key_next == 0 || key_next > key_end)
4645 * Use the full live (not deleted) element for the scan
4646 * iteration. HAMMER2 does not allow partial replacements.
4648 * XXX should be built into hammer2_combined_find().
4650 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4653 * Expand our calculated key range (key, keybits) to fit
4654 * the scanned key. nkeybits represents the full range
4655 * that we will later cut in half (two halves @ nkeybits - 1).
4658 if (nkeybits < bref->keybits) {
4659 if (bref->keybits > 64) {
4660 kprintf("bad bref chain %p bref %p\n",
4664 nkeybits = bref->keybits;
4666 while (nkeybits < 64 &&
4667 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4668 (key ^ bref->key)) != 0) {
4673 * If the new key range is larger we have to determine
4674 * which side of the new key range the existing keys fall
4675 * under by checking the high bit, then collapsing the
4676 * locount into the hicount or vise-versa.
4678 if (keybits != nkeybits) {
4679 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4690 * The newly scanned key will be in the lower half or the
4691 * upper half of the (new) key range.
4693 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4702 hammer2_spin_unex(&parent->core.spin);
4703 bref = NULL; /* now invalid (safety) */
4706 * Adjust keybits to represent half of the full range calculated
4707 * above (radix 63 max) for our new indirect block.
4712 * Expand keybits to hold at least ncount elements. ncount will be
4713 * a power of 2. This is to try to completely fill leaf nodes (at
4714 * least for keys which are not hashes).
4716 * We aren't counting 'in' or 'out', we are counting 'high side'
4717 * and 'low side' based on the bit at (1LL << keybits). We want
4718 * everything to be inside in these cases so shift it all to
4719 * the low or high side depending on the new high bit.
4721 while (((hammer2_key_t)1 << keybits) < ncount) {
4723 if (key & ((hammer2_key_t)1 << keybits)) {
4732 if (hicount > locount)
4733 key |= (hammer2_key_t)1 << keybits;
4735 key &= ~(hammer2_key_t)1 << keybits;
4745 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4748 * Both parent and chain must be locked exclusively.
4750 * This function will modify the parent if the blockref requires removal
4751 * from the parent's block table.
4753 * This function is NOT recursive. Any entity already pushed into the
4754 * chain (such as an inode) may still need visibility into its contents,
4755 * as well as the ability to read and modify the contents. For example,
4756 * for an unlinked file which is still open.
4758 * Also note that the flusher is responsible for cleaning up empty
4762 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4763 hammer2_tid_t mtid, int flags)
4767 KKASSERT(hammer2_mtx_owned(&chain->lock));
4770 * Nothing to do if already marked.
4772 * We need the spinlock on the core whos RBTREE contains chain
4773 * to protect against races.
4775 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4776 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4777 chain->parent == parent);
4778 error = _hammer2_chain_delete_helper(parent, chain,
4783 * Permanent deletions mark the chain as destroyed.
4786 if (flags & HAMMER2_DELETE_PERMANENT)
4787 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4788 hammer2_chain_setflush(chain);
4795 * Returns the index of the nearest element in the blockref array >= elm.
4796 * Returns (count) if no element could be found.
4798 * Sets *key_nextp to the next key for loop purposes but does not modify
4799 * it if the next key would be higher than the current value of *key_nextp.
4800 * Note that *key_nexp can overflow to 0, which should be tested by the
4803 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4804 * held through the operation.
4807 hammer2_base_find(hammer2_chain_t *parent,
4808 hammer2_blockref_t *base, int count,
4809 hammer2_key_t *key_nextp,
4810 hammer2_key_t key_beg, hammer2_key_t key_end)
4812 hammer2_blockref_t *scan;
4813 hammer2_key_t scan_end;
4818 * Require the live chain's already have their core's counted
4819 * so we can optimize operations.
4821 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4826 if (count == 0 || base == NULL)
4830 * Sequential optimization using parent->cache_index. This is
4831 * the most likely scenario.
4833 * We can avoid trailing empty entries on live chains, otherwise
4834 * we might have to check the whole block array.
4836 i = parent->cache_index; /* SMP RACE OK */
4838 limit = parent->core.live_zero;
4843 KKASSERT(i < count);
4849 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4853 parent->cache_index = i;
4856 * Search forwards, stop when we find a scan element which
4857 * encloses the key or until we know that there are no further
4861 if (scan->type != 0) {
4862 scan_end = scan->key +
4863 ((hammer2_key_t)1 << scan->keybits) - 1;
4864 if (scan->key > key_beg || scan_end >= key_beg)
4873 parent->cache_index = i;
4877 scan_end = scan->key +
4878 ((hammer2_key_t)1 << scan->keybits);
4879 if (scan_end && (*key_nextp > scan_end ||
4881 *key_nextp = scan_end;
4889 * Do a combined search and return the next match either from the blockref
4890 * array or from the in-memory chain. Sets *bresp to the returned bref in
4891 * both cases, or sets it to NULL if the search exhausted. Only returns
4892 * a non-NULL chain if the search matched from the in-memory chain.
4894 * When no in-memory chain has been found and a non-NULL bref is returned
4898 * The returned chain is not locked or referenced. Use the returned bref
4899 * to determine if the search exhausted or not. Iterate if the base find
4900 * is chosen but matches a deleted chain.
4902 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4903 * held through the operation.
4906 hammer2_combined_find(hammer2_chain_t *parent,
4907 hammer2_blockref_t *base, int count,
4908 hammer2_key_t *key_nextp,
4909 hammer2_key_t key_beg, hammer2_key_t key_end,
4910 hammer2_blockref_t **bresp)
4912 hammer2_blockref_t *bref;
4913 hammer2_chain_t *chain;
4917 * Lookup in block array and in rbtree.
4919 *key_nextp = key_end + 1;
4920 i = hammer2_base_find(parent, base, count, key_nextp,
4922 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4927 if (i == count && chain == NULL) {
4933 * Only chain matched.
4936 bref = &chain->bref;
4941 * Only blockref matched.
4943 if (chain == NULL) {
4949 * Both in-memory and blockref matched, select the nearer element.
4951 * If both are flush with the left-hand side or both are the
4952 * same distance away, select the chain. In this situation the
4953 * chain must have been loaded from the matching blockmap.
4955 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4956 chain->bref.key == base[i].key) {
4957 KKASSERT(chain->bref.key == base[i].key);
4958 bref = &chain->bref;
4963 * Select the nearer key
4965 if (chain->bref.key < base[i].key) {
4966 bref = &chain->bref;
4973 * If the bref is out of bounds we've exhausted our search.
4976 if (bref->key > key_end) {
4986 * Locate the specified block array element and delete it. The element
4989 * The spin lock on the related chain must be held.
4991 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4992 * need to be adjusted when we commit the media change.
4995 hammer2_base_delete(hammer2_chain_t *parent,
4996 hammer2_blockref_t *base, int count,
4997 hammer2_chain_t *chain)
4999 hammer2_blockref_t *elm = &chain->bref;
5000 hammer2_blockref_t *scan;
5001 hammer2_key_t key_next;
5005 * Delete element. Expect the element to exist.
5007 * XXX see caller, flush code not yet sophisticated enough to prevent
5008 * re-flushed in some cases.
5010 key_next = 0; /* max range */
5011 i = hammer2_base_find(parent, base, count, &key_next,
5012 elm->key, elm->key);
5014 if (i == count || scan->type == 0 ||
5015 scan->key != elm->key ||
5016 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
5017 scan->keybits != elm->keybits)) {
5018 hammer2_spin_unex(&parent->core.spin);
5019 panic("delete base %p element not found at %d/%d elm %p\n",
5020 base, i, count, elm);
5025 * Update stats and zero the entry.
5027 * NOTE: Handle radix == 0 (0 bytes) case.
5029 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5030 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5031 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5033 switch(scan->type) {
5034 case HAMMER2_BREF_TYPE_INODE:
5035 --parent->bref.embed.stats.inode_count;
5037 case HAMMER2_BREF_TYPE_DATA:
5038 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5039 atomic_set_int(&chain->flags,
5040 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5042 if (parent->bref.leaf_count)
5043 --parent->bref.leaf_count;
5046 case HAMMER2_BREF_TYPE_INDIRECT:
5047 if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5048 parent->bref.embed.stats.data_count -=
5049 scan->embed.stats.data_count;
5050 parent->bref.embed.stats.inode_count -=
5051 scan->embed.stats.inode_count;
5053 if (scan->type == HAMMER2_BREF_TYPE_INODE)
5055 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5056 atomic_set_int(&chain->flags,
5057 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5059 if (parent->bref.leaf_count <= scan->leaf_count)
5060 parent->bref.leaf_count = 0;
5062 parent->bref.leaf_count -= scan->leaf_count;
5065 case HAMMER2_BREF_TYPE_DIRENT:
5066 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5067 atomic_set_int(&chain->flags,
5068 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5070 if (parent->bref.leaf_count)
5071 --parent->bref.leaf_count;
5077 bzero(scan, sizeof(*scan));
5080 * We can only optimize parent->core.live_zero for live chains.
5082 if (parent->core.live_zero == i + 1) {
5083 while (--i >= 0 && base[i].type == 0)
5085 parent->core.live_zero = i + 1;
5089 * Clear appropriate blockmap flags in chain.
5091 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
5092 HAMMER2_CHAIN_BMAPUPD);
5096 * Insert the specified element. The block array must not already have the
5097 * element and must have space available for the insertion.
5099 * The spin lock on the related chain must be held.
5101 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5102 * need to be adjusted when we commit the media change.
5105 hammer2_base_insert(hammer2_chain_t *parent,
5106 hammer2_blockref_t *base, int count,
5107 hammer2_chain_t *chain, hammer2_blockref_t *elm)
5109 hammer2_key_t key_next;
5118 * Insert new element. Expect the element to not already exist
5119 * unless we are replacing it.
5121 * XXX see caller, flush code not yet sophisticated enough to prevent
5122 * re-flushed in some cases.
5124 key_next = 0; /* max range */
5125 i = hammer2_base_find(parent, base, count, &key_next,
5126 elm->key, elm->key);
5129 * Shortcut fill optimization, typical ordered insertion(s) may not
5132 KKASSERT(i >= 0 && i <= count);
5135 * Set appropriate blockmap flags in chain (if not NULL)
5138 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
5141 * Update stats and zero the entry
5143 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5144 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5145 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5148 case HAMMER2_BREF_TYPE_INODE:
5149 ++parent->bref.embed.stats.inode_count;
5151 case HAMMER2_BREF_TYPE_DATA:
5152 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5153 ++parent->bref.leaf_count;
5155 case HAMMER2_BREF_TYPE_INDIRECT:
5156 if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5157 parent->bref.embed.stats.data_count +=
5158 elm->embed.stats.data_count;
5159 parent->bref.embed.stats.inode_count +=
5160 elm->embed.stats.inode_count;
5162 if (elm->type == HAMMER2_BREF_TYPE_INODE)
5164 if (parent->bref.leaf_count + elm->leaf_count <
5165 HAMMER2_BLOCKREF_LEAF_MAX) {
5166 parent->bref.leaf_count += elm->leaf_count;
5168 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5171 case HAMMER2_BREF_TYPE_DIRENT:
5172 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5173 ++parent->bref.leaf_count;
5181 * We can only optimize parent->core.live_zero for live chains.
5183 if (i == count && parent->core.live_zero < count) {
5184 i = parent->core.live_zero++;
5189 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5190 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5191 hammer2_spin_unex(&parent->core.spin);
5192 panic("insert base %p overlapping elements at %d elm %p\n",
5197 * Try to find an empty slot before or after.
5201 while (j > 0 || k < count) {
5203 if (j >= 0 && base[j].type == 0) {
5207 bcopy(&base[j+1], &base[j],
5208 (i - j - 1) * sizeof(*base));
5214 if (k < count && base[k].type == 0) {
5215 bcopy(&base[i], &base[i+1],
5216 (k - i) * sizeof(hammer2_blockref_t));
5220 * We can only update parent->core.live_zero for live
5223 if (parent->core.live_zero <= k)
5224 parent->core.live_zero = k + 1;
5229 panic("hammer2_base_insert: no room!");
5236 for (l = 0; l < count; ++l) {
5238 key_next = base[l].key +
5239 ((hammer2_key_t)1 << base[l].keybits) - 1;
5243 while (++l < count) {
5245 if (base[l].key <= key_next)
5246 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5247 key_next = base[l].key +
5248 ((hammer2_key_t)1 << base[l].keybits) - 1;
5258 * Sort the blockref array for the chain. Used by the flush code to
5259 * sort the blockref[] array.
5261 * The chain must be exclusively locked AND spin-locked.
5263 typedef hammer2_blockref_t *hammer2_blockref_p;
5267 hammer2_base_sort_callback(const void *v1, const void *v2)
5269 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5270 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5273 * Make sure empty elements are placed at the end of the array
5275 if (bref1->type == 0) {
5276 if (bref2->type == 0)
5279 } else if (bref2->type == 0) {
5286 if (bref1->key < bref2->key)
5288 if (bref1->key > bref2->key)
5294 hammer2_base_sort(hammer2_chain_t *chain)
5296 hammer2_blockref_t *base;
5299 switch(chain->bref.type) {
5300 case HAMMER2_BREF_TYPE_INODE:
5302 * Special shortcut for embedded data returns the inode
5303 * itself. Callers must detect this condition and access
5304 * the embedded data (the strategy code does this for us).
5306 * This is only applicable to regular files and softlinks.
5308 if (chain->data->ipdata.meta.op_flags &
5309 HAMMER2_OPFLAG_DIRECTDATA) {
5312 base = &chain->data->ipdata.u.blockset.blockref[0];
5313 count = HAMMER2_SET_COUNT;
5315 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5316 case HAMMER2_BREF_TYPE_INDIRECT:
5318 * Optimize indirect blocks in the INITIAL state to avoid
5321 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5322 base = &chain->data->npdata[0];
5323 count = chain->bytes / sizeof(hammer2_blockref_t);
5325 case HAMMER2_BREF_TYPE_VOLUME:
5326 base = &chain->data->voldata.sroot_blockset.blockref[0];
5327 count = HAMMER2_SET_COUNT;
5329 case HAMMER2_BREF_TYPE_FREEMAP:
5330 base = &chain->data->blkset.blockref[0];
5331 count = HAMMER2_SET_COUNT;
5334 kprintf("hammer2_chain_lookup: unrecognized "
5335 "blockref(A) type: %d",
5338 tsleep(&base, 0, "dead", 0);
5339 panic("hammer2_chain_lookup: unrecognized "
5340 "blockref(A) type: %d",
5342 base = NULL; /* safety */
5343 count = 0; /* safety */
5345 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5351 * Chain memory management
5354 hammer2_chain_wait(hammer2_chain_t *chain)
5356 tsleep(chain, 0, "chnflw", 1);
5359 const hammer2_media_data_t *
5360 hammer2_chain_rdata(hammer2_chain_t *chain)
5362 KKASSERT(chain->data != NULL);
5363 return (chain->data);
5366 hammer2_media_data_t *
5367 hammer2_chain_wdata(hammer2_chain_t *chain)
5369 KKASSERT(chain->data != NULL);
5370 return (chain->data);
5374 * Set the check data for a chain. This can be a heavy-weight operation
5375 * and typically only runs on-flush. For file data check data is calculated
5376 * when the logical buffers are flushed.
5379 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5381 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5383 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5384 case HAMMER2_CHECK_NONE:
5386 case HAMMER2_CHECK_DISABLED:
5388 case HAMMER2_CHECK_ISCSI32:
5389 chain->bref.check.iscsi32.value =
5390 hammer2_icrc32(bdata, chain->bytes);
5392 case HAMMER2_CHECK_XXHASH64:
5393 chain->bref.check.xxhash64.value =
5394 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5396 case HAMMER2_CHECK_SHA192:
5398 SHA256_CTX hash_ctx;
5400 uint8_t digest[SHA256_DIGEST_LENGTH];
5401 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5404 SHA256_Init(&hash_ctx);
5405 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5406 SHA256_Final(u.digest, &hash_ctx);
5407 u.digest64[2] ^= u.digest64[3];
5409 chain->bref.check.sha192.data,
5410 sizeof(chain->bref.check.sha192.data));
5413 case HAMMER2_CHECK_FREEMAP:
5414 chain->bref.check.freemap.icrc32 =
5415 hammer2_icrc32(bdata, chain->bytes);
5418 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5419 chain->bref.methods);
5425 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5431 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5434 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5435 case HAMMER2_CHECK_NONE:
5438 case HAMMER2_CHECK_DISABLED:
5441 case HAMMER2_CHECK_ISCSI32:
5442 check32 = hammer2_icrc32(bdata, chain->bytes);
5443 r = (chain->bref.check.iscsi32.value == check32);
5445 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5446 "(flags=%08x, bref/data %08x/%08x)\n",
5447 chain->bref.data_off,
5449 chain->bref.methods,
5451 chain->bref.check.iscsi32.value,
5454 hammer2_check_icrc32 += chain->bytes;
5456 case HAMMER2_CHECK_XXHASH64:
5457 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5458 r = (chain->bref.check.xxhash64.value == check64);
5460 kprintf("chain %016jx.%02x key=%016jx "
5461 "meth=%02x CHECK FAIL "
5462 "(flags=%08x, bref/data %016jx/%016jx)\n",
5463 chain->bref.data_off,
5466 chain->bref.methods,
5468 chain->bref.check.xxhash64.value,
5471 hammer2_check_xxhash64 += chain->bytes;
5473 case HAMMER2_CHECK_SHA192:
5475 SHA256_CTX hash_ctx;
5477 uint8_t digest[SHA256_DIGEST_LENGTH];
5478 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5481 SHA256_Init(&hash_ctx);
5482 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5483 SHA256_Final(u.digest, &hash_ctx);
5484 u.digest64[2] ^= u.digest64[3];
5486 chain->bref.check.sha192.data,
5487 sizeof(chain->bref.check.sha192.data)) == 0) {
5491 kprintf("chain %016jx.%02x meth=%02x "
5493 chain->bref.data_off,
5495 chain->bref.methods);
5499 case HAMMER2_CHECK_FREEMAP:
5500 r = (chain->bref.check.freemap.icrc32 ==
5501 hammer2_icrc32(bdata, chain->bytes));
5503 kprintf("chain %016jx.%02x meth=%02x "
5505 chain->bref.data_off,
5507 chain->bref.methods);
5508 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5509 chain->bref.check.freemap.icrc32,
5510 hammer2_icrc32(bdata, chain->bytes),
5513 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5514 chain->dio, chain->dio->bp->b_loffset,
5515 chain->dio->bp->b_bufsize, bdata,
5516 chain->dio->bp->b_data);
5521 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5522 chain->bref.methods);
5530 * Acquire the chain and parent representing the specified inode for the
5531 * device at the specified cluster index.
5533 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5535 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5536 * will be NULL. *parentp may still be set error or not, or NULL if the
5537 * parent itself could not be resolved.
5539 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5540 * *parentp and *chainp will be unlocked if not NULL.
5543 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5544 int clindex, int flags,
5545 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5547 hammer2_chain_t *parent;
5548 hammer2_chain_t *rchain;
5549 hammer2_key_t key_dummy;
5553 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5554 HAMMER2_RESOLVE_SHARED : 0;
5557 * Caller expects us to replace these.
5560 hammer2_chain_unlock(*chainp);
5561 hammer2_chain_drop(*chainp);
5565 hammer2_chain_unlock(*parentp);
5566 hammer2_chain_drop(*parentp);
5571 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5572 * inodes from root directory entries in the key lookup).
5574 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5577 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5581 error = HAMMER2_ERROR_EIO;
5590 * Used by the bulkscan code to snapshot the synchronized storage for
5591 * a volume, allowing it to be scanned concurrently against normal
5595 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5597 hammer2_chain_t *copy;
5599 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5600 copy->data = kmalloc(sizeof(copy->data->voldata),
5603 hammer2_voldata_lock(hmp);
5604 copy->data->voldata = hmp->volsync;
5605 hammer2_voldata_unlock(hmp);
5611 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5613 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5614 KKASSERT(copy->data);
5615 kfree(copy->data, copy->hmp->mchain);
5617 atomic_add_long(&hammer2_chain_allocs, -1);
5618 hammer2_chain_drop(copy);
5622 * Create a snapshot of the specified (chain) with the specified label.
5623 * The originating hammer2_inode must be exclusively locked for
5624 * safety. The device's bulklk should be held by the caller. The caller
5625 * is responsible for synchronizing the filesystem to storage before
5626 * taking the snapshot.
5629 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5633 const hammer2_inode_data_t *ripdata;
5634 hammer2_inode_data_t *wipdata;
5635 hammer2_chain_t *nchain;
5636 hammer2_inode_t *nip;
5645 kprintf("snapshot %s\n", pmp->name);
5647 name_len = strlen(pmp->name);
5648 lhc = hammer2_dirhash(pmp->name, name_len);
5653 ripdata = &chain->data->ipdata;
5655 opfs_clid = ripdata->meta.pfs_clid;
5660 * Create the snapshot directory under the super-root
5662 * Set PFS type, generate a unique filesystem id, and generate
5663 * a cluster id. Use the same clid when snapshotting a PFS root,
5664 * which theoretically allows the snapshot to be used as part of
5665 * the same cluster (perhaps as a cache).
5667 * Copy the (flushed) blockref array. Theoretically we could use
5668 * chain_duplicate() but it becomes difficult to disentangle
5669 * the shared core so for now just brute-force it.
5674 hammer2_chain_unlock(chain);
5675 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5676 &vat, proc0.p_ucred,
5677 pmp->name, name_len, 0,
5679 HAMMER2_INSERT_PFSROOT, &error);
5680 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5683 hammer2_inode_modify(nip);
5684 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5685 error = hammer2_chain_modify(nchain, mtid, 0, 0);
5686 KKASSERT(error == 0);
5687 wipdata = &nchain->data->ipdata;
5689 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5690 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5691 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5692 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5696 * Give the snapshot its own private cluster id. As a
5697 * snapshot no further synchronization with the original
5698 * cluster will be done.
5700 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5701 nip->meta.pfs_clid = opfs_clid;
5703 kern_uuidgen(&nip->meta.pfs_clid, 1);
5705 kern_uuidgen(&nip->meta.pfs_clid, 1);
5706 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5708 /* XXX hack blockset copy */
5709 /* XXX doesn't work with real cluster */
5710 wipdata->meta = nip->meta;
5711 wipdata->u.blockset = ripdata->u.blockset;
5713 hammer2_flush(nchain, 1);
5714 KKASSERT(wipdata == &nchain->data->ipdata);
5715 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5717 hammer2_chain_unlock(nchain);
5718 hammer2_chain_drop(nchain);
5719 hammer2_inode_chain_sync(nip);
5720 hammer2_inode_unlock(nip);
5721 hammer2_inode_run_sideq(hmp->spmp);
5727 * Returns non-zero if the chain (INODE or DIRENT) matches the
5731 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5734 const hammer2_inode_data_t *ripdata;
5735 const hammer2_dirent_head_t *den;
5737 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5738 ripdata = &chain->data->ipdata;
5739 if (ripdata->meta.name_len == name_len &&
5740 bcmp(ripdata->filename, name, name_len) == 0) {
5744 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5745 chain->bref.embed.dirent.namlen == name_len) {
5746 den = &chain->bref.embed.dirent;
5747 if (name_len > sizeof(chain->bref.check.buf) &&
5748 bcmp(chain->data->buf, name, name_len) == 0) {
5751 if (name_len <= sizeof(chain->bref.check.buf) &&
5752 bcmp(chain->bref.check.buf, name, name_len) == 0) {