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 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3250 mtid, type, &error);
3251 if (nparent == NULL) {
3253 hammer2_chain_drop(chain);
3257 if (parent != nparent) {
3258 hammer2_chain_unlock(parent);
3259 hammer2_chain_drop(parent);
3260 parent = *parentp = nparent;
3265 if (chain->flags & HAMMER2_CHAIN_DELETED)
3266 kprintf("Inserting deleted chain @%016jx\n",
3270 * Link the chain into its parent.
3272 if (chain->parent != NULL)
3273 panic("hammer2: hammer2_chain_create: chain already connected");
3274 KKASSERT(chain->parent == NULL);
3275 KKASSERT(parent->core.live_count < count);
3276 hammer2_chain_insert(parent, chain,
3277 HAMMER2_CHAIN_INSERT_SPIN |
3278 HAMMER2_CHAIN_INSERT_LIVE,
3283 * Mark the newly created chain modified. This will cause
3284 * UPDATE to be set and process the INITIAL flag.
3286 * Device buffers are not instantiated for DATA elements
3287 * as these are handled by logical buffers.
3289 * Indirect and freemap node indirect blocks are handled
3290 * by hammer2_chain_create_indirect() and not by this
3293 * Data for all other bref types is expected to be
3294 * instantiated (INODE, LEAF).
3296 switch(chain->bref.type) {
3297 case HAMMER2_BREF_TYPE_DATA:
3298 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3299 case HAMMER2_BREF_TYPE_DIRENT:
3300 case HAMMER2_BREF_TYPE_INODE:
3301 error = hammer2_chain_modify(chain, mtid, dedup_off,
3302 HAMMER2_MODIFY_OPTDATA);
3306 * Remaining types are not supported by this function.
3307 * In particular, INDIRECT and LEAF_NODE types are
3308 * handled by create_indirect().
3310 panic("hammer2_chain_create: bad type: %d",
3317 * When reconnecting a chain we must set UPDATE and
3318 * setflush so the flush recognizes that it must update
3319 * the bref in the parent.
3321 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3322 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3326 * We must setflush(parent) to ensure that it recurses through to
3327 * chain. setflush(chain) might not work because ONFLUSH is possibly
3328 * already set in the chain (so it won't recurse up to set it in the
3331 hammer2_chain_setflush(parent);
3340 * Move the chain from its old parent to a new parent. The chain must have
3341 * already been deleted or already disconnected (or never associated) with
3342 * a parent. The chain is reassociated with the new parent and the deleted
3343 * flag will be cleared (no longer deleted). The chain's modification state
3346 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3347 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3348 * FULL. This typically means that the caller is creating the chain after
3349 * doing a hammer2_chain_lookup().
3351 * A non-NULL bref is typically passed when key and keybits must be overridden.
3352 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3353 * from a passed-in bref and uses the old chain's bref for everything else.
3355 * Neither (parent) or (chain) can be errored.
3357 * If (parent) is non-NULL then the chain is inserted under the parent.
3359 * If (parent) is NULL then the newly duplicated chain is not inserted
3360 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3361 * passing into hammer2_chain_create() after this function returns).
3363 * WARNING! This function calls create which means it can insert indirect
3364 * blocks. This can cause other unrelated chains in the parent to
3365 * be moved to a newly inserted indirect block in addition to the
3369 hammer2_chain_rename(hammer2_blockref_t *bref,
3370 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3371 hammer2_tid_t mtid, int flags)
3374 hammer2_chain_t *parent;
3378 * WARNING! We should never resolve DATA to device buffers
3379 * (XXX allow it if the caller did?), and since
3380 * we currently do not have the logical buffer cache
3381 * buffer in-hand to fix its cached physical offset
3382 * we also force the modify code to not COW it. XXX
3385 KKASSERT(chain->parent == NULL);
3386 KKASSERT(chain->error == 0);
3389 * Now create a duplicate of the chain structure, associating
3390 * it with the same core, making it the same size, pointing it
3391 * to the same bref (the same media block).
3393 * NOTE: Handle special radix == 0 case (means 0 bytes).
3396 bref = &chain->bref;
3397 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3399 bytes = (hammer2_off_t)1 << bytes;
3402 * If parent is not NULL the duplicated chain will be entered under
3403 * the parent and the UPDATE bit set to tell flush to update
3406 * We must setflush(parent) to ensure that it recurses through to
3407 * chain. setflush(chain) might not work because ONFLUSH is possibly
3408 * already set in the chain (so it won't recurse up to set it in the
3411 * Having both chains locked is extremely important for atomicy.
3413 if (parentp && (parent = *parentp) != NULL) {
3414 KKASSERT(hammer2_mtx_owned(&parent->lock));
3415 KKASSERT(parent->refs > 0);
3416 KKASSERT(parent->error == 0);
3418 hammer2_chain_create(parentp, &chain,
3419 chain->pmp, HAMMER2_METH_DEFAULT,
3420 bref->key, bref->keybits, bref->type,
3421 chain->bytes, mtid, 0, flags);
3422 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3423 hammer2_chain_setflush(*parentp);
3428 * Helper function for deleting chains.
3430 * The chain is removed from the live view (the RBTREE) as well as the parent's
3431 * blockmap. Both chain and its parent must be locked.
3433 * parent may not be errored. chain can be errored.
3436 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3437 hammer2_tid_t mtid, int flags)
3442 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3443 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3444 KKASSERT(chain->parent == parent);
3447 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3449 * Chain is blockmapped, so there must be a parent.
3450 * Atomically remove the chain from the parent and remove
3451 * the blockmap entry. The parent must be set modified
3452 * to remove the blockmap entry.
3454 hammer2_blockref_t *base;
3457 KKASSERT(parent != NULL);
3458 KKASSERT(parent->error == 0);
3459 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3460 error = hammer2_chain_modify(parent, mtid, 0, 0);
3465 * Calculate blockmap pointer
3467 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3468 hammer2_spin_ex(&chain->core.spin);
3469 hammer2_spin_ex(&parent->core.spin);
3471 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3472 atomic_add_int(&parent->core.live_count, -1);
3473 ++parent->core.generation;
3474 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3475 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3476 --parent->core.chain_count;
3477 chain->parent = NULL;
3479 switch(parent->bref.type) {
3480 case HAMMER2_BREF_TYPE_INODE:
3482 * Access the inode's block array. However, there
3483 * is no block array if the inode is flagged
3487 (parent->data->ipdata.meta.op_flags &
3488 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3490 &parent->data->ipdata.u.blockset.blockref[0];
3494 count = HAMMER2_SET_COUNT;
3496 case HAMMER2_BREF_TYPE_INDIRECT:
3497 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3499 base = &parent->data->npdata[0];
3502 count = parent->bytes / sizeof(hammer2_blockref_t);
3504 case HAMMER2_BREF_TYPE_VOLUME:
3505 base = &parent->data->voldata.
3506 sroot_blockset.blockref[0];
3507 count = HAMMER2_SET_COUNT;
3509 case HAMMER2_BREF_TYPE_FREEMAP:
3510 base = &parent->data->blkset.blockref[0];
3511 count = HAMMER2_SET_COUNT;
3516 panic("hammer2_flush_pass2: "
3517 "unrecognized blockref type: %d",
3522 * delete blockmapped chain from its parent.
3524 * The parent is not affected by any statistics in chain
3525 * which are pending synchronization. That is, there is
3526 * nothing to undo in the parent since they have not yet
3527 * been incorporated into the parent.
3529 * The parent is affected by statistics stored in inodes.
3530 * Those have already been synchronized, so they must be
3531 * undone. XXX split update possible w/delete in middle?
3534 hammer2_base_delete(parent, base, count, chain);
3536 hammer2_spin_unex(&parent->core.spin);
3537 hammer2_spin_unex(&chain->core.spin);
3538 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3540 * Chain is not blockmapped but a parent is present.
3541 * Atomically remove the chain from the parent. There is
3542 * no blockmap entry to remove.
3544 * Because chain was associated with a parent but not
3545 * synchronized, the chain's *_count_up fields contain
3546 * inode adjustment statistics which must be undone.
3548 hammer2_spin_ex(&chain->core.spin);
3549 hammer2_spin_ex(&parent->core.spin);
3550 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3551 atomic_add_int(&parent->core.live_count, -1);
3552 ++parent->core.generation;
3553 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3554 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3555 --parent->core.chain_count;
3556 chain->parent = NULL;
3557 hammer2_spin_unex(&parent->core.spin);
3558 hammer2_spin_unex(&chain->core.spin);
3561 * Chain is not blockmapped and has no parent. This
3562 * is a degenerate case.
3564 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3571 * Create an indirect block that covers one or more of the elements in the
3572 * current parent. Either returns the existing parent with no locking or
3573 * ref changes or returns the new indirect block locked and referenced
3574 * and leaving the original parent lock/ref intact as well.
3576 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3578 * The returned chain depends on where the specified key falls.
3580 * The key/keybits for the indirect mode only needs to follow three rules:
3582 * (1) That all elements underneath it fit within its key space and
3584 * (2) That all elements outside it are outside its key space.
3586 * (3) When creating the new indirect block any elements in the current
3587 * parent that fit within the new indirect block's keyspace must be
3588 * moved into the new indirect block.
3590 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3591 * keyspace the the current parent, but lookup/iteration rules will
3592 * ensure (and must ensure) that rule (2) for all parents leading up
3593 * to the nearest inode or the root volume header is adhered to. This
3594 * is accomplished by always recursing through matching keyspaces in
3595 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3597 * The current implementation calculates the current worst-case keyspace by
3598 * iterating the current parent and then divides it into two halves, choosing
3599 * whichever half has the most elements (not necessarily the half containing
3600 * the requested key).
3602 * We can also opt to use the half with the least number of elements. This
3603 * causes lower-numbered keys (aka logical file offsets) to recurse through
3604 * fewer indirect blocks and higher-numbered keys to recurse through more.
3605 * This also has the risk of not moving enough elements to the new indirect
3606 * block and being forced to create several indirect blocks before the element
3609 * Must be called with an exclusively locked parent.
3611 * NOTE: *errorp set to HAMMER_ERROR_* flags
3613 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3614 hammer2_key_t *keyp, int keybits,
3615 hammer2_blockref_t *base, int count);
3616 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3617 hammer2_key_t *keyp, int keybits,
3618 hammer2_blockref_t *base, int count,
3620 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3621 hammer2_key_t *keyp, int keybits,
3622 hammer2_blockref_t *base, int count,
3626 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3627 hammer2_key_t create_key, int create_bits,
3628 hammer2_tid_t mtid, int for_type, int *errorp)
3631 hammer2_blockref_t *base;
3632 hammer2_blockref_t *bref;
3633 hammer2_blockref_t bcopy;
3634 hammer2_chain_t *chain;
3635 hammer2_chain_t *ichain;
3636 hammer2_chain_t dummy;
3637 hammer2_key_t key = create_key;
3638 hammer2_key_t key_beg;
3639 hammer2_key_t key_end;
3640 hammer2_key_t key_next;
3641 int keybits = create_bits;
3649 int maxloops = 300000;
3652 * Calculate the base blockref pointer or NULL if the chain
3653 * is known to be empty. We need to calculate the array count
3654 * for RB lookups either way.
3657 KKASSERT(hammer2_mtx_owned(&parent->lock));
3660 * Pre-modify the parent now to avoid having to deal with error
3661 * processing if we tried to later (in the middle of our loop).
3663 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3665 kprintf("hammer2_create_indirect: error %08x %s\n",
3666 *errorp, hammer2_error_str(*errorp));
3670 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3671 base = hammer2_chain_base_and_count(parent, &count);
3674 * dummy used in later chain allocation (no longer used for lookups).
3676 bzero(&dummy, sizeof(dummy));
3679 * How big should our new indirect block be? It has to be at least
3680 * as large as its parent for splits to work properly.
3682 * The freemap uses a specific indirect block size. The number of
3683 * levels are built dynamically and ultimately depend on the size
3684 * volume. Because freemap blocks are taken from the reserved areas
3685 * of the volume our goal is efficiency (fewer levels) and not so
3686 * much to save disk space.
3688 * The first indirect block level for a directory usually uses
3689 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3690 * the hash mechanism, this typically gives us a nominal
3691 * 32 * 4 entries with one level of indirection.
3693 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3694 * indirect blocks. The initial 4 entries in the inode gives us
3695 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3696 * of indirection gives us 137GB, and so forth. H2 can support
3697 * huge file sizes but they are not typical, so we try to stick
3698 * with compactness and do not use a larger indirect block size.
3700 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3701 * due to the way indirect blocks are created this usually winds
3702 * up being extremely inefficient for small files. Even though
3703 * 16KB requires more levels of indirection for very large files,
3704 * the 16KB records can be ganged together into 64KB DIOs.
3706 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3707 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3708 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3709 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3710 if (parent->data->ipdata.meta.type ==
3711 HAMMER2_OBJTYPE_DIRECTORY)
3712 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3714 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3717 nbytes = HAMMER2_IND_BYTES_NOM;
3719 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3720 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3721 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3722 nbytes = count * sizeof(hammer2_blockref_t);
3724 ncount = nbytes / sizeof(hammer2_blockref_t);
3727 * When creating an indirect block for a freemap node or leaf
3728 * the key/keybits must be fitted to static radix levels because
3729 * particular radix levels use particular reserved blocks in the
3732 * This routine calculates the key/radix of the indirect block
3733 * we need to create, and whether it is on the high-side or the
3737 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3738 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3739 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3742 case HAMMER2_BREF_TYPE_DATA:
3743 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3744 base, count, ncount);
3746 case HAMMER2_BREF_TYPE_DIRENT:
3747 case HAMMER2_BREF_TYPE_INODE:
3748 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3749 base, count, ncount);
3752 panic("illegal indirect block for bref type %d", for_type);
3757 * Normalize the key for the radix being represented, keeping the
3758 * high bits and throwing away the low bits.
3760 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3763 * Ok, create our new indirect block
3765 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3766 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3767 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3769 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3771 dummy.bref.key = key;
3772 dummy.bref.keybits = keybits;
3773 dummy.bref.data_off = hammer2_getradix(nbytes);
3774 dummy.bref.methods =
3775 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3776 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3778 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3779 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3780 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3781 /* ichain has one ref at this point */
3784 * We have to mark it modified to allocate its block, but use
3785 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3786 * it won't be acted upon by the flush code.
3788 *errorp = hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3790 kprintf("hammer2_alloc_indirect: error %08x %s\n",
3791 *errorp, hammer2_error_str(*errorp));
3792 hammer2_chain_unlock(ichain);
3793 hammer2_chain_drop(ichain);
3798 * Iterate the original parent and move the matching brefs into
3799 * the new indirect block.
3801 * XXX handle flushes.
3804 key_end = HAMMER2_KEY_MAX;
3805 key_next = 0; /* avoid gcc warnings */
3806 hammer2_spin_ex(&parent->core.spin);
3812 * Parent may have been modified, relocating its block array.
3813 * Reload the base pointer.
3815 base = hammer2_chain_base_and_count(parent, &count);
3817 if (++loops > 100000) {
3818 hammer2_spin_unex(&parent->core.spin);
3819 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3820 reason, parent, base, count, key_next);
3824 * NOTE: spinlock stays intact, returned chain (if not NULL)
3825 * is not referenced or locked which means that we
3826 * cannot safely check its flagged / deletion status
3829 chain = hammer2_combined_find(parent, base, count,
3833 generation = parent->core.generation;
3836 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3839 * Skip keys that are not within the key/radix of the new
3840 * indirect block. They stay in the parent.
3842 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3843 (key ^ bref->key)) != 0) {
3844 goto next_key_spinlocked;
3848 * Load the new indirect block by acquiring the related
3849 * chains (potentially from media as it might not be
3850 * in-memory). Then move it to the new parent (ichain).
3852 * chain is referenced but not locked. We must lock the
3853 * chain to obtain definitive state.
3857 * Use chain already present in the RBTREE
3859 hammer2_chain_ref(chain);
3860 hammer2_spin_unex(&parent->core.spin);
3861 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3864 * Get chain for blockref element. _get returns NULL
3865 * on insertion race.
3868 hammer2_spin_unex(&parent->core.spin);
3869 chain = hammer2_chain_get(parent, generation, &bcopy);
3870 if (chain == NULL) {
3872 hammer2_spin_ex(&parent->core.spin);
3875 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3877 hammer2_chain_drop(chain);
3878 hammer2_spin_ex(&parent->core.spin);
3881 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3885 * This is always live so if the chain has been deleted
3886 * we raced someone and we have to retry.
3888 * NOTE: Lookups can race delete-duplicate because
3889 * delete-duplicate does not lock the parent's core
3890 * (they just use the spinlock on the core).
3892 * (note reversed logic for this one)
3894 if (chain->parent != parent ||
3895 (chain->flags & HAMMER2_CHAIN_DELETED)) {
3896 hammer2_chain_unlock(chain);
3897 hammer2_chain_drop(chain);
3898 kprintf("hammer2_chain_create_indirect "
3899 "RETRY (%p,%p)->%p %08x\n",
3900 parent, chain->parent, chain, chain->flags);
3901 hammer2_spin_ex(&parent->core.spin);
3906 * Shift the chain to the indirect block.
3908 * WARNING! No reason for us to load chain data, pass NOSTATS
3909 * to prevent delete/insert from trying to access
3910 * inode stats (and thus asserting if there is no
3911 * chain->data loaded).
3913 * WARNING! The (parent, chain) deletion may modify the parent
3914 * and invalidate the base pointer.
3916 * WARNING! Parent must already be marked modified, so we
3917 * can assume that chain_delete always suceeds.
3919 error = hammer2_chain_delete(parent, chain, mtid, 0);
3920 KKASSERT(error == 0);
3921 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3922 hammer2_chain_unlock(chain);
3923 hammer2_chain_drop(chain);
3924 KKASSERT(parent->refs > 0);
3926 base = NULL; /* safety */
3927 hammer2_spin_ex(&parent->core.spin);
3928 next_key_spinlocked:
3929 if (--maxloops == 0)
3930 panic("hammer2_chain_create_indirect: maxloops");
3932 if (key_next == 0 || key_next > key_end)
3937 hammer2_spin_unex(&parent->core.spin);
3940 * Insert the new indirect block into the parent now that we've
3941 * cleared out some entries in the parent. We calculated a good
3942 * insertion index in the loop above (ichain->index).
3944 * We don't have to set UPDATE here because we mark ichain
3945 * modified down below (so the normal modified -> flush -> set-moved
3946 * sequence applies).
3948 * The insertion shouldn't race as this is a completely new block
3949 * and the parent is locked.
3951 base = NULL; /* safety, parent modify may change address */
3952 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3953 KKASSERT(parent->core.live_count < count);
3954 hammer2_chain_insert(parent, ichain,
3955 HAMMER2_CHAIN_INSERT_SPIN |
3956 HAMMER2_CHAIN_INSERT_LIVE,
3960 * Make sure flushes propogate after our manual insertion.
3962 hammer2_chain_setflush(ichain);
3963 hammer2_chain_setflush(parent);
3966 * Figure out what to return.
3968 if (~(((hammer2_key_t)1 << keybits) - 1) &
3969 (create_key ^ key)) {
3971 * Key being created is outside the key range,
3972 * return the original parent.
3974 hammer2_chain_unlock(ichain);
3975 hammer2_chain_drop(ichain);
3978 * Otherwise its in the range, return the new parent.
3979 * (leave both the new and old parent locked).
3988 * Freemap indirect blocks
3990 * Calculate the keybits and highside/lowside of the freemap node the
3991 * caller is creating.
3993 * This routine will specify the next higher-level freemap key/radix
3994 * representing the lowest-ordered set. By doing so, eventually all
3995 * low-ordered sets will be moved one level down.
3997 * We have to be careful here because the freemap reserves a limited
3998 * number of blocks for a limited number of levels. So we can't just
3999 * push indiscriminately.
4002 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4003 int keybits, hammer2_blockref_t *base, int count)
4005 hammer2_chain_t *chain;
4006 hammer2_blockref_t *bref;
4008 hammer2_key_t key_beg;
4009 hammer2_key_t key_end;
4010 hammer2_key_t key_next;
4013 int maxloops = 300000;
4021 * Calculate the range of keys in the array being careful to skip
4022 * slots which are overridden with a deletion.
4025 key_end = HAMMER2_KEY_MAX;
4026 hammer2_spin_ex(&parent->core.spin);
4029 if (--maxloops == 0) {
4030 panic("indkey_freemap shit %p %p:%d\n",
4031 parent, base, count);
4033 chain = hammer2_combined_find(parent, base, count,
4045 * Skip deleted chains.
4047 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4048 if (key_next == 0 || key_next > key_end)
4055 * Use the full live (not deleted) element for the scan
4056 * iteration. HAMMER2 does not allow partial replacements.
4058 * XXX should be built into hammer2_combined_find().
4060 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4062 if (keybits > bref->keybits) {
4064 keybits = bref->keybits;
4065 } else if (keybits == bref->keybits && bref->key < key) {
4072 hammer2_spin_unex(&parent->core.spin);
4075 * Return the keybits for a higher-level FREEMAP_NODE covering
4079 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4080 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4082 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4083 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4085 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4086 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4088 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4089 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4091 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4092 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4094 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4095 panic("hammer2_chain_indkey_freemap: level too high");
4098 panic("hammer2_chain_indkey_freemap: bad radix");
4107 * File indirect blocks
4109 * Calculate the key/keybits for the indirect block to create by scanning
4110 * existing keys. The key being created is also passed in *keyp and can be
4111 * inside or outside the indirect block. Regardless, the indirect block
4112 * must hold at least two keys in order to guarantee sufficient space.
4114 * We use a modified version of the freemap's fixed radix tree, but taylored
4115 * for file data. Basically we configure an indirect block encompassing the
4119 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4120 int keybits, hammer2_blockref_t *base, int count,
4123 hammer2_chain_t *chain;
4124 hammer2_blockref_t *bref;
4126 hammer2_key_t key_beg;
4127 hammer2_key_t key_end;
4128 hammer2_key_t key_next;
4132 int maxloops = 300000;
4140 * Calculate the range of keys in the array being careful to skip
4141 * slots which are overridden with a deletion.
4143 * Locate the smallest key.
4146 key_end = HAMMER2_KEY_MAX;
4147 hammer2_spin_ex(&parent->core.spin);
4150 if (--maxloops == 0) {
4151 panic("indkey_freemap shit %p %p:%d\n",
4152 parent, base, count);
4154 chain = hammer2_combined_find(parent, base, count,
4166 * Skip deleted chains.
4168 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4169 if (key_next == 0 || key_next > key_end)
4176 * Use the full live (not deleted) element for the scan
4177 * iteration. HAMMER2 does not allow partial replacements.
4179 * XXX should be built into hammer2_combined_find().
4181 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4183 if (keybits > bref->keybits) {
4185 keybits = bref->keybits;
4186 } else if (keybits == bref->keybits && bref->key < key) {
4193 hammer2_spin_unex(&parent->core.spin);
4196 * Calculate the static keybits for a higher-level indirect block
4197 * that contains the key.
4202 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4203 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4205 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4206 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4208 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4209 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4212 panic("bad ncount %d\n", ncount);
4218 * The largest radix that can be returned for an indirect block is
4219 * 63 bits. (The largest practical indirect block radix is actually
4220 * 62 bits because the top-level inode or volume root contains four
4221 * entries, but allow 63 to be returned).
4226 return keybits + nradix;
4232 * Directory indirect blocks.
4234 * Covers both the inode index (directory of inodes), and directory contents
4235 * (filenames hardlinked to inodes).
4237 * Because directory keys are hashed we generally try to cut the space in
4238 * half. We accomodate the inode index (which tends to have linearly
4239 * increasing inode numbers) by ensuring that the keyspace is at least large
4240 * enough to fill up the indirect block being created.
4243 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4244 int keybits, hammer2_blockref_t *base, int count,
4247 hammer2_blockref_t *bref;
4248 hammer2_chain_t *chain;
4249 hammer2_key_t key_beg;
4250 hammer2_key_t key_end;
4251 hammer2_key_t key_next;
4256 int maxloops = 300000;
4259 * Shortcut if the parent is the inode. In this situation the
4260 * parent has 4+1 directory entries and we are creating an indirect
4261 * block capable of holding many more.
4263 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4272 * Calculate the range of keys in the array being careful to skip
4273 * slots which are overridden with a deletion.
4276 key_end = HAMMER2_KEY_MAX;
4277 hammer2_spin_ex(&parent->core.spin);
4280 if (--maxloops == 0) {
4281 panic("indkey_freemap shit %p %p:%d\n",
4282 parent, base, count);
4284 chain = hammer2_combined_find(parent, base, count,
4298 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4299 if (key_next == 0 || key_next > key_end)
4306 * Use the full live (not deleted) element for the scan
4307 * iteration. HAMMER2 does not allow partial replacements.
4309 * XXX should be built into hammer2_combined_find().
4311 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4314 * Expand our calculated key range (key, keybits) to fit
4315 * the scanned key. nkeybits represents the full range
4316 * that we will later cut in half (two halves @ nkeybits - 1).
4319 if (nkeybits < bref->keybits) {
4320 if (bref->keybits > 64) {
4321 kprintf("bad bref chain %p bref %p\n",
4325 nkeybits = bref->keybits;
4327 while (nkeybits < 64 &&
4328 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4329 (key ^ bref->key)) != 0) {
4334 * If the new key range is larger we have to determine
4335 * which side of the new key range the existing keys fall
4336 * under by checking the high bit, then collapsing the
4337 * locount into the hicount or vise-versa.
4339 if (keybits != nkeybits) {
4340 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4351 * The newly scanned key will be in the lower half or the
4352 * upper half of the (new) key range.
4354 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4363 hammer2_spin_unex(&parent->core.spin);
4364 bref = NULL; /* now invalid (safety) */
4367 * Adjust keybits to represent half of the full range calculated
4368 * above (radix 63 max) for our new indirect block.
4373 * Expand keybits to hold at least ncount elements. ncount will be
4374 * a power of 2. This is to try to completely fill leaf nodes (at
4375 * least for keys which are not hashes).
4377 * We aren't counting 'in' or 'out', we are counting 'high side'
4378 * and 'low side' based on the bit at (1LL << keybits). We want
4379 * everything to be inside in these cases so shift it all to
4380 * the low or high side depending on the new high bit.
4382 while (((hammer2_key_t)1 << keybits) < ncount) {
4384 if (key & ((hammer2_key_t)1 << keybits)) {
4393 if (hicount > locount)
4394 key |= (hammer2_key_t)1 << keybits;
4396 key &= ~(hammer2_key_t)1 << keybits;
4406 * Directory indirect blocks.
4408 * Covers both the inode index (directory of inodes), and directory contents
4409 * (filenames hardlinked to inodes).
4411 * Because directory keys are hashed we generally try to cut the space in
4412 * half. We accomodate the inode index (which tends to have linearly
4413 * increasing inode numbers) by ensuring that the keyspace is at least large
4414 * enough to fill up the indirect block being created.
4417 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4418 int keybits, hammer2_blockref_t *base, int count,
4421 hammer2_blockref_t *bref;
4422 hammer2_chain_t *chain;
4423 hammer2_key_t key_beg;
4424 hammer2_key_t key_end;
4425 hammer2_key_t key_next;
4430 int maxloops = 300000;
4433 * Shortcut if the parent is the inode. In this situation the
4434 * parent has 4+1 directory entries and we are creating an indirect
4435 * block capable of holding many more.
4437 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4446 * Calculate the range of keys in the array being careful to skip
4447 * slots which are overridden with a deletion.
4450 key_end = HAMMER2_KEY_MAX;
4451 hammer2_spin_ex(&parent->core.spin);
4454 if (--maxloops == 0) {
4455 panic("indkey_freemap shit %p %p:%d\n",
4456 parent, base, count);
4458 chain = hammer2_combined_find(parent, base, count,
4472 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4473 if (key_next == 0 || key_next > key_end)
4480 * Use the full live (not deleted) element for the scan
4481 * iteration. HAMMER2 does not allow partial replacements.
4483 * XXX should be built into hammer2_combined_find().
4485 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4488 * Expand our calculated key range (key, keybits) to fit
4489 * the scanned key. nkeybits represents the full range
4490 * that we will later cut in half (two halves @ nkeybits - 1).
4493 if (nkeybits < bref->keybits) {
4494 if (bref->keybits > 64) {
4495 kprintf("bad bref chain %p bref %p\n",
4499 nkeybits = bref->keybits;
4501 while (nkeybits < 64 &&
4502 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4503 (key ^ bref->key)) != 0) {
4508 * If the new key range is larger we have to determine
4509 * which side of the new key range the existing keys fall
4510 * under by checking the high bit, then collapsing the
4511 * locount into the hicount or vise-versa.
4513 if (keybits != nkeybits) {
4514 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4525 * The newly scanned key will be in the lower half or the
4526 * upper half of the (new) key range.
4528 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4537 hammer2_spin_unex(&parent->core.spin);
4538 bref = NULL; /* now invalid (safety) */
4541 * Adjust keybits to represent half of the full range calculated
4542 * above (radix 63 max) for our new indirect block.
4547 * Expand keybits to hold at least ncount elements. ncount will be
4548 * a power of 2. This is to try to completely fill leaf nodes (at
4549 * least for keys which are not hashes).
4551 * We aren't counting 'in' or 'out', we are counting 'high side'
4552 * and 'low side' based on the bit at (1LL << keybits). We want
4553 * everything to be inside in these cases so shift it all to
4554 * the low or high side depending on the new high bit.
4556 while (((hammer2_key_t)1 << keybits) < ncount) {
4558 if (key & ((hammer2_key_t)1 << keybits)) {
4567 if (hicount > locount)
4568 key |= (hammer2_key_t)1 << keybits;
4570 key &= ~(hammer2_key_t)1 << keybits;
4580 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4583 * Both parent and chain must be locked exclusively.
4585 * This function will modify the parent if the blockref requires removal
4586 * from the parent's block table.
4588 * This function is NOT recursive. Any entity already pushed into the
4589 * chain (such as an inode) may still need visibility into its contents,
4590 * as well as the ability to read and modify the contents. For example,
4591 * for an unlinked file which is still open.
4593 * Also note that the flusher is responsible for cleaning up empty
4597 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4598 hammer2_tid_t mtid, int flags)
4602 KKASSERT(hammer2_mtx_owned(&chain->lock));
4605 * Nothing to do if already marked.
4607 * We need the spinlock on the core whos RBTREE contains chain
4608 * to protect against races.
4610 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4611 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4612 chain->parent == parent);
4613 error = _hammer2_chain_delete_helper(parent, chain,
4618 * Permanent deletions mark the chain as destroyed.
4621 if (flags & HAMMER2_DELETE_PERMANENT)
4622 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4623 hammer2_chain_setflush(chain);
4630 * Returns the index of the nearest element in the blockref array >= elm.
4631 * Returns (count) if no element could be found.
4633 * Sets *key_nextp to the next key for loop purposes but does not modify
4634 * it if the next key would be higher than the current value of *key_nextp.
4635 * Note that *key_nexp can overflow to 0, which should be tested by the
4638 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4639 * held through the operation.
4642 hammer2_base_find(hammer2_chain_t *parent,
4643 hammer2_blockref_t *base, int count,
4644 hammer2_key_t *key_nextp,
4645 hammer2_key_t key_beg, hammer2_key_t key_end)
4647 hammer2_blockref_t *scan;
4648 hammer2_key_t scan_end;
4653 * Require the live chain's already have their core's counted
4654 * so we can optimize operations.
4656 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4661 if (count == 0 || base == NULL)
4665 * Sequential optimization using parent->cache_index. This is
4666 * the most likely scenario.
4668 * We can avoid trailing empty entries on live chains, otherwise
4669 * we might have to check the whole block array.
4671 i = parent->cache_index; /* SMP RACE OK */
4673 limit = parent->core.live_zero;
4678 KKASSERT(i < count);
4684 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4688 parent->cache_index = i;
4691 * Search forwards, stop when we find a scan element which
4692 * encloses the key or until we know that there are no further
4696 if (scan->type != 0) {
4697 scan_end = scan->key +
4698 ((hammer2_key_t)1 << scan->keybits) - 1;
4699 if (scan->key > key_beg || scan_end >= key_beg)
4708 parent->cache_index = i;
4712 scan_end = scan->key +
4713 ((hammer2_key_t)1 << scan->keybits);
4714 if (scan_end && (*key_nextp > scan_end ||
4716 *key_nextp = scan_end;
4724 * Do a combined search and return the next match either from the blockref
4725 * array or from the in-memory chain. Sets *bresp to the returned bref in
4726 * both cases, or sets it to NULL if the search exhausted. Only returns
4727 * a non-NULL chain if the search matched from the in-memory chain.
4729 * When no in-memory chain has been found and a non-NULL bref is returned
4733 * The returned chain is not locked or referenced. Use the returned bref
4734 * to determine if the search exhausted or not. Iterate if the base find
4735 * is chosen but matches a deleted chain.
4737 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4738 * held through the operation.
4740 static hammer2_chain_t *
4741 hammer2_combined_find(hammer2_chain_t *parent,
4742 hammer2_blockref_t *base, int count,
4743 hammer2_key_t *key_nextp,
4744 hammer2_key_t key_beg, hammer2_key_t key_end,
4745 hammer2_blockref_t **bresp)
4747 hammer2_blockref_t *bref;
4748 hammer2_chain_t *chain;
4752 * Lookup in block array and in rbtree.
4754 *key_nextp = key_end + 1;
4755 i = hammer2_base_find(parent, base, count, key_nextp,
4757 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4762 if (i == count && chain == NULL) {
4768 * Only chain matched.
4771 bref = &chain->bref;
4776 * Only blockref matched.
4778 if (chain == NULL) {
4784 * Both in-memory and blockref matched, select the nearer element.
4786 * If both are flush with the left-hand side or both are the
4787 * same distance away, select the chain. In this situation the
4788 * chain must have been loaded from the matching blockmap.
4790 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4791 chain->bref.key == base[i].key) {
4792 KKASSERT(chain->bref.key == base[i].key);
4793 bref = &chain->bref;
4798 * Select the nearer key
4800 if (chain->bref.key < base[i].key) {
4801 bref = &chain->bref;
4808 * If the bref is out of bounds we've exhausted our search.
4811 if (bref->key > key_end) {
4821 * Locate the specified block array element and delete it. The element
4824 * The spin lock on the related chain must be held.
4826 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4827 * need to be adjusted when we commit the media change.
4830 hammer2_base_delete(hammer2_chain_t *parent,
4831 hammer2_blockref_t *base, int count,
4832 hammer2_chain_t *chain)
4834 hammer2_blockref_t *elm = &chain->bref;
4835 hammer2_blockref_t *scan;
4836 hammer2_key_t key_next;
4840 * Delete element. Expect the element to exist.
4842 * XXX see caller, flush code not yet sophisticated enough to prevent
4843 * re-flushed in some cases.
4845 key_next = 0; /* max range */
4846 i = hammer2_base_find(parent, base, count, &key_next,
4847 elm->key, elm->key);
4849 if (i == count || scan->type == 0 ||
4850 scan->key != elm->key ||
4851 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4852 scan->keybits != elm->keybits)) {
4853 hammer2_spin_unex(&parent->core.spin);
4854 panic("delete base %p element not found at %d/%d elm %p\n",
4855 base, i, count, elm);
4860 * Update stats and zero the entry.
4862 * NOTE: Handle radix == 0 (0 bytes) case.
4864 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4865 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4866 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4868 switch(scan->type) {
4869 case HAMMER2_BREF_TYPE_INODE:
4870 case HAMMER2_BREF_TYPE_DATA:
4871 --parent->bref.embed.stats.inode_count;
4872 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
4873 atomic_set_int(&chain->flags,
4874 HAMMER2_CHAIN_HINT_LEAF_COUNT);
4876 if (parent->bref.leaf_count)
4877 --parent->bref.leaf_count;
4880 case HAMMER2_BREF_TYPE_INDIRECT:
4881 parent->bref.embed.stats.data_count -=
4882 scan->embed.stats.data_count;
4883 parent->bref.embed.stats.inode_count -=
4884 scan->embed.stats.inode_count;
4885 if (scan->type == HAMMER2_BREF_TYPE_INODE)
4887 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
4888 atomic_set_int(&chain->flags,
4889 HAMMER2_CHAIN_HINT_LEAF_COUNT);
4891 if (parent->bref.leaf_count <= scan->leaf_count)
4892 parent->bref.leaf_count = 0;
4894 parent->bref.leaf_count -= scan->leaf_count;
4897 case HAMMER2_BREF_TYPE_DIRENT:
4898 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
4899 atomic_set_int(&chain->flags,
4900 HAMMER2_CHAIN_HINT_LEAF_COUNT);
4902 if (parent->bref.leaf_count)
4903 --parent->bref.leaf_count;
4909 bzero(scan, sizeof(*scan));
4912 * We can only optimize parent->core.live_zero for live chains.
4914 if (parent->core.live_zero == i + 1) {
4915 while (--i >= 0 && base[i].type == 0)
4917 parent->core.live_zero = i + 1;
4921 * Clear appropriate blockmap flags in chain.
4923 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4924 HAMMER2_CHAIN_BMAPUPD);
4928 * Insert the specified element. The block array must not already have the
4929 * element and must have space available for the insertion.
4931 * The spin lock on the related chain must be held.
4933 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4934 * need to be adjusted when we commit the media change.
4937 hammer2_base_insert(hammer2_chain_t *parent,
4938 hammer2_blockref_t *base, int count,
4939 hammer2_chain_t *chain)
4941 hammer2_blockref_t *elm = &chain->bref;
4942 hammer2_key_t key_next;
4951 * Insert new element. Expect the element to not already exist
4952 * unless we are replacing it.
4954 * XXX see caller, flush code not yet sophisticated enough to prevent
4955 * re-flushed in some cases.
4957 key_next = 0; /* max range */
4958 i = hammer2_base_find(parent, base, count, &key_next,
4959 elm->key, elm->key);
4962 * Shortcut fill optimization, typical ordered insertion(s) may not
4965 KKASSERT(i >= 0 && i <= count);
4968 * Set appropriate blockmap flags in chain.
4970 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4973 * Update stats and zero the entry
4975 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4976 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4977 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4980 case HAMMER2_BREF_TYPE_INODE:
4981 ++parent->bref.embed.stats.inode_count;
4982 case HAMMER2_BREF_TYPE_DATA:
4983 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
4984 ++parent->bref.leaf_count;
4986 case HAMMER2_BREF_TYPE_INDIRECT:
4987 parent->bref.embed.stats.data_count +=
4988 elm->embed.stats.data_count;
4989 parent->bref.embed.stats.inode_count +=
4990 elm->embed.stats.inode_count;
4991 if (elm->type == HAMMER2_BREF_TYPE_INODE)
4993 if (parent->bref.leaf_count + elm->leaf_count <
4994 HAMMER2_BLOCKREF_LEAF_MAX) {
4995 parent->bref.leaf_count += elm->leaf_count;
4997 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5000 case HAMMER2_BREF_TYPE_DIRENT:
5001 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5002 ++parent->bref.leaf_count;
5010 * We can only optimize parent->core.live_zero for live chains.
5012 if (i == count && parent->core.live_zero < count) {
5013 i = parent->core.live_zero++;
5018 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5019 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5020 hammer2_spin_unex(&parent->core.spin);
5021 panic("insert base %p overlapping elements at %d elm %p\n",
5026 * Try to find an empty slot before or after.
5030 while (j > 0 || k < count) {
5032 if (j >= 0 && base[j].type == 0) {
5036 bcopy(&base[j+1], &base[j],
5037 (i - j - 1) * sizeof(*base));
5043 if (k < count && base[k].type == 0) {
5044 bcopy(&base[i], &base[i+1],
5045 (k - i) * sizeof(hammer2_blockref_t));
5049 * We can only update parent->core.live_zero for live
5052 if (parent->core.live_zero <= k)
5053 parent->core.live_zero = k + 1;
5058 panic("hammer2_base_insert: no room!");
5065 for (l = 0; l < count; ++l) {
5067 key_next = base[l].key +
5068 ((hammer2_key_t)1 << base[l].keybits) - 1;
5072 while (++l < count) {
5074 if (base[l].key <= key_next)
5075 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5076 key_next = base[l].key +
5077 ((hammer2_key_t)1 << base[l].keybits) - 1;
5087 * Sort the blockref array for the chain. Used by the flush code to
5088 * sort the blockref[] array.
5090 * The chain must be exclusively locked AND spin-locked.
5092 typedef hammer2_blockref_t *hammer2_blockref_p;
5096 hammer2_base_sort_callback(const void *v1, const void *v2)
5098 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5099 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5102 * Make sure empty elements are placed at the end of the array
5104 if (bref1->type == 0) {
5105 if (bref2->type == 0)
5108 } else if (bref2->type == 0) {
5115 if (bref1->key < bref2->key)
5117 if (bref1->key > bref2->key)
5123 hammer2_base_sort(hammer2_chain_t *chain)
5125 hammer2_blockref_t *base;
5128 switch(chain->bref.type) {
5129 case HAMMER2_BREF_TYPE_INODE:
5131 * Special shortcut for embedded data returns the inode
5132 * itself. Callers must detect this condition and access
5133 * the embedded data (the strategy code does this for us).
5135 * This is only applicable to regular files and softlinks.
5137 if (chain->data->ipdata.meta.op_flags &
5138 HAMMER2_OPFLAG_DIRECTDATA) {
5141 base = &chain->data->ipdata.u.blockset.blockref[0];
5142 count = HAMMER2_SET_COUNT;
5144 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5145 case HAMMER2_BREF_TYPE_INDIRECT:
5147 * Optimize indirect blocks in the INITIAL state to avoid
5150 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5151 base = &chain->data->npdata[0];
5152 count = chain->bytes / sizeof(hammer2_blockref_t);
5154 case HAMMER2_BREF_TYPE_VOLUME:
5155 base = &chain->data->voldata.sroot_blockset.blockref[0];
5156 count = HAMMER2_SET_COUNT;
5158 case HAMMER2_BREF_TYPE_FREEMAP:
5159 base = &chain->data->blkset.blockref[0];
5160 count = HAMMER2_SET_COUNT;
5163 kprintf("hammer2_chain_lookup: unrecognized "
5164 "blockref(A) type: %d",
5167 tsleep(&base, 0, "dead", 0);
5168 panic("hammer2_chain_lookup: unrecognized "
5169 "blockref(A) type: %d",
5171 base = NULL; /* safety */
5172 count = 0; /* safety */
5174 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5180 * Chain memory management
5183 hammer2_chain_wait(hammer2_chain_t *chain)
5185 tsleep(chain, 0, "chnflw", 1);
5188 const hammer2_media_data_t *
5189 hammer2_chain_rdata(hammer2_chain_t *chain)
5191 KKASSERT(chain->data != NULL);
5192 return (chain->data);
5195 hammer2_media_data_t *
5196 hammer2_chain_wdata(hammer2_chain_t *chain)
5198 KKASSERT(chain->data != NULL);
5199 return (chain->data);
5203 * Set the check data for a chain. This can be a heavy-weight operation
5204 * and typically only runs on-flush. For file data check data is calculated
5205 * when the logical buffers are flushed.
5208 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5210 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5212 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5213 case HAMMER2_CHECK_NONE:
5215 case HAMMER2_CHECK_DISABLED:
5217 case HAMMER2_CHECK_ISCSI32:
5218 chain->bref.check.iscsi32.value =
5219 hammer2_icrc32(bdata, chain->bytes);
5221 case HAMMER2_CHECK_XXHASH64:
5222 chain->bref.check.xxhash64.value =
5223 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5225 case HAMMER2_CHECK_SHA192:
5227 SHA256_CTX hash_ctx;
5229 uint8_t digest[SHA256_DIGEST_LENGTH];
5230 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5233 SHA256_Init(&hash_ctx);
5234 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5235 SHA256_Final(u.digest, &hash_ctx);
5236 u.digest64[2] ^= u.digest64[3];
5238 chain->bref.check.sha192.data,
5239 sizeof(chain->bref.check.sha192.data));
5242 case HAMMER2_CHECK_FREEMAP:
5243 chain->bref.check.freemap.icrc32 =
5244 hammer2_icrc32(bdata, chain->bytes);
5247 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5248 chain->bref.methods);
5254 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5260 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5263 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5264 case HAMMER2_CHECK_NONE:
5267 case HAMMER2_CHECK_DISABLED:
5270 case HAMMER2_CHECK_ISCSI32:
5271 check32 = hammer2_icrc32(bdata, chain->bytes);
5272 r = (chain->bref.check.iscsi32.value == check32);
5274 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5275 "(flags=%08x, bref/data %08x/%08x)\n",
5276 chain->bref.data_off,
5278 chain->bref.methods,
5280 chain->bref.check.iscsi32.value,
5283 hammer2_check_icrc32 += chain->bytes;
5285 case HAMMER2_CHECK_XXHASH64:
5286 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5287 r = (chain->bref.check.xxhash64.value == check64);
5289 kprintf("chain %016jx.%02x key=%016jx "
5290 "meth=%02x CHECK FAIL "
5291 "(flags=%08x, bref/data %016jx/%016jx)\n",
5292 chain->bref.data_off,
5295 chain->bref.methods,
5297 chain->bref.check.xxhash64.value,
5300 hammer2_check_xxhash64 += chain->bytes;
5302 case HAMMER2_CHECK_SHA192:
5304 SHA256_CTX hash_ctx;
5306 uint8_t digest[SHA256_DIGEST_LENGTH];
5307 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5310 SHA256_Init(&hash_ctx);
5311 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5312 SHA256_Final(u.digest, &hash_ctx);
5313 u.digest64[2] ^= u.digest64[3];
5315 chain->bref.check.sha192.data,
5316 sizeof(chain->bref.check.sha192.data)) == 0) {
5320 kprintf("chain %016jx.%02x meth=%02x "
5322 chain->bref.data_off,
5324 chain->bref.methods);
5328 case HAMMER2_CHECK_FREEMAP:
5329 r = (chain->bref.check.freemap.icrc32 ==
5330 hammer2_icrc32(bdata, chain->bytes));
5332 kprintf("chain %016jx.%02x meth=%02x "
5334 chain->bref.data_off,
5336 chain->bref.methods);
5337 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5338 chain->bref.check.freemap.icrc32,
5339 hammer2_icrc32(bdata, chain->bytes),
5342 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5343 chain->dio, chain->dio->bp->b_loffset,
5344 chain->dio->bp->b_bufsize, bdata,
5345 chain->dio->bp->b_data);
5350 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5351 chain->bref.methods);
5359 * Acquire the chain and parent representing the specified inode for the
5360 * device at the specified cluster index.
5362 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5364 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5365 * will be NULL. *parentp may still be set error or not, or NULL if the
5366 * parent itself could not be resolved.
5368 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5369 * *parentp and *chainp will be unlocked if not NULL.
5372 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5373 int clindex, int flags,
5374 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5376 hammer2_chain_t *parent;
5377 hammer2_chain_t *rchain;
5378 hammer2_key_t key_dummy;
5382 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5383 HAMMER2_RESOLVE_SHARED : 0;
5386 * Caller expects us to replace these.
5389 hammer2_chain_unlock(*chainp);
5390 hammer2_chain_drop(*chainp);
5394 hammer2_chain_unlock(*parentp);
5395 hammer2_chain_drop(*parentp);
5400 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5401 * inodes from root directory entries in the key lookup).
5403 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5406 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5410 error = HAMMER2_ERROR_EIO;
5419 * Used by the bulkscan code to snapshot the synchronized storage for
5420 * a volume, allowing it to be scanned concurrently against normal
5424 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5426 hammer2_chain_t *copy;
5428 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5429 copy->data = kmalloc(sizeof(copy->data->voldata),
5432 hammer2_voldata_lock(hmp);
5433 copy->data->voldata = hmp->volsync;
5434 hammer2_voldata_unlock(hmp);
5440 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5442 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5443 KKASSERT(copy->data);
5444 kfree(copy->data, copy->hmp->mchain);
5446 atomic_add_long(&hammer2_chain_allocs, -1);
5447 hammer2_chain_drop(copy);
5451 * Create a snapshot of the specified (chain) with the specified label.
5452 * The originating hammer2_inode must be exclusively locked for
5453 * safety. The device's bulklk should be held by the caller. The caller
5454 * is responsible for synchronizing the filesystem to storage before
5455 * taking the snapshot.
5458 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5462 const hammer2_inode_data_t *ripdata;
5463 hammer2_inode_data_t *wipdata;
5464 hammer2_chain_t *nchain;
5465 hammer2_inode_t *nip;
5474 kprintf("snapshot %s\n", pmp->name);
5476 name_len = strlen(pmp->name);
5477 lhc = hammer2_dirhash(pmp->name, name_len);
5482 ripdata = &chain->data->ipdata;
5484 opfs_clid = ripdata->meta.pfs_clid;
5489 * Create the snapshot directory under the super-root
5491 * Set PFS type, generate a unique filesystem id, and generate
5492 * a cluster id. Use the same clid when snapshotting a PFS root,
5493 * which theoretically allows the snapshot to be used as part of
5494 * the same cluster (perhaps as a cache).
5496 * Copy the (flushed) blockref array. Theoretically we could use
5497 * chain_duplicate() but it becomes difficult to disentangle
5498 * the shared core so for now just brute-force it.
5503 hammer2_chain_unlock(chain);
5504 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5505 &vat, proc0.p_ucred,
5506 pmp->name, name_len, 0,
5508 HAMMER2_INSERT_PFSROOT, &error);
5509 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5512 hammer2_inode_modify(nip);
5513 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5514 error = hammer2_chain_modify(nchain, mtid, 0, 0);
5515 KKASSERT(error == 0);
5516 wipdata = &nchain->data->ipdata;
5518 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5519 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5520 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5521 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5525 * Give the snapshot its own private cluster id. As a
5526 * snapshot no further synchronization with the original
5527 * cluster will be done.
5529 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5530 nip->meta.pfs_clid = opfs_clid;
5532 kern_uuidgen(&nip->meta.pfs_clid, 1);
5534 kern_uuidgen(&nip->meta.pfs_clid, 1);
5535 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5537 /* XXX hack blockset copy */
5538 /* XXX doesn't work with real cluster */
5539 wipdata->meta = nip->meta;
5540 wipdata->u.blockset = ripdata->u.blockset;
5542 hammer2_flush(nchain, 1);
5543 KKASSERT(wipdata == &nchain->data->ipdata);
5544 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5546 hammer2_chain_unlock(nchain);
5547 hammer2_chain_drop(nchain);
5548 hammer2_inode_chain_sync(nip);
5549 hammer2_inode_unlock(nip);
5550 hammer2_inode_run_sideq(hmp->spmp);
5556 * Returns non-zero if the chain (INODE or DIRENT) matches the
5560 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5563 const hammer2_inode_data_t *ripdata;
5564 const hammer2_dirent_head_t *den;
5566 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5567 ripdata = &chain->data->ipdata;
5568 if (ripdata->meta.name_len == name_len &&
5569 bcmp(ripdata->filename, name, name_len) == 0) {
5573 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5574 chain->bref.embed.dirent.namlen == name_len) {
5575 den = &chain->bref.embed.dirent;
5576 if (name_len > sizeof(chain->bref.check.buf) &&
5577 bcmp(chain->data->buf, name, name_len) == 0) {
5580 if (name_len <= sizeof(chain->bref.check.buf) &&
5581 bcmp(chain->bref.check.buf, name, name_len) == 0) {