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);
79 static struct krate krate_h2me = { .freq = 1 };
82 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
83 * overlap in the RB trees. Deleted chains are moved from rbtree to either
86 * Chains in delete-duplicate sequences can always iterate through core_entry
87 * to locate the live version of the chain.
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
92 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
100 * Compare chains. Overlaps are not supposed to happen and catch
101 * any software issues early we count overlaps as a match.
103 c1_beg = chain1->bref.key;
104 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
105 c2_beg = chain2->bref.key;
106 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
108 if (c1_end < c2_beg) /* fully to the left */
110 if (c1_beg > c2_end) /* fully to the right */
112 return(0); /* overlap (must not cross edge boundary) */
116 * Assert that a chain has no media data associated with it.
119 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
121 KKASSERT(chain->dio == NULL);
122 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
123 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
125 panic("hammer2_assert_no_data: chain %p still has data", chain);
130 * Make a chain visible to the flusher. The flusher needs to be able to
131 * do flushes of subdirectory chains or single files so it does a top-down
132 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
133 * or UPDATE chains and flushes back up the chain to the volume root.
135 * This routine sets ONFLUSH upward until it hits the volume root. For
136 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
137 * Extra ONFLUSH flagging doesn't hurt the filesystem.
140 hammer2_chain_setflush(hammer2_chain_t *chain)
142 hammer2_chain_t *parent;
144 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 hammer2_spin_sh(&chain->core.spin);
146 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
147 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
148 if ((parent = chain->parent) == NULL)
150 hammer2_spin_sh(&parent->core.spin);
151 hammer2_spin_unsh(&chain->core.spin);
154 hammer2_spin_unsh(&chain->core.spin);
159 * Allocate a new disconnected chain element representing the specified
160 * bref. chain->refs is set to 1 and the passed bref is copied to
161 * chain->bref. chain->bytes is derived from the bref.
163 * chain->pmp inherits pmp unless the chain is an inode (other than the
166 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
169 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
170 hammer2_blockref_t *bref)
172 hammer2_chain_t *chain;
176 * Special case - radix of 0 indicates a chain that does not
177 * need a data reference (context is completely embedded in the
180 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
181 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
185 atomic_add_long(&hammer2_chain_allocs, 1);
188 * Construct the appropriate system structure.
191 case HAMMER2_BREF_TYPE_DIRENT:
192 case HAMMER2_BREF_TYPE_INODE:
193 case HAMMER2_BREF_TYPE_INDIRECT:
194 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
195 case HAMMER2_BREF_TYPE_DATA:
196 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
198 * Chain's are really only associated with the hmp but we
199 * maintain a pmp association for per-mount memory tracking
200 * purposes. The pmp can be NULL.
202 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
204 case HAMMER2_BREF_TYPE_VOLUME:
205 case HAMMER2_BREF_TYPE_FREEMAP:
207 * Only hammer2_chain_bulksnap() calls this function with these
210 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
214 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
219 * Initialize the new chain structure. pmp must be set to NULL for
220 * chains belonging to the super-root topology of a device mount.
222 if (pmp == hmp->spmp)
228 chain->bytes = bytes;
230 chain->flags = HAMMER2_CHAIN_ALLOCATED;
233 * Set the PFS boundary flag if this chain represents a PFS root.
235 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
236 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
237 hammer2_chain_core_init(chain);
243 * Initialize a chain's core structure. This structure used to be allocated
244 * but is now embedded.
246 * The core is not locked. No additional refs on the chain are made.
247 * (trans) must not be NULL if (core) is not NULL.
250 hammer2_chain_core_init(hammer2_chain_t *chain)
253 * Fresh core under nchain (no multi-homing of ochain's
256 RB_INIT(&chain->core.rbtree); /* live chains */
257 hammer2_mtx_init(&chain->lock, "h2chain");
261 * Add a reference to a chain element, preventing its destruction.
263 * (can be called with spinlock held)
266 hammer2_chain_ref(hammer2_chain_t *chain)
268 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
270 * 0->non-zero transition must ensure that chain is removed
273 * NOTE: Already holding lru_spin here so we cannot call
274 * hammer2_chain_ref() to get it off lru_list, do
277 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
278 hammer2_pfs_t *pmp = chain->pmp;
279 hammer2_spin_ex(&pmp->lru_spin);
280 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
281 atomic_add_int(&pmp->lru_count, -1);
282 atomic_clear_int(&chain->flags,
283 HAMMER2_CHAIN_ONLRU);
284 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
286 hammer2_spin_unex(&pmp->lru_spin);
290 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
296 * Ref a locked chain and force the data to be held across an unlock.
297 * Chain must be currently locked. The user of the chain who desires
298 * to release the hold must call hammer2_chain_lock_unhold() to relock
299 * and unhold the chain, then unlock normally, or may simply call
300 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
303 hammer2_chain_ref_hold(hammer2_chain_t *chain)
305 atomic_add_int(&chain->lockcnt, 1);
306 hammer2_chain_ref(chain);
310 * Insert the chain in the core rbtree.
312 * Normal insertions are placed in the live rbtree. Insertion of a deleted
313 * chain is a special case used by the flush code that is placed on the
314 * unstaged deleted list to avoid confusing the live view.
316 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
317 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
318 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
322 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
323 int flags, int generation)
325 hammer2_chain_t *xchain;
328 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
329 hammer2_spin_ex(&parent->core.spin);
332 * Interlocked by spinlock, check for race
334 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
335 parent->core.generation != generation) {
336 error = HAMMER2_ERROR_EAGAIN;
343 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
344 KASSERT(xchain == NULL,
345 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
346 chain, xchain, chain->bref.key));
347 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
348 chain->parent = parent;
349 ++parent->core.chain_count;
350 ++parent->core.generation; /* XXX incs for _get() too, XXX */
353 * We have to keep track of the effective live-view blockref count
354 * so the create code knows when to push an indirect block.
356 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
357 atomic_add_int(&parent->core.live_count, 1);
359 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
360 hammer2_spin_unex(&parent->core.spin);
365 * Drop the caller's reference to the chain. When the ref count drops to
366 * zero this function will try to disassociate the chain from its parent and
367 * deallocate it, then recursely drop the parent using the implied ref
368 * from the chain's chain->parent.
370 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
371 * races an acquisition by another cpu. Therefore we can loop if we are
372 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
373 * race against another drop.
375 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
378 hammer2_chain_drop(hammer2_chain_t *chain)
382 if (hammer2_debug & 0x200000)
385 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
389 KKASSERT(chain->refs > 0);
397 if (mtx_lock_ex_try(&chain->lock) == 0)
398 chain = hammer2_chain_lastdrop(chain);
399 /* retry the same chain */
401 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
403 /* retry the same chain */
410 * Unhold a held and probably not-locked chain, ensure that the data is
411 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
412 * lock and then simply unlocking the chain.
415 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
421 lockcnt = chain->lockcnt;
424 if (atomic_cmpset_int(&chain->lockcnt,
425 lockcnt, lockcnt - 1)) {
428 } else if (mtx_lock_ex_try(&chain->lock) == 0) {
429 hammer2_chain_unlock(chain);
433 * This situation can easily occur on SMP due to
434 * the gap inbetween the 1->0 transition and the
435 * final unlock. We cannot safely block on the
436 * mutex because lockcnt might go above 1.
438 * XXX Sleep for one tick if it takes too long.
441 if (iter > 1000 + hz) {
442 kprintf("hammer2: h2race1 %p\n", chain);
445 tsleep(&iter, 0, "h2race1", 1);
450 hammer2_chain_drop(chain);
454 * Handles the (potential) last drop of chain->refs from 1->0. Called with
455 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
456 * possible against refs and lockcnt. We must dispose of the mutex on chain.
458 * This function returns an unlocked chain for recursive drop or NULL. It
459 * can return the same chain if it determines it has raced another ref.
463 * When two chains need to be recursively dropped we use the chain we
464 * would otherwise free to placehold the additional chain. It's a bit
465 * convoluted but we can't just recurse without potentially blowing out
468 * The chain cannot be freed if it has any children.
469 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
470 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
471 * Any dedup registration can remain intact.
473 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
477 hammer2_chain_lastdrop(hammer2_chain_t *chain)
481 hammer2_chain_t *parent;
482 hammer2_chain_t *rdrop;
489 * On last drop if there is no parent and data_off is good (at
490 * least does not represent the volume root), the modified chain
491 * is probably going to be destroyed. We have to make sure that
492 * the data area is not registered for dedup.
494 * XXX removed. In fact, we do not have to make sure that the
495 * data area is not registered for dedup. The data area
496 * can, in fact, still be used for dedup because it is
497 * still allocated in the freemap and the underlying I/O
498 * will still be flushed.
500 if (chain->parent == NULL &&
501 (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
502 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
504 hammer2_io_dedup_delete(hmp, chain->bref.type,
505 chain->bref.data_off, chain->bytes);
509 * We need chain's spinlock to interlock the sub-tree test.
510 * We already have chain's mutex, protecting chain->parent.
512 * Remember that chain->refs can be in flux.
514 hammer2_spin_ex(&chain->core.spin);
516 if ((parent = chain->parent) != NULL) {
518 * If the chain has a parent the UPDATE bit prevents scrapping
519 * as the chain is needed to properly flush the parent. Try
520 * to complete the 1->0 transition and return NULL. Retry
521 * (return chain) if we are unable to complete the 1->0
522 * transition, else return NULL (nothing more to do).
524 * If the chain has a parent the MODIFIED bit prevents
527 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
529 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
530 HAMMER2_CHAIN_MODIFIED)) {
531 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
532 hammer2_spin_unex(&chain->core.spin);
534 dio = hammer2_chain_drop_data(chain, 0);
536 hammer2_io_bqrelse(&dio);
538 hammer2_chain_assert_no_data(chain);
539 hammer2_mtx_unlock(&chain->lock);
542 hammer2_spin_unex(&chain->core.spin);
543 hammer2_mtx_unlock(&chain->lock);
547 /* spinlock still held */
550 * The chain has no parent and can be flagged for destruction.
551 * Since it has no parent, UPDATE can also be cleared.
553 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
554 if (chain->flags & HAMMER2_CHAIN_UPDATE)
555 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
558 * If the chain has children we must still flush the chain.
559 * Any dedup is already handled by the underlying DIO, so
560 * we do not have to specifically flush it here.
562 * In the case where it has children, the DESTROY flag test
563 * in the flush code will prevent unnecessary flushes of
564 * MODIFIED chains that are not flagged DEDUP so don't worry
567 if (chain->core.chain_count) {
569 * Put on flushq (should ensure refs > 1), retry
572 hammer2_spin_unex(&chain->core.spin);
573 hammer2_delayed_flush(chain);
574 hammer2_mtx_unlock(&chain->lock);
576 return(chain); /* retry drop */
580 * Otherwise we can scrap the MODIFIED bit if it is set,
581 * and continue along the freeing path.
583 * Be sure to clean-out any dedup bits. Without a parent
584 * this chain will no longer be visible to the flush code.
585 * Easy check data_off to avoid the volume root.
587 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
588 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
589 atomic_add_long(&hammer2_count_modified_chains, -1);
591 hammer2_pfs_memory_wakeup(chain->pmp);
593 /* spinlock still held */
596 /* spinlock still held */
602 * If any children exist we must leave the chain intact with refs == 0.
603 * They exist because chains are retained below us which have refs or
604 * may require flushing.
606 * Retry (return chain) if we fail to transition the refs to 0, else
607 * return NULL indication nothing more to do.
609 * Chains with children are NOT put on the LRU list.
611 if (chain->core.chain_count) {
612 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
613 hammer2_spin_unex(&chain->core.spin);
614 hammer2_chain_assert_no_data(chain);
615 hammer2_mtx_unlock(&chain->lock);
618 hammer2_spin_unex(&chain->core.spin);
619 hammer2_mtx_unlock(&chain->lock);
623 /* spinlock still held */
624 /* no chains left under us */
627 * chain->core has no children left so no accessors can get to our
628 * chain from there. Now we have to lock the parent core to interlock
629 * remaining possible accessors that might bump chain's refs before
630 * we can safely drop chain's refs with intent to free the chain.
633 pmp = chain->pmp; /* can be NULL */
636 parent = chain->parent;
639 * WARNING! chain's spin lock is still held here, and other spinlocks
640 * will be acquired and released in the code below. We
641 * cannot be making fancy procedure calls!
645 * We can cache the chain if it is associated with a pmp
646 * and not flagged as being destroyed or requesting a full
647 * release. In this situation the chain is not removed
648 * from its parent, i.e. it can still be looked up.
650 * We intentionally do not cache DATA chains because these
651 * were likely used to load data into the logical buffer cache
652 * and will not be accessed again for some time.
655 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
657 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
659 hammer2_spin_ex(&parent->core.spin);
660 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
662 * 1->0 transition failed, retry. Do not drop
663 * the chain's data yet!
666 hammer2_spin_unex(&parent->core.spin);
667 hammer2_spin_unex(&chain->core.spin);
668 hammer2_mtx_unlock(&chain->lock);
677 dio = hammer2_chain_drop_data(chain, 1);
679 hammer2_chain_assert_no_data(chain);
681 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
682 hammer2_spin_ex(&pmp->lru_spin);
683 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
684 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
687 * If we are over the LRU limit we need to drop something.
689 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
690 rdrop = TAILQ_FIRST(&pmp->lru_list);
691 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
692 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
693 atomic_add_int(&rdrop->refs, 1);
694 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
696 atomic_add_int(&pmp->lru_count, 1);
698 hammer2_spin_unex(&pmp->lru_spin);
700 hammer2_spin_unex(&parent->core.spin);
701 parent = NULL; /* safety */
703 hammer2_spin_unex(&chain->core.spin);
704 hammer2_mtx_unlock(&chain->lock);
707 hammer2_io_bqrelse(&dio);
715 * Spinlock the parent and try to drop the last ref on chain.
716 * On success determine if we should dispose of the chain
717 * (remove the chain from its parent, etc).
719 * (normal core locks are top-down recursive but we define
720 * core spinlocks as bottom-up recursive, so this is safe).
723 hammer2_spin_ex(&parent->core.spin);
724 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
726 /* XXX remove, don't try to drop data on fail */
727 hammer2_spin_unex(&parent->core.spin);
728 dio = hammer2_chain_drop_data(chain, 0);
729 hammer2_spin_unex(&chain->core.spin);
731 hammer2_io_bqrelse(&dio);
734 * 1->0 transition failed, retry.
736 hammer2_spin_unex(&parent->core.spin);
737 hammer2_spin_unex(&chain->core.spin);
738 hammer2_mtx_unlock(&chain->lock);
744 * 1->0 transition successful, parent spin held to prevent
745 * new lookups, chain spinlock held to protect parent field.
746 * Remove chain from the parent.
748 * If the chain is being removed from the parent's btree but
749 * is not bmapped, we have to adjust live_count downward. If
750 * it is bmapped then the blockref is retained in the parent
751 * as is its associated live_count. This case can occur when
752 * a chain added to the topology is unable to flush and is
753 * then later deleted.
755 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
756 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
757 (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
758 atomic_add_int(&parent->core.live_count, -1);
760 RB_REMOVE(hammer2_chain_tree,
761 &parent->core.rbtree, chain);
762 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
763 --parent->core.chain_count;
764 chain->parent = NULL;
768 * If our chain was the last chain in the parent's core the
769 * core is now empty and its parent might have to be
770 * re-dropped if it has 0 refs.
772 if (parent->core.chain_count == 0) {
774 atomic_add_int(&rdrop->refs, 1);
776 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
780 hammer2_spin_unex(&parent->core.spin);
781 parent = NULL; /* safety */
787 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
789 * 1->0 transition failed, retry.
791 hammer2_spin_unex(&parent->core.spin);
792 hammer2_spin_unex(&chain->core.spin);
793 hammer2_mtx_unlock(&chain->lock);
800 * Successful 1->0 transition, no parent, no children... no way for
801 * anyone to ref this chain any more. We can clean-up and free it.
803 * We still have the core spinlock, and core's chain_count is 0.
804 * Any parent spinlock is gone.
806 hammer2_spin_unex(&chain->core.spin);
807 hammer2_chain_assert_no_data(chain);
808 hammer2_mtx_unlock(&chain->lock);
809 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
810 chain->core.chain_count == 0);
813 * All locks are gone, no pointers remain to the chain, finish
816 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
817 HAMMER2_CHAIN_MODIFIED)) == 0);
819 dio = hammer2_chain_drop_data(chain, 1);
821 hammer2_io_bqrelse(&dio);
825 * Once chain resources are gone we can use the now dead chain
826 * structure to placehold what might otherwise require a recursive
827 * drop, because we have potentially two things to drop and can only
828 * return one directly.
830 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
831 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
833 kfree(chain, hmp->mchain);
837 * Possible chaining loop when parent re-drop needed.
843 * On last lock release.
845 static hammer2_io_t *
846 hammer2_chain_drop_data(hammer2_chain_t *chain)
850 if ((dio = chain->dio) != NULL) {
854 switch(chain->bref.type) {
855 case HAMMER2_BREF_TYPE_VOLUME:
856 case HAMMER2_BREF_TYPE_FREEMAP:
859 if (chain->data != NULL) {
860 hammer2_spin_unex(&chain->core.spin);
861 panic("chain data not null: "
862 "chain %p bref %016jx.%02x "
863 "refs %d parent %p dio %p data %p",
864 chain, chain->bref.data_off,
865 chain->bref.type, chain->refs,
867 chain->dio, chain->data);
869 KKASSERT(chain->data == NULL);
877 * Lock a referenced chain element, acquiring its data with I/O if necessary,
878 * and specify how you would like the data to be resolved.
880 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
882 * The lock is allowed to recurse, multiple locking ops will aggregate
883 * the requested resolve types. Once data is assigned it will not be
884 * removed until the last unlock.
886 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
887 * (typically used to avoid device/logical buffer
890 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
891 * the INITIAL-create state (indirect blocks only).
893 * Do not resolve data elements for DATA chains.
894 * (typically used to avoid device/logical buffer
897 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
899 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
900 * it will be locked exclusive.
902 * NOTE: Embedded elements (volume header, inodes) are always resolved
905 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
906 * element will instantiate and zero its buffer, and flush it on
909 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
910 * so as not to instantiate a device buffer, which could alias against
911 * a logical file buffer. However, if ALWAYS is specified the
912 * device buffer will be instantiated anyway.
914 * WARNING! This function blocks on I/O if data needs to be fetched. This
915 * blocking can run concurrent with other compatible lock holders
916 * who do not need data returning. The lock is not upgraded to
917 * exclusive during a data fetch, a separate bit is used to
918 * interlock I/O. However, an exclusive lock holder can still count
919 * on being interlocked against an I/O fetch managed by a shared
923 hammer2_chain_lock(hammer2_chain_t *chain, int how)
926 * Ref and lock the element. Recursive locks are allowed.
928 KKASSERT(chain->refs > 0);
929 atomic_add_int(&chain->lockcnt, 1);
932 * Get the appropriate lock. If LOCKAGAIN is flagged with SHARED
933 * the caller expects a shared lock to already be present and we
934 * are giving it another ref. This case must importantly not block
935 * if there is a pending exclusive lock request.
937 if (how & HAMMER2_RESOLVE_SHARED) {
938 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
939 hammer2_mtx_sh_again(&chain->lock);
941 hammer2_mtx_sh(&chain->lock);
944 hammer2_mtx_ex(&chain->lock);
946 ++curthread->td_tracker;
949 * If we already have a valid data pointer no further action is
956 * Do we have to resolve the data? This is generally only
957 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
958 * Other BREF types expects the data to be there.
960 switch(how & HAMMER2_RESOLVE_MASK) {
961 case HAMMER2_RESOLVE_NEVER:
963 case HAMMER2_RESOLVE_MAYBE:
964 if (chain->flags & HAMMER2_CHAIN_INITIAL)
966 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
969 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
971 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
975 case HAMMER2_RESOLVE_ALWAYS:
981 * Caller requires data
983 hammer2_chain_load_data(chain);
987 * Lock the chain, retain the hold, and drop the data persistence count.
988 * The data should remain valid because we never transitioned lockcnt
992 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
994 hammer2_chain_lock(chain, how);
995 atomic_add_int(&chain->lockcnt, -1);
1000 * Downgrade an exclusive chain lock to a shared chain lock.
1002 * NOTE: There is no upgrade equivalent due to the ease of
1003 * deadlocks in that direction.
1006 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1008 hammer2_mtx_downgrade(&chain->lock);
1013 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1014 * may be of any type.
1016 * Once chain->data is set it cannot be disposed of until all locks are
1020 hammer2_chain_load_data(hammer2_chain_t *chain)
1022 hammer2_blockref_t *bref;
1029 * Degenerate case, data already present, or chain has no media
1030 * reference to load.
1034 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1038 KKASSERT(hmp != NULL);
1041 * Gain the IOINPROG bit, interlocked block.
1047 oflags = chain->flags;
1049 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1050 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1051 tsleep_interlock(&chain->flags, 0);
1052 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1053 tsleep(&chain->flags, PINTERLOCKED,
1058 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1059 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1067 * We own CHAIN_IOINPROG
1069 * Degenerate case if we raced another load.
1075 * We must resolve to a device buffer, either by issuing I/O or
1076 * by creating a zero-fill element. We do not mark the buffer
1077 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1078 * API must still be used to do that).
1080 * The device buffer is variable-sized in powers of 2 down
1081 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1082 * chunk always contains buffers of the same size. (XXX)
1084 * The minimum physical IO size may be larger than the variable
1087 bref = &chain->bref;
1090 * The getblk() optimization can only be used on newly created
1091 * elements if the physical block size matches the request.
1093 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1094 error = hammer2_io_new(hmp, bref->type,
1095 bref->data_off, chain->bytes,
1098 error = hammer2_io_bread(hmp, bref->type,
1099 bref->data_off, chain->bytes,
1101 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1104 chain->error = HAMMER2_ERROR_EIO;
1105 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1106 (intmax_t)bref->data_off, error);
1107 hammer2_io_bqrelse(&chain->dio);
1113 * This isn't perfect and can be ignored on OSs which do not have
1114 * an indication as to whether a buffer is coming from cache or
1115 * if I/O was actually issued for the read. TESTEDGOOD will work
1116 * pretty well without the B_IOISSUED logic because chains are
1117 * cached, but in that situation (without B_IOISSUED) it will not
1118 * detect whether a re-read via I/O is corrupted verses the original
1121 * We can't re-run the CRC on every fresh lock. That would be
1122 * insanely expensive.
1124 * If the underlying kernel buffer covers the entire chain we can
1125 * use the B_IOISSUED indication to determine if we have to re-run
1126 * the CRC on chain data for chains that managed to stay cached
1127 * across the kernel disposal of the original buffer.
1129 if ((dio = chain->dio) != NULL && dio->bp) {
1130 struct buf *bp = dio->bp;
1132 if (dio->psize == chain->bytes &&
1133 (bp->b_flags & B_IOISSUED)) {
1134 atomic_clear_int(&chain->flags,
1135 HAMMER2_CHAIN_TESTEDGOOD);
1136 bp->b_flags &= ~B_IOISSUED;
1141 * NOTE: A locked chain's data cannot be modified without first
1142 * calling hammer2_chain_modify().
1146 * Clear INITIAL. In this case we used io_new() and the buffer has
1147 * been zero'd and marked dirty.
1149 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1151 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1152 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1153 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1154 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1156 * check data not currently synchronized due to
1157 * modification. XXX assumes data stays in the buffer
1158 * cache, which might not be true (need biodep on flush
1159 * to calculate crc? or simple crc?).
1161 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1162 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1163 chain->error = HAMMER2_ERROR_CHECK;
1165 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1170 * Setup the data pointer, either pointing it to an embedded data
1171 * structure and copying the data from the buffer, or pointing it
1174 * The buffer is not retained when copying to an embedded data
1175 * structure in order to avoid potential deadlocks or recursions
1176 * on the same physical buffer.
1178 * WARNING! Other threads can start using the data the instant we
1179 * set chain->data non-NULL.
1181 switch (bref->type) {
1182 case HAMMER2_BREF_TYPE_VOLUME:
1183 case HAMMER2_BREF_TYPE_FREEMAP:
1185 * Copy data from bp to embedded buffer
1187 panic("hammer2_chain_load_data: unresolved volume header");
1189 case HAMMER2_BREF_TYPE_DIRENT:
1190 KKASSERT(chain->bytes != 0);
1192 case HAMMER2_BREF_TYPE_INODE:
1193 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1194 case HAMMER2_BREF_TYPE_INDIRECT:
1195 case HAMMER2_BREF_TYPE_DATA:
1196 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1199 * Point data at the device buffer and leave dio intact.
1201 chain->data = (void *)bdata;
1206 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1213 oflags = chain->flags;
1214 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1215 HAMMER2_CHAIN_IOSIGNAL);
1216 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1217 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1218 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1219 wakeup(&chain->flags);
1226 * Unlock and deref a chain element.
1228 * Remember that the presence of children under chain prevent the chain's
1229 * destruction but do not add additional references, so the dio will still
1233 hammer2_chain_unlock(hammer2_chain_t *chain)
1239 --curthread->td_tracker;
1242 * If multiple locks are present (or being attempted) on this
1243 * particular chain we can just unlock, drop refs, and return.
1245 * Otherwise fall-through on the 1->0 transition.
1248 lockcnt = chain->lockcnt;
1249 KKASSERT(lockcnt > 0);
1252 if (atomic_cmpset_int(&chain->lockcnt,
1253 lockcnt, lockcnt - 1)) {
1254 hammer2_mtx_unlock(&chain->lock);
1257 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1258 /* while holding the mutex exclusively */
1259 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1263 * This situation can easily occur on SMP due to
1264 * the gap inbetween the 1->0 transition and the
1265 * final unlock. We cannot safely block on the
1266 * mutex because lockcnt might go above 1.
1268 * XXX Sleep for one tick if it takes too long.
1270 if (++iter > 1000) {
1271 if (iter > 1000 + hz) {
1272 kprintf("hammer2: h2race2 %p\n", chain);
1275 tsleep(&iter, 0, "h2race2", 1);
1283 * Last unlock / mutex upgraded to exclusive. Drop the data
1286 dio = hammer2_chain_drop_data(chain);
1288 hammer2_io_bqrelse(&dio);
1289 hammer2_mtx_unlock(&chain->lock);
1293 * Unlock and hold chain data intact
1296 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1298 atomic_add_int(&chain->lockcnt, 1);
1299 hammer2_chain_unlock(chain);
1303 * Helper to obtain the blockref[] array base and count for a chain.
1305 * XXX Not widely used yet, various use cases need to be validated and
1306 * converted to use this function.
1309 hammer2_blockref_t *
1310 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1312 hammer2_blockref_t *base;
1315 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1318 switch(parent->bref.type) {
1319 case HAMMER2_BREF_TYPE_INODE:
1320 count = HAMMER2_SET_COUNT;
1322 case HAMMER2_BREF_TYPE_INDIRECT:
1323 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1324 count = parent->bytes / sizeof(hammer2_blockref_t);
1326 case HAMMER2_BREF_TYPE_VOLUME:
1327 count = HAMMER2_SET_COUNT;
1329 case HAMMER2_BREF_TYPE_FREEMAP:
1330 count = HAMMER2_SET_COUNT;
1333 panic("hammer2_chain_create_indirect: "
1334 "unrecognized blockref type: %d",
1340 switch(parent->bref.type) {
1341 case HAMMER2_BREF_TYPE_INODE:
1342 base = &parent->data->ipdata.u.blockset.blockref[0];
1343 count = HAMMER2_SET_COUNT;
1345 case HAMMER2_BREF_TYPE_INDIRECT:
1346 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1347 base = &parent->data->npdata[0];
1348 count = parent->bytes / sizeof(hammer2_blockref_t);
1350 case HAMMER2_BREF_TYPE_VOLUME:
1351 base = &parent->data->voldata.
1352 sroot_blockset.blockref[0];
1353 count = HAMMER2_SET_COUNT;
1355 case HAMMER2_BREF_TYPE_FREEMAP:
1356 base = &parent->data->blkset.blockref[0];
1357 count = HAMMER2_SET_COUNT;
1360 panic("hammer2_chain_create_indirect: "
1361 "unrecognized blockref type: %d",
1373 * This counts the number of live blockrefs in a block array and
1374 * also calculates the point at which all remaining blockrefs are empty.
1375 * This routine can only be called on a live chain.
1377 * Caller holds the chain locked, but possibly with a shared lock. We
1378 * must use an exclusive spinlock to prevent corruption.
1380 * NOTE: Flag is not set until after the count is complete, allowing
1381 * callers to test the flag without holding the spinlock.
1383 * NOTE: If base is NULL the related chain is still in the INITIAL
1384 * state and there are no blockrefs to count.
1386 * NOTE: live_count may already have some counts accumulated due to
1387 * creation and deletion and could even be initially negative.
1390 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1391 hammer2_blockref_t *base, int count)
1393 hammer2_spin_ex(&chain->core.spin);
1394 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1396 while (--count >= 0) {
1397 if (base[count].type)
1400 chain->core.live_zero = count + 1;
1401 while (count >= 0) {
1402 if (base[count].type)
1403 atomic_add_int(&chain->core.live_count,
1408 chain->core.live_zero = 0;
1410 /* else do not modify live_count */
1411 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1413 hammer2_spin_unex(&chain->core.spin);
1417 * Resize the chain's physical storage allocation in-place. This function does
1418 * not usually adjust the data pointer and must be followed by (typically) a
1419 * hammer2_chain_modify() call to copy any old data over and adjust the
1422 * Chains can be resized smaller without reallocating the storage. Resizing
1423 * larger will reallocate the storage. Excess or prior storage is reclaimed
1424 * asynchronously at a later time.
1426 * An nradix value of 0 is special-cased to mean that the storage should
1427 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1430 * Must be passed an exclusively locked parent and chain.
1432 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1433 * to avoid instantiating a device buffer that conflicts with the vnode data
1434 * buffer. However, because H2 can compress or encrypt data, the chain may
1435 * have a dio assigned to it in those situations, and they do not conflict.
1437 * XXX return error if cannot resize.
1440 hammer2_chain_resize(hammer2_chain_t *chain,
1441 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1442 int nradix, int flags)
1452 * Only data and indirect blocks can be resized for now.
1453 * (The volu root, inodes, and freemap elements use a fixed size).
1455 KKASSERT(chain != &hmp->vchain);
1456 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1457 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1458 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1461 * Nothing to do if the element is already the proper size
1463 obytes = chain->bytes;
1464 nbytes = (nradix) ? (1U << nradix) : 0;
1465 if (obytes == nbytes)
1466 return (chain->error);
1469 * Make sure the old data is instantiated so we can copy it. If this
1470 * is a data block, the device data may be superfluous since the data
1471 * might be in a logical block, but compressed or encrypted data is
1474 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1476 error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1481 * Relocate the block, even if making it smaller (because different
1482 * block sizes may be in different regions).
1484 * NOTE: Operation does not copy the data and may only be used
1485 * to resize data blocks in-place, or directory entry blocks
1486 * which are about to be modified in some manner.
1488 error = hammer2_freemap_alloc(chain, nbytes);
1492 chain->bytes = nbytes;
1495 * We don't want the followup chain_modify() to try to copy data
1496 * from the old (wrong-sized) buffer. It won't know how much to
1497 * copy. This case should only occur during writes when the
1498 * originator already has the data to write in-hand.
1501 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1502 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1503 hammer2_io_brelse(&chain->dio);
1506 return (chain->error);
1510 * Set the chain modified so its data can be changed by the caller, or
1511 * install deduplicated data. The caller must call this routine for each
1512 * set of modifications it makes, even if the chain is already flagged
1515 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1516 * is a CLC (cluster level change) field and is not updated by parent
1517 * propagation during a flush.
1519 * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1520 * chain->error except for HAMMER2_ERROR_ENOSPC. If the allocation fails
1521 * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1522 * remains unmodified with its old data ref intact and chain->error
1527 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1528 * even if the chain is still flagged MODIFIED. In this case the chain's
1529 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1531 * If the caller passes a non-zero dedup_off we will use it to assign the
1532 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1533 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1534 * must not modify the data content upon return.
1537 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1538 hammer2_off_t dedup_off, int flags)
1540 hammer2_blockref_t obref;
1551 obref = chain->bref;
1552 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1555 * Data is not optional for freemap chains (we must always be sure
1556 * to copy the data on COW storage allocations).
1558 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1559 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1560 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1561 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1565 * Data must be resolved if already assigned, unless explicitly
1566 * flagged otherwise. If we cannot safety load the data the
1567 * modification fails and we return early.
1569 if (chain->data == NULL && chain->bytes != 0 &&
1570 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1571 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1572 hammer2_chain_load_data(chain);
1574 return (chain->error);
1579 * Set MODIFIED to indicate that the chain has been modified. A new
1580 * allocation is required when modifying a chain.
1582 * Set UPDATE to ensure that the blockref is updated in the parent.
1584 * If MODIFIED is already set determine if we can reuse the assigned
1585 * data block or if we need a new data block.
1587 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1589 * Must set modified bit.
1591 atomic_add_long(&hammer2_count_modified_chains, 1);
1592 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1593 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1597 * We may be able to avoid a copy-on-write if the chain's
1598 * check mode is set to NONE and the chain's current
1599 * modify_tid is beyond the last explicit snapshot tid.
1601 * This implements HAMMER2's overwrite-in-place feature.
1603 * NOTE! This data-block cannot be used as a de-duplication
1604 * source when the check mode is set to NONE.
1606 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1607 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1608 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1609 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1610 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1611 HAMMER2_CHECK_NONE &&
1613 chain->bref.modify_tid >
1614 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1616 * Sector overwrite allowed.
1621 * Sector overwrite not allowed, must copy-on-write.
1625 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1627 * If the modified chain was registered for dedup we need
1628 * a new allocation. This only happens for delayed-flush
1629 * chains (i.e. which run through the front-end buffer
1636 * Already flagged modified, no new allocation is needed.
1643 * Flag parent update required.
1645 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1646 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1653 * The modification or re-modification requires an allocation and
1654 * possible COW. If an error occurs, the previous content and data
1655 * reference is retained and the modification fails.
1657 * If dedup_off is non-zero, the caller is requesting a deduplication
1658 * rather than a modification. The MODIFIED bit is not set and the
1659 * data offset is set to the deduplication offset. The data cannot
1662 * NOTE: The dedup offset is allowed to be in a partially free state
1663 * and we must be sure to reset it to a fully allocated state
1664 * to force two bulkfree passes to free it again.
1666 * NOTE: Only applicable when chain->bytes != 0.
1668 * XXX can a chain already be marked MODIFIED without a data
1669 * assignment? If not, assert here instead of testing the case.
1671 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1673 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1677 * NOTE: We do not have to remove the dedup
1678 * registration because the area is still
1679 * allocated and the underlying DIO will
1683 chain->bref.data_off = dedup_off;
1684 chain->bytes = 1 << (dedup_off &
1685 HAMMER2_OFF_MASK_RADIX);
1687 atomic_clear_int(&chain->flags,
1688 HAMMER2_CHAIN_MODIFIED);
1689 atomic_add_long(&hammer2_count_modified_chains,
1692 hammer2_pfs_memory_wakeup(chain->pmp);
1693 hammer2_freemap_adjust(hmp, &chain->bref,
1694 HAMMER2_FREEMAP_DORECOVER);
1695 atomic_set_int(&chain->flags,
1696 HAMMER2_CHAIN_DEDUPABLE);
1698 error = hammer2_freemap_alloc(chain,
1700 atomic_clear_int(&chain->flags,
1701 HAMMER2_CHAIN_DEDUPABLE);
1707 * Stop here if error. We have to undo any flag bits we might
1712 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1713 atomic_add_long(&hammer2_count_modified_chains, -1);
1715 hammer2_pfs_memory_wakeup(chain->pmp);
1718 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1724 * Update mirror_tid and modify_tid. modify_tid is only updated
1725 * if not passed as zero (during flushes, parent propagation passes
1728 * NOTE: chain->pmp could be the device spmp.
1730 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1732 chain->bref.modify_tid = mtid;
1735 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1736 * requires updating as well as to tell the delete code that the
1737 * chain's blockref might not exactly match (in terms of physical size
1738 * or block offset) the one in the parent's blocktable. The base key
1739 * of course will still match.
1741 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1742 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1745 * Short-cut data blocks which the caller does not need an actual
1746 * data reference to (aka OPTDATA), as long as the chain does not
1747 * already have a data pointer to the data. This generally means
1748 * that the modifications are being done via the logical buffer cache.
1749 * The INITIAL flag relates only to the device data buffer and thus
1750 * remains unchange in this situation.
1752 * This code also handles bytes == 0 (most dirents).
1754 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1755 (flags & HAMMER2_MODIFY_OPTDATA) &&
1756 chain->data == NULL) {
1757 KKASSERT(chain->dio == NULL);
1762 * Clearing the INITIAL flag (for indirect blocks) indicates that
1763 * we've processed the uninitialized storage allocation.
1765 * If this flag is already clear we are likely in a copy-on-write
1766 * situation but we have to be sure NOT to bzero the storage if
1767 * no data is present.
1769 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1770 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1777 * Instantiate data buffer and possibly execute COW operation
1779 switch(chain->bref.type) {
1780 case HAMMER2_BREF_TYPE_VOLUME:
1781 case HAMMER2_BREF_TYPE_FREEMAP:
1783 * The data is embedded, no copy-on-write operation is
1786 KKASSERT(chain->dio == NULL);
1788 case HAMMER2_BREF_TYPE_DIRENT:
1790 * The data might be fully embedded.
1792 if (chain->bytes == 0) {
1793 KKASSERT(chain->dio == NULL);
1797 case HAMMER2_BREF_TYPE_INODE:
1798 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1799 case HAMMER2_BREF_TYPE_DATA:
1800 case HAMMER2_BREF_TYPE_INDIRECT:
1801 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1803 * Perform the copy-on-write operation
1805 * zero-fill or copy-on-write depending on whether
1806 * chain->data exists or not and set the dirty state for
1807 * the new buffer. hammer2_io_new() will handle the
1810 * If a dedup_off was supplied this is an existing block
1811 * and no COW, copy, or further modification is required.
1813 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1815 if (wasinitial && dedup_off == 0) {
1816 error = hammer2_io_new(hmp, chain->bref.type,
1817 chain->bref.data_off,
1818 chain->bytes, &dio);
1820 error = hammer2_io_bread(hmp, chain->bref.type,
1821 chain->bref.data_off,
1822 chain->bytes, &dio);
1824 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1827 * If an I/O error occurs make sure callers cannot accidently
1828 * modify the old buffer's contents and corrupt the filesystem.
1831 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1833 chain->error = HAMMER2_ERROR_EIO;
1834 hammer2_io_brelse(&dio);
1835 hammer2_io_brelse(&chain->dio);
1840 bdata = hammer2_io_data(dio, chain->bref.data_off);
1844 * COW (unless a dedup).
1846 KKASSERT(chain->dio != NULL);
1847 if (chain->data != (void *)bdata && dedup_off == 0) {
1848 bcopy(chain->data, bdata, chain->bytes);
1850 } else if (wasinitial == 0) {
1852 * We have a problem. We were asked to COW but
1853 * we don't have any data to COW with!
1855 panic("hammer2_chain_modify: having a COW %p\n",
1860 * Retire the old buffer, replace with the new. Dirty or
1861 * redirty the new buffer.
1863 * WARNING! The system buffer cache may have already flushed
1864 * the buffer, so we must be sure to [re]dirty it
1865 * for further modification.
1867 * If dedup_off was supplied, the caller is not
1868 * expected to make any further modification to the
1872 hammer2_io_bqrelse(&chain->dio);
1873 chain->data = (void *)bdata;
1876 hammer2_io_setdirty(dio);
1879 panic("hammer2_chain_modify: illegal non-embedded type %d",
1886 * setflush on parent indicating that the parent must recurse down
1887 * to us. Do not call on chain itself which might already have it
1891 hammer2_chain_setflush(chain->parent);
1892 return (chain->error);
1896 * Modify the chain associated with an inode.
1899 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1900 hammer2_tid_t mtid, int flags)
1904 hammer2_inode_modify(ip);
1905 error = hammer2_chain_modify(chain, mtid, 0, flags);
1911 * Volume header data locks
1914 hammer2_voldata_lock(hammer2_dev_t *hmp)
1916 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1920 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1922 lockmgr(&hmp->vollk, LK_RELEASE);
1926 hammer2_voldata_modify(hammer2_dev_t *hmp)
1928 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1929 atomic_add_long(&hammer2_count_modified_chains, 1);
1930 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1931 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1936 * This function returns the chain at the nearest key within the specified
1937 * range. The returned chain will be referenced but not locked.
1939 * This function will recurse through chain->rbtree as necessary and will
1940 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1941 * the iteration value is less than the current value of *key_nextp.
1943 * The caller should use (*key_nextp) to calculate the actual range of
1944 * the returned element, which will be (key_beg to *key_nextp - 1), because
1945 * there might be another element which is superior to the returned element
1948 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1949 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1950 * it will wind up being (key_end + 1).
1952 * WARNING! Must be called with child's spinlock held. Spinlock remains
1953 * held through the operation.
1955 struct hammer2_chain_find_info {
1956 hammer2_chain_t *best;
1957 hammer2_key_t key_beg;
1958 hammer2_key_t key_end;
1959 hammer2_key_t key_next;
1962 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1963 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1967 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1968 hammer2_key_t key_beg, hammer2_key_t key_end)
1970 struct hammer2_chain_find_info info;
1973 info.key_beg = key_beg;
1974 info.key_end = key_end;
1975 info.key_next = *key_nextp;
1977 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1978 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1980 *key_nextp = info.key_next;
1982 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1983 parent, key_beg, key_end, *key_nextp);
1991 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1993 struct hammer2_chain_find_info *info = data;
1994 hammer2_key_t child_beg;
1995 hammer2_key_t child_end;
1997 child_beg = child->bref.key;
1998 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2000 if (child_end < info->key_beg)
2002 if (child_beg > info->key_end)
2009 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2011 struct hammer2_chain_find_info *info = data;
2012 hammer2_chain_t *best;
2013 hammer2_key_t child_end;
2016 * WARNING! Layerq is scanned forwards, exact matches should keep
2017 * the existing info->best.
2019 if ((best = info->best) == NULL) {
2021 * No previous best. Assign best
2024 } else if (best->bref.key <= info->key_beg &&
2025 child->bref.key <= info->key_beg) {
2030 /*info->best = child;*/
2031 } else if (child->bref.key < best->bref.key) {
2033 * Child has a nearer key and best is not flush with key_beg.
2034 * Set best to child. Truncate key_next to the old best key.
2037 if (info->key_next > best->bref.key || info->key_next == 0)
2038 info->key_next = best->bref.key;
2039 } else if (child->bref.key == best->bref.key) {
2041 * If our current best is flush with the child then this
2042 * is an illegal overlap.
2044 * key_next will automatically be limited to the smaller of
2045 * the two end-points.
2051 * Keep the current best but truncate key_next to the child's
2054 * key_next will also automatically be limited to the smaller
2055 * of the two end-points (probably not necessary for this case
2056 * but we do it anyway).
2058 if (info->key_next > child->bref.key || info->key_next == 0)
2059 info->key_next = child->bref.key;
2063 * Always truncate key_next based on child's end-of-range.
2065 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2066 if (child_end && (info->key_next > child_end || info->key_next == 0))
2067 info->key_next = child_end;
2073 * Retrieve the specified chain from a media blockref, creating the
2074 * in-memory chain structure which reflects it. The returned chain is
2075 * held but not locked. The caller must lock it to crc-check and
2076 * dereference its data, and should check chain->error after locking
2077 * before assuming that the data is good.
2079 * To handle insertion races pass the INSERT_RACE flag along with the
2080 * generation number of the core. NULL will be returned if the generation
2081 * number changes before we have a chance to insert the chain. Insert
2082 * races can occur because the parent might be held shared.
2084 * Caller must hold the parent locked shared or exclusive since we may
2085 * need the parent's bref array to find our block.
2087 * WARNING! chain->pmp is always set to NULL for any chain representing
2088 * part of the super-root topology.
2091 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2092 hammer2_blockref_t *bref)
2094 hammer2_dev_t *hmp = parent->hmp;
2095 hammer2_chain_t *chain;
2099 * Allocate a chain structure representing the existing media
2100 * entry. Resulting chain has one ref and is not locked.
2102 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2103 chain = hammer2_chain_alloc(hmp, NULL, bref);
2105 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2106 /* ref'd chain returned */
2109 * Flag that the chain is in the parent's blockmap so delete/flush
2110 * knows what to do with it.
2112 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2115 * Link the chain into its parent. A spinlock is required to safely
2116 * access the RBTREE, and it is possible to collide with another
2117 * hammer2_chain_get() operation because the caller might only hold
2118 * a shared lock on the parent.
2120 * NOTE: Get races can occur quite often when we distribute
2121 * asynchronous read-aheads across multiple threads.
2123 KKASSERT(parent->refs > 0);
2124 error = hammer2_chain_insert(parent, chain,
2125 HAMMER2_CHAIN_INSERT_SPIN |
2126 HAMMER2_CHAIN_INSERT_RACE,
2129 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2130 /*kprintf("chain %p get race\n", chain);*/
2131 hammer2_chain_drop(chain);
2134 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2138 * Return our new chain referenced but not locked, or NULL if
2145 * Lookup initialization/completion API
2148 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2150 hammer2_chain_ref(parent);
2151 if (flags & HAMMER2_LOOKUP_SHARED) {
2152 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2153 HAMMER2_RESOLVE_SHARED);
2155 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2161 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2164 hammer2_chain_unlock(parent);
2165 hammer2_chain_drop(parent);
2170 * Take the locked chain and return a locked parent. The chain remains
2171 * locked on return. Pass HAMMER2_RESOLVE_* flags in flags.
2173 * This will work even if the chain is errored, and the caller can check
2174 * parent->error on return if desired since the parent will be locked.
2176 * This function handles the lock order reversal.
2179 hammer2_chain_getparent(hammer2_chain_t *chain, int flags)
2181 hammer2_chain_t *parent;
2184 * Be careful of order, chain must be unlocked before parent
2185 * is locked below to avoid a deadlock.
2187 * Safe access to fu->parent requires fu's core spinlock.
2190 hammer2_spin_ex(&chain->core.spin);
2191 parent = chain->parent;
2192 if (parent == NULL) {
2193 hammer2_spin_unex(&chain->core.spin);
2194 panic("hammer2_chain_getparent: no parent");
2196 hammer2_chain_ref(parent);
2197 hammer2_spin_unex(&chain->core.spin);
2199 hammer2_chain_unlock(chain);
2200 hammer2_chain_lock(parent, flags);
2201 hammer2_chain_lock(chain, flags);
2204 * Parent relinking races are quite common. We have to get it right
2205 * or we will blow up the block table.
2207 if (chain->parent != parent) {
2208 hammer2_chain_unlock(parent);
2209 hammer2_chain_drop(parent);
2216 * Take the locked chain and return a locked parent. The chain is unlocked
2217 * and dropped. *chainp is set to the returned parent as a convenience.
2218 * Pass HAMMER2_RESOLVE_* flags in flags.
2220 * This will work even if the chain is errored, and the caller can check
2221 * parent->error on return if desired since the parent will be locked.
2223 * This function handles the lock order reversal.
2226 hammer2_chain_repparent(hammer2_chain_t **chainp, int flags)
2228 hammer2_chain_t *chain;
2229 hammer2_chain_t *parent;
2232 * Be careful of order, chain must be unlocked before parent
2233 * is locked below to avoid a deadlock.
2235 * Safe access to fu->parent requires fu's core spinlock.
2239 hammer2_spin_ex(&chain->core.spin);
2240 parent = chain->parent;
2241 if (parent == NULL) {
2242 hammer2_spin_unex(&chain->core.spin);
2243 panic("hammer2_chain_getparent: no parent");
2245 hammer2_chain_ref(parent);
2246 hammer2_spin_unex(&chain->core.spin);
2248 hammer2_chain_unlock(chain);
2249 hammer2_chain_lock(parent, flags);
2252 * Parent relinking races are quite common. We have to get it right
2253 * or we will blow up the block table.
2255 if (chain->parent != parent) {
2256 hammer2_chain_lock(chain, flags);
2257 hammer2_chain_unlock(parent);
2258 hammer2_chain_drop(parent);
2261 hammer2_chain_drop(chain);
2268 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2269 * (*parentp) typically points to an inode but can also point to a related
2270 * indirect block and this function will recurse upwards and find the inode
2271 * or the nearest undeleted indirect block covering the key range.
2273 * This function unconditionally sets *errorp, replacing any previous value.
2275 * (*parentp) must be exclusive or shared locked (depending on flags) and
2276 * referenced and can be an inode or an existing indirect block within the
2279 * If (*parent) is errored out, this function will not attempt to recurse
2280 * the radix tree and will return NULL along with an appropriate *errorp.
2281 * If NULL is returned and *errorp is 0, the requested lookup could not be
2284 * On return (*parentp) will be modified to point at the deepest parent chain
2285 * element encountered during the search, as a helper for an insertion or
2288 * The new (*parentp) will be locked shared or exclusive (depending on flags),
2289 * and referenced, and the old will be unlocked and dereferenced (no change
2290 * if they are both the same). This is particularly important if the caller
2291 * wishes to insert a new chain, (*parentp) will be set properly even if NULL
2292 * is returned, as long as no error occurred.
2294 * The matching chain will be returned locked according to flags. If NOLOCK
2295 * is requested the chain will be returned only referenced. Note that the
2296 * parent chain must always be locked shared or exclusive, matching the
2297 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2298 * when NOLOCK is specified but that complicates matters if *parentp must
2299 * inherit the chain.
2301 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2302 * data pointer or can otherwise be in flux.
2304 * NULL is returned if no match was found, but (*parentp) will still
2305 * potentially be adjusted.
2307 * On return (*key_nextp) will point to an iterative value for key_beg.
2308 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2310 * This function will also recurse up the chain if the key is not within the
2311 * current parent's range. (*parentp) can never be set to NULL. An iteration
2312 * can simply allow (*parentp) to float inside the loop.
2314 * NOTE! chain->data is not always resolved. By default it will not be
2315 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2316 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2317 * BREF_TYPE_DATA as the device buffer can alias the logical file
2322 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2323 hammer2_key_t key_beg, hammer2_key_t key_end,
2324 int *errorp, int flags)
2327 hammer2_chain_t *parent;
2328 hammer2_chain_t *chain;
2329 hammer2_blockref_t *base;
2330 hammer2_blockref_t *bref;
2331 hammer2_blockref_t bcopy;
2332 hammer2_key_t scan_beg;
2333 hammer2_key_t scan_end;
2335 int how_always = HAMMER2_RESOLVE_ALWAYS;
2336 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2339 int maxloops = 300000;
2340 volatile hammer2_mtx_t save_mtx;
2342 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2343 how_maybe = how_always;
2344 how = HAMMER2_RESOLVE_ALWAYS;
2345 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2346 how = HAMMER2_RESOLVE_NEVER;
2348 how = HAMMER2_RESOLVE_MAYBE;
2350 if (flags & HAMMER2_LOOKUP_SHARED) {
2351 how_maybe |= HAMMER2_RESOLVE_SHARED;
2352 how_always |= HAMMER2_RESOLVE_SHARED;
2353 how |= HAMMER2_RESOLVE_SHARED;
2357 * Recurse (*parentp) upward if necessary until the parent completely
2358 * encloses the key range or we hit the inode.
2360 * Handle races against the flusher deleting indirect nodes on its
2361 * way back up by continuing to recurse upward past the deletion.
2367 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2368 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2369 scan_beg = parent->bref.key;
2370 scan_end = scan_beg +
2371 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2372 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2373 if (key_beg >= scan_beg && key_end <= scan_end)
2376 parent = hammer2_chain_repparent(parentp, how_maybe);
2380 if (--maxloops == 0)
2381 panic("hammer2_chain_lookup: maxloops");
2383 * Locate the blockref array. Currently we do a fully associative
2384 * search through the array.
2386 switch(parent->bref.type) {
2387 case HAMMER2_BREF_TYPE_INODE:
2389 * Special shortcut for embedded data returns the inode
2390 * itself. Callers must detect this condition and access
2391 * the embedded data (the strategy code does this for us).
2393 * This is only applicable to regular files and softlinks.
2395 * We need a second lock on parent. Since we already have
2396 * a lock we must pass LOCKAGAIN to prevent unexpected
2397 * blocking (we don't want to block on a second shared
2398 * ref if an exclusive lock is pending)
2400 if (parent->data->ipdata.meta.op_flags &
2401 HAMMER2_OPFLAG_DIRECTDATA) {
2402 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2404 *key_nextp = key_end + 1;
2407 hammer2_chain_ref(parent);
2408 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2409 hammer2_chain_lock(parent,
2411 HAMMER2_RESOLVE_LOCKAGAIN);
2412 *key_nextp = key_end + 1;
2415 base = &parent->data->ipdata.u.blockset.blockref[0];
2416 count = HAMMER2_SET_COUNT;
2418 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2419 case HAMMER2_BREF_TYPE_INDIRECT:
2421 * Handle MATCHIND on the parent
2423 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2424 scan_beg = parent->bref.key;
2425 scan_end = scan_beg +
2426 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2427 if (key_beg == scan_beg && key_end == scan_end) {
2429 hammer2_chain_ref(chain);
2430 hammer2_chain_lock(chain, how_maybe);
2431 *key_nextp = scan_end + 1;
2437 * Optimize indirect blocks in the INITIAL state to avoid
2440 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2443 if (parent->data == NULL) {
2444 kprintf("parent->data is NULL %p\n", parent);
2446 tsleep(parent, 0, "xxx", 0);
2448 base = &parent->data->npdata[0];
2450 count = parent->bytes / sizeof(hammer2_blockref_t);
2452 case HAMMER2_BREF_TYPE_VOLUME:
2453 base = &parent->data->voldata.sroot_blockset.blockref[0];
2454 count = HAMMER2_SET_COUNT;
2456 case HAMMER2_BREF_TYPE_FREEMAP:
2457 base = &parent->data->blkset.blockref[0];
2458 count = HAMMER2_SET_COUNT;
2461 kprintf("hammer2_chain_lookup: unrecognized "
2462 "blockref(B) type: %d",
2465 tsleep(&base, 0, "dead", 0);
2466 panic("hammer2_chain_lookup: unrecognized "
2467 "blockref(B) type: %d",
2469 base = NULL; /* safety */
2470 count = 0; /* safety */
2474 * No lookup is possible if the parent is errored. We delayed
2475 * this check as long as we could to ensure that the parent backup,
2476 * embedded data, and MATCHIND code could still execute.
2478 if (parent->error) {
2479 *errorp = parent->error;
2484 * Merged scan to find next candidate.
2486 * hammer2_base_*() functions require the parent->core.live_* fields
2487 * to be synchronized.
2489 * We need to hold the spinlock to access the block array and RB tree
2490 * and to interlock chain creation.
2492 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2493 hammer2_chain_countbrefs(parent, base, count);
2498 hammer2_spin_ex(&parent->core.spin);
2499 chain = hammer2_combined_find(parent, base, count,
2503 generation = parent->core.generation;
2506 * Exhausted parent chain, iterate.
2509 KKASSERT(chain == NULL);
2510 hammer2_spin_unex(&parent->core.spin);
2511 if (key_beg == key_end) /* short cut single-key case */
2515 * Stop if we reached the end of the iteration.
2517 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2518 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2523 * Calculate next key, stop if we reached the end of the
2524 * iteration, otherwise go up one level and loop.
2526 key_beg = parent->bref.key +
2527 ((hammer2_key_t)1 << parent->bref.keybits);
2528 if (key_beg == 0 || key_beg > key_end)
2530 parent = hammer2_chain_repparent(parentp, how_maybe);
2535 * Selected from blockref or in-memory chain.
2537 if (chain == NULL) {
2539 hammer2_spin_unex(&parent->core.spin);
2540 chain = hammer2_chain_get(parent, generation,
2542 if (chain == NULL) {
2544 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2545 parent, key_beg, key_end);
2549 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2550 hammer2_chain_drop(chain);
2551 chain = NULL; /* SAFETY */
2555 hammer2_chain_ref(chain);
2556 hammer2_spin_unex(&parent->core.spin);
2560 * chain is referenced but not locked. We must lock the chain
2561 * to obtain definitive state.
2563 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2564 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2565 hammer2_chain_lock(chain, how_maybe);
2567 hammer2_chain_lock(chain, how);
2569 KKASSERT(chain->parent == parent);
2572 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2574 * NOTE: Chain's key range is not relevant as there might be
2575 * one-offs within the range that are not deleted.
2577 * NOTE: Lookups can race delete-duplicate because
2578 * delete-duplicate does not lock the parent's core
2579 * (they just use the spinlock on the core).
2581 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2582 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2583 chain->bref.data_off, chain->bref.type,
2585 hammer2_chain_unlock(chain);
2586 hammer2_chain_drop(chain);
2587 chain = NULL; /* SAFETY */
2588 key_beg = *key_nextp;
2589 if (key_beg == 0 || key_beg > key_end)
2595 * If the chain element is an indirect block it becomes the new
2596 * parent and we loop on it. We must maintain our top-down locks
2597 * to prevent the flusher from interfering (i.e. doing a
2598 * delete-duplicate and leaving us recursing down a deleted chain).
2600 * The parent always has to be locked with at least RESOLVE_MAYBE
2601 * so we can access its data. It might need a fixup if the caller
2602 * passed incompatible flags. Be careful not to cause a deadlock
2603 * as a data-load requires an exclusive lock.
2605 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2606 * range is within the requested key range we return the indirect
2607 * block and do NOT loop. This is usually only used to acquire
2610 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2611 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2612 save_mtx = parent->lock;
2613 hammer2_chain_unlock(parent);
2614 hammer2_chain_drop(parent);
2615 *parentp = parent = chain;
2616 chain = NULL; /* SAFETY */
2621 * All done, return the chain.
2623 * If the caller does not want a locked chain, replace the lock with
2624 * a ref. Perhaps this can eventually be optimized to not obtain the
2625 * lock in the first place for situations where the data does not
2626 * need to be resolved.
2628 * NOTE! A chain->error must be tested by the caller upon return.
2629 * *errorp is only set based on issues which occur while
2630 * trying to reach the chain.
2633 if (flags & HAMMER2_LOOKUP_NOLOCK)
2634 hammer2_chain_unlock(chain);
2640 * After having issued a lookup we can iterate all matching keys.
2642 * If chain is non-NULL we continue the iteration from just after it's index.
2644 * If chain is NULL we assume the parent was exhausted and continue the
2645 * iteration at the next parent.
2647 * If a fatal error occurs (typically an I/O error), a dummy chain is
2648 * returned with chain->error and error-identifying information set. This
2649 * chain will assert if you try to do anything fancy with it.
2651 * XXX Depending on where the error occurs we should allow continued iteration.
2653 * parent must be locked on entry and remains locked throughout. chain's
2654 * lock status must match flags. Chain is always at least referenced.
2656 * WARNING! The MATCHIND flag does not apply to this function.
2659 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2660 hammer2_key_t *key_nextp,
2661 hammer2_key_t key_beg, hammer2_key_t key_end,
2662 int *errorp, int flags)
2664 hammer2_chain_t *parent;
2668 * Calculate locking flags for upward recursion.
2670 how_maybe = HAMMER2_RESOLVE_MAYBE;
2671 if (flags & HAMMER2_LOOKUP_SHARED)
2672 how_maybe |= HAMMER2_RESOLVE_SHARED;
2678 * Calculate the next index and recalculate the parent if necessary.
2681 key_beg = chain->bref.key +
2682 ((hammer2_key_t)1 << chain->bref.keybits);
2683 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2684 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2685 hammer2_chain_unlock(chain);
2687 hammer2_chain_drop(chain);
2690 * chain invalid past this point, but we can still do a
2691 * pointer comparison w/parent.
2693 * Any scan where the lookup returned degenerate data embedded
2694 * in the inode has an invalid index and must terminate.
2696 if (chain == parent)
2698 if (key_beg == 0 || key_beg > key_end)
2701 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2702 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2704 * We reached the end of the iteration.
2709 * Continue iteration with next parent unless the current
2710 * parent covers the range.
2712 * (This also handles the case of a deleted, empty indirect
2715 key_beg = parent->bref.key +
2716 ((hammer2_key_t)1 << parent->bref.keybits);
2717 if (key_beg == 0 || key_beg > key_end)
2719 parent = hammer2_chain_repparent(parentp, how_maybe);
2725 return (hammer2_chain_lookup(parentp, key_nextp,
2731 * Caller wishes to iterate chains under parent, loading new chains into
2732 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
2733 * then call hammer2_chain_scan() repeatedly until a non-zero return.
2734 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
2735 * with the returned chain for the scan. The returned *chainp will be
2736 * locked and referenced. Any prior contents will be unlocked and dropped.
2738 * Caller should check the return value. A normal scan EOF will return
2739 * exactly HAMMER2_ERROR_EOF. Any other non-zero value indicates an
2740 * error trying to access parent data. Any error in the returned chain
2741 * must be tested separately by the caller.
2743 * (*chainp) is dropped on each scan, but will only be set if the returned
2744 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
2745 * returned via *chainp. The caller will get their bref only.
2747 * The raw scan function is similar to lookup/next but does not seek to a key.
2748 * Blockrefs are iterated via first_bref = (parent, NULL) and
2749 * next_chain = (parent, bref).
2751 * The passed-in parent must be locked and its data resolved. The function
2752 * nominally returns a locked and referenced *chainp != NULL for chains
2753 * the caller might need to recurse on (and will dipose of any *chainp passed
2754 * in). The caller must check the chain->bref.type either way.
2757 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2758 hammer2_blockref_t *bref, int *firstp,
2762 hammer2_blockref_t *base;
2763 hammer2_blockref_t *bref_ptr;
2765 hammer2_key_t next_key;
2766 hammer2_chain_t *chain = NULL;
2768 int how_always = HAMMER2_RESOLVE_ALWAYS;
2769 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2772 int maxloops = 300000;
2779 * Scan flags borrowed from lookup.
2781 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2782 how_maybe = how_always;
2783 how = HAMMER2_RESOLVE_ALWAYS;
2784 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2785 how = HAMMER2_RESOLVE_NEVER;
2787 how = HAMMER2_RESOLVE_MAYBE;
2789 if (flags & HAMMER2_LOOKUP_SHARED) {
2790 how_maybe |= HAMMER2_RESOLVE_SHARED;
2791 how_always |= HAMMER2_RESOLVE_SHARED;
2792 how |= HAMMER2_RESOLVE_SHARED;
2796 * Calculate key to locate first/next element, unlocking the previous
2797 * element as we go. Be careful, the key calculation can overflow.
2799 * (also reset bref to NULL)
2805 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2806 if ((chain = *chainp) != NULL) {
2808 hammer2_chain_unlock(chain);
2809 hammer2_chain_drop(chain);
2813 error |= HAMMER2_ERROR_EOF;
2819 if (parent->error) {
2820 error = parent->error;
2823 if (--maxloops == 0)
2824 panic("hammer2_chain_scan: maxloops");
2827 * Locate the blockref array. Currently we do a fully associative
2828 * search through the array.
2830 switch(parent->bref.type) {
2831 case HAMMER2_BREF_TYPE_INODE:
2833 * An inode with embedded data has no sub-chains.
2835 * WARNING! Bulk scan code may pass a static chain marked
2836 * as BREF_TYPE_INODE with a copy of the volume
2837 * root blockset to snapshot the volume.
2839 if (parent->data->ipdata.meta.op_flags &
2840 HAMMER2_OPFLAG_DIRECTDATA) {
2841 error |= HAMMER2_ERROR_EOF;
2844 base = &parent->data->ipdata.u.blockset.blockref[0];
2845 count = HAMMER2_SET_COUNT;
2847 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2848 case HAMMER2_BREF_TYPE_INDIRECT:
2850 * Optimize indirect blocks in the INITIAL state to avoid
2853 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2856 if (parent->data == NULL)
2857 panic("parent->data is NULL");
2858 base = &parent->data->npdata[0];
2860 count = parent->bytes / sizeof(hammer2_blockref_t);
2862 case HAMMER2_BREF_TYPE_VOLUME:
2863 base = &parent->data->voldata.sroot_blockset.blockref[0];
2864 count = HAMMER2_SET_COUNT;
2866 case HAMMER2_BREF_TYPE_FREEMAP:
2867 base = &parent->data->blkset.blockref[0];
2868 count = HAMMER2_SET_COUNT;
2871 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2873 base = NULL; /* safety */
2874 count = 0; /* safety */
2878 * Merged scan to find next candidate.
2880 * hammer2_base_*() functions require the parent->core.live_* fields
2881 * to be synchronized.
2883 * We need to hold the spinlock to access the block array and RB tree
2884 * and to interlock chain creation.
2886 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2887 hammer2_chain_countbrefs(parent, base, count);
2891 hammer2_spin_ex(&parent->core.spin);
2892 chain = hammer2_combined_find(parent, base, count,
2894 key, HAMMER2_KEY_MAX,
2896 generation = parent->core.generation;
2899 * Exhausted parent chain, we're done.
2901 if (bref_ptr == NULL) {
2902 hammer2_spin_unex(&parent->core.spin);
2903 KKASSERT(chain == NULL);
2904 error |= HAMMER2_ERROR_EOF;
2909 * Copy into the supplied stack-based blockref.
2914 * Selected from blockref or in-memory chain.
2916 if (chain == NULL) {
2917 switch(bref->type) {
2918 case HAMMER2_BREF_TYPE_INODE:
2919 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2920 case HAMMER2_BREF_TYPE_INDIRECT:
2921 case HAMMER2_BREF_TYPE_VOLUME:
2922 case HAMMER2_BREF_TYPE_FREEMAP:
2924 * Recursion, always get the chain
2926 hammer2_spin_unex(&parent->core.spin);
2927 chain = hammer2_chain_get(parent, generation, bref);
2928 if (chain == NULL) {
2929 kprintf("retry scan parent %p keys %016jx\n",
2933 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2934 hammer2_chain_drop(chain);
2941 * No recursion, do not waste time instantiating
2942 * a chain, just iterate using the bref.
2944 hammer2_spin_unex(&parent->core.spin);
2949 * Recursion or not we need the chain in order to supply
2952 hammer2_chain_ref(chain);
2953 hammer2_spin_unex(&parent->core.spin);
2957 * chain is referenced but not locked. We must lock the chain
2958 * to obtain definitive state.
2961 hammer2_chain_lock(chain, how);
2964 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2966 * NOTE: chain's key range is not relevant as there might be
2967 * one-offs within the range that are not deleted.
2969 * NOTE: XXX this could create problems with scans used in
2970 * situations other than mount-time recovery.
2972 * NOTE: Lookups can race delete-duplicate because
2973 * delete-duplicate does not lock the parent's core
2974 * (they just use the spinlock on the core).
2976 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2977 hammer2_chain_unlock(chain);
2978 hammer2_chain_drop(chain);
2983 error |= HAMMER2_ERROR_EOF;
2991 * All done, return the bref or NULL, supply chain if necessary.
2999 * Create and return a new hammer2 system memory structure of the specified
3000 * key, type and size and insert it under (*parentp). This is a full
3001 * insertion, based on the supplied key/keybits, and may involve creating
3002 * indirect blocks and moving other chains around via delete/duplicate.
3004 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3005 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3006 * FULL. This typically means that the caller is creating the chain after
3007 * doing a hammer2_chain_lookup().
3009 * (*parentp) must be exclusive locked and may be replaced on return
3010 * depending on how much work the function had to do.
3012 * (*parentp) must not be errored or this function will assert.
3014 * (*chainp) usually starts out NULL and returns the newly created chain,
3015 * but if the caller desires the caller may allocate a disconnected chain
3016 * and pass it in instead.
3018 * This function should NOT be used to insert INDIRECT blocks. It is
3019 * typically used to create/insert inodes and data blocks.
3021 * Caller must pass-in an exclusively locked parent the new chain is to
3022 * be inserted under, and optionally pass-in a disconnected, exclusively
3023 * locked chain to insert (else we create a new chain). The function will
3024 * adjust (*parentp) as necessary, create or connect the chain, and
3025 * return an exclusively locked chain in *chainp.
3027 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3028 * and will be reassigned.
3030 * NOTE: returns HAMMER_ERROR_* flags
3033 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3034 hammer2_pfs_t *pmp, int methods,
3035 hammer2_key_t key, int keybits, int type, size_t bytes,
3036 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3039 hammer2_chain_t *chain;
3040 hammer2_chain_t *parent;
3041 hammer2_blockref_t *base;
3042 hammer2_blockref_t dummy;
3046 int maxloops = 300000;
3049 * Topology may be crossing a PFS boundary.
3052 KKASSERT(hammer2_mtx_owned(&parent->lock));
3053 KKASSERT(parent->error == 0);
3057 if (chain == NULL) {
3059 * First allocate media space and construct the dummy bref,
3060 * then allocate the in-memory chain structure. Set the
3061 * INITIAL flag for fresh chains which do not have embedded
3064 * XXX for now set the check mode of the child based on
3065 * the parent or, if the parent is an inode, the
3066 * specification in the inode.
3068 bzero(&dummy, sizeof(dummy));
3071 dummy.keybits = keybits;
3072 dummy.data_off = hammer2_getradix(bytes);
3075 * Inherit methods from parent by default. Primarily used
3076 * for BREF_TYPE_DATA. Non-data types *must* be set to
3077 * a non-NONE check algorithm.
3080 dummy.methods = parent->bref.methods;
3082 dummy.methods = (uint8_t)methods;
3084 if (type != HAMMER2_BREF_TYPE_DATA &&
3085 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3087 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3090 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3093 * Lock the chain manually, chain_lock will load the chain
3094 * which we do NOT want to do. (note: chain->refs is set
3095 * to 1 by chain_alloc() for us, but lockcnt is not).
3098 hammer2_mtx_ex(&chain->lock);
3100 ++curthread->td_tracker;
3103 * Set INITIAL to optimize I/O. The flag will generally be
3104 * processed when we call hammer2_chain_modify().
3106 * Recalculate bytes to reflect the actual media block
3107 * allocation. Handle special case radix 0 == 0 bytes.
3109 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3111 bytes = (hammer2_off_t)1 << bytes;
3112 chain->bytes = bytes;
3115 case HAMMER2_BREF_TYPE_VOLUME:
3116 case HAMMER2_BREF_TYPE_FREEMAP:
3117 panic("hammer2_chain_create: called with volume type");
3119 case HAMMER2_BREF_TYPE_INDIRECT:
3120 panic("hammer2_chain_create: cannot be used to"
3121 "create indirect block");
3123 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3124 panic("hammer2_chain_create: cannot be used to"
3125 "create freemap root or node");
3127 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3128 KKASSERT(bytes == sizeof(chain->data->bmdata));
3130 case HAMMER2_BREF_TYPE_DIRENT:
3131 case HAMMER2_BREF_TYPE_INODE:
3132 case HAMMER2_BREF_TYPE_DATA:
3135 * leave chain->data NULL, set INITIAL
3137 KKASSERT(chain->data == NULL);
3138 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3143 * We are reattaching a previously deleted chain, possibly
3144 * under a new parent and possibly with a new key/keybits.
3145 * The chain does not have to be in a modified state. The
3146 * UPDATE flag will be set later on in this routine.
3148 * Do NOT mess with the current state of the INITIAL flag.
3150 chain->bref.key = key;
3151 chain->bref.keybits = keybits;
3152 if (chain->flags & HAMMER2_CHAIN_DELETED)
3153 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3154 KKASSERT(chain->parent == NULL);
3156 if (flags & HAMMER2_INSERT_PFSROOT)
3157 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3159 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3162 * Calculate how many entries we have in the blockref array and
3163 * determine if an indirect block is required.
3166 if (--maxloops == 0)
3167 panic("hammer2_chain_create: maxloops");
3169 switch(parent->bref.type) {
3170 case HAMMER2_BREF_TYPE_INODE:
3171 if ((parent->data->ipdata.meta.op_flags &
3172 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3173 kprintf("hammer2: parent set for direct-data! "
3174 "pkey=%016jx ckey=%016jx\n",
3178 KKASSERT((parent->data->ipdata.meta.op_flags &
3179 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3180 KKASSERT(parent->data != NULL);
3181 base = &parent->data->ipdata.u.blockset.blockref[0];
3182 count = HAMMER2_SET_COUNT;
3184 case HAMMER2_BREF_TYPE_INDIRECT:
3185 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3186 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3189 base = &parent->data->npdata[0];
3190 count = parent->bytes / sizeof(hammer2_blockref_t);
3192 case HAMMER2_BREF_TYPE_VOLUME:
3193 KKASSERT(parent->data != NULL);
3194 base = &parent->data->voldata.sroot_blockset.blockref[0];
3195 count = HAMMER2_SET_COUNT;
3197 case HAMMER2_BREF_TYPE_FREEMAP:
3198 KKASSERT(parent->data != NULL);
3199 base = &parent->data->blkset.blockref[0];
3200 count = HAMMER2_SET_COUNT;
3203 panic("hammer2_chain_create: unrecognized blockref type: %d",
3211 * Make sure we've counted the brefs
3213 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3214 hammer2_chain_countbrefs(parent, base, count);
3216 KASSERT(parent->core.live_count >= 0 &&
3217 parent->core.live_count <= count,
3218 ("bad live_count %d/%d (%02x, %d)",
3219 parent->core.live_count, count,
3220 parent->bref.type, parent->bytes));
3223 * If no free blockref could be found we must create an indirect
3224 * block and move a number of blockrefs into it. With the parent
3225 * locked we can safely lock each child in order to delete+duplicate
3226 * it without causing a deadlock.
3228 * This may return the new indirect block or the old parent depending
3229 * on where the key falls. NULL is returned on error.
3231 if (parent->core.live_count == count) {
3232 hammer2_chain_t *nparent;
3234 KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3236 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3237 mtid, type, &error);
3238 if (nparent == NULL) {
3240 hammer2_chain_drop(chain);
3244 if (parent != nparent) {
3245 hammer2_chain_unlock(parent);
3246 hammer2_chain_drop(parent);
3247 parent = *parentp = nparent;
3252 if (chain->flags & HAMMER2_CHAIN_DELETED)
3253 kprintf("Inserting deleted chain @%016jx\n",
3257 * Link the chain into its parent.
3259 if (chain->parent != NULL)
3260 panic("hammer2: hammer2_chain_create: chain already connected");
3261 KKASSERT(chain->parent == NULL);
3262 KKASSERT(parent->core.live_count < count);
3263 hammer2_chain_insert(parent, chain,
3264 HAMMER2_CHAIN_INSERT_SPIN |
3265 HAMMER2_CHAIN_INSERT_LIVE,
3270 * Mark the newly created chain modified. This will cause
3271 * UPDATE to be set and process the INITIAL flag.
3273 * Device buffers are not instantiated for DATA elements
3274 * as these are handled by logical buffers.
3276 * Indirect and freemap node indirect blocks are handled
3277 * by hammer2_chain_create_indirect() and not by this
3280 * Data for all other bref types is expected to be
3281 * instantiated (INODE, LEAF).
3283 switch(chain->bref.type) {
3284 case HAMMER2_BREF_TYPE_DATA:
3285 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3286 case HAMMER2_BREF_TYPE_DIRENT:
3287 case HAMMER2_BREF_TYPE_INODE:
3288 error = hammer2_chain_modify(chain, mtid, dedup_off,
3289 HAMMER2_MODIFY_OPTDATA);
3293 * Remaining types are not supported by this function.
3294 * In particular, INDIRECT and LEAF_NODE types are
3295 * handled by create_indirect().
3297 panic("hammer2_chain_create: bad type: %d",
3304 * When reconnecting a chain we must set UPDATE and
3305 * setflush so the flush recognizes that it must update
3306 * the bref in the parent.
3308 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3309 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3313 * We must setflush(parent) to ensure that it recurses through to
3314 * chain. setflush(chain) might not work because ONFLUSH is possibly
3315 * already set in the chain (so it won't recurse up to set it in the
3318 hammer2_chain_setflush(parent);
3327 * Move the chain from its old parent to a new parent. The chain must have
3328 * already been deleted or already disconnected (or never associated) with
3329 * a parent. The chain is reassociated with the new parent and the deleted
3330 * flag will be cleared (no longer deleted). The chain's modification state
3333 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3334 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3335 * FULL. This typically means that the caller is creating the chain after
3336 * doing a hammer2_chain_lookup().
3338 * A non-NULL bref is typically passed when key and keybits must be overridden.
3339 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3340 * from a passed-in bref and uses the old chain's bref for everything else.
3342 * Neither (parent) or (chain) can be errored.
3344 * If (parent) is non-NULL then the chain is inserted under the parent.
3346 * If (parent) is NULL then the newly duplicated chain is not inserted
3347 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3348 * passing into hammer2_chain_create() after this function returns).
3350 * WARNING! This function calls create which means it can insert indirect
3351 * blocks. This can cause other unrelated chains in the parent to
3352 * be moved to a newly inserted indirect block in addition to the
3356 hammer2_chain_rename(hammer2_blockref_t *bref,
3357 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3358 hammer2_tid_t mtid, int flags)
3361 hammer2_chain_t *parent;
3365 * WARNING! We should never resolve DATA to device buffers
3366 * (XXX allow it if the caller did?), and since
3367 * we currently do not have the logical buffer cache
3368 * buffer in-hand to fix its cached physical offset
3369 * we also force the modify code to not COW it. XXX
3372 KKASSERT(chain->parent == NULL);
3373 KKASSERT(chain->error == 0);
3376 * Now create a duplicate of the chain structure, associating
3377 * it with the same core, making it the same size, pointing it
3378 * to the same bref (the same media block).
3380 * NOTE: Handle special radix == 0 case (means 0 bytes).
3383 bref = &chain->bref;
3384 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3386 bytes = (hammer2_off_t)1 << bytes;
3389 * If parent is not NULL the duplicated chain will be entered under
3390 * the parent and the UPDATE bit set to tell flush to update
3393 * We must setflush(parent) to ensure that it recurses through to
3394 * chain. setflush(chain) might not work because ONFLUSH is possibly
3395 * already set in the chain (so it won't recurse up to set it in the
3398 * Having both chains locked is extremely important for atomicy.
3400 if (parentp && (parent = *parentp) != NULL) {
3401 KKASSERT(hammer2_mtx_owned(&parent->lock));
3402 KKASSERT(parent->refs > 0);
3403 KKASSERT(parent->error == 0);
3405 hammer2_chain_create(parentp, &chain,
3406 chain->pmp, HAMMER2_METH_DEFAULT,
3407 bref->key, bref->keybits, bref->type,
3408 chain->bytes, mtid, 0, flags);
3409 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3410 hammer2_chain_setflush(*parentp);
3415 * Helper function for deleting chains.
3417 * The chain is removed from the live view (the RBTREE) as well as the parent's
3418 * blockmap. Both chain and its parent must be locked.
3420 * parent may not be errored. chain can be errored.
3423 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3424 hammer2_tid_t mtid, int flags)
3429 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3430 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3431 KKASSERT(chain->parent == parent);
3434 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3436 * Chain is blockmapped, so there must be a parent.
3437 * Atomically remove the chain from the parent and remove
3438 * the blockmap entry. The parent must be set modified
3439 * to remove the blockmap entry.
3441 hammer2_blockref_t *base;
3444 KKASSERT(parent != NULL);
3445 KKASSERT(parent->error == 0);
3446 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3447 error = hammer2_chain_modify(parent, mtid, 0, 0);
3452 * Calculate blockmap pointer
3454 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3455 hammer2_spin_ex(&chain->core.spin);
3456 hammer2_spin_ex(&parent->core.spin);
3458 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3459 atomic_add_int(&parent->core.live_count, -1);
3460 ++parent->core.generation;
3461 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3462 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3463 --parent->core.chain_count;
3464 chain->parent = NULL;
3466 switch(parent->bref.type) {
3467 case HAMMER2_BREF_TYPE_INODE:
3469 * Access the inode's block array. However, there
3470 * is no block array if the inode is flagged
3474 (parent->data->ipdata.meta.op_flags &
3475 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3477 &parent->data->ipdata.u.blockset.blockref[0];
3481 count = HAMMER2_SET_COUNT;
3483 case HAMMER2_BREF_TYPE_INDIRECT:
3484 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3486 base = &parent->data->npdata[0];
3489 count = parent->bytes / sizeof(hammer2_blockref_t);
3491 case HAMMER2_BREF_TYPE_VOLUME:
3492 base = &parent->data->voldata.
3493 sroot_blockset.blockref[0];
3494 count = HAMMER2_SET_COUNT;
3496 case HAMMER2_BREF_TYPE_FREEMAP:
3497 base = &parent->data->blkset.blockref[0];
3498 count = HAMMER2_SET_COUNT;
3503 panic("hammer2_flush_pass2: "
3504 "unrecognized blockref type: %d",
3509 * delete blockmapped chain from its parent.
3511 * The parent is not affected by any statistics in chain
3512 * which are pending synchronization. That is, there is
3513 * nothing to undo in the parent since they have not yet
3514 * been incorporated into the parent.
3516 * The parent is affected by statistics stored in inodes.
3517 * Those have already been synchronized, so they must be
3518 * undone. XXX split update possible w/delete in middle?
3521 hammer2_base_delete(parent, base, count, chain);
3523 hammer2_spin_unex(&parent->core.spin);
3524 hammer2_spin_unex(&chain->core.spin);
3525 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3527 * Chain is not blockmapped but a parent is present.
3528 * Atomically remove the chain from the parent. There is
3529 * no blockmap entry to remove.
3531 * Because chain was associated with a parent but not
3532 * synchronized, the chain's *_count_up fields contain
3533 * inode adjustment statistics which must be undone.
3535 hammer2_spin_ex(&chain->core.spin);
3536 hammer2_spin_ex(&parent->core.spin);
3537 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3538 atomic_add_int(&parent->core.live_count, -1);
3539 ++parent->core.generation;
3540 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3541 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3542 --parent->core.chain_count;
3543 chain->parent = NULL;
3544 hammer2_spin_unex(&parent->core.spin);
3545 hammer2_spin_unex(&chain->core.spin);
3548 * Chain is not blockmapped and has no parent. This
3549 * is a degenerate case.
3551 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3558 * Create an indirect block that covers one or more of the elements in the
3559 * current parent. Either returns the existing parent with no locking or
3560 * ref changes or returns the new indirect block locked and referenced
3561 * and leaving the original parent lock/ref intact as well.
3563 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3565 * The returned chain depends on where the specified key falls.
3567 * The key/keybits for the indirect mode only needs to follow three rules:
3569 * (1) That all elements underneath it fit within its key space and
3571 * (2) That all elements outside it are outside its key space.
3573 * (3) When creating the new indirect block any elements in the current
3574 * parent that fit within the new indirect block's keyspace must be
3575 * moved into the new indirect block.
3577 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3578 * keyspace the the current parent, but lookup/iteration rules will
3579 * ensure (and must ensure) that rule (2) for all parents leading up
3580 * to the nearest inode or the root volume header is adhered to. This
3581 * is accomplished by always recursing through matching keyspaces in
3582 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3584 * The current implementation calculates the current worst-case keyspace by
3585 * iterating the current parent and then divides it into two halves, choosing
3586 * whichever half has the most elements (not necessarily the half containing
3587 * the requested key).
3589 * We can also opt to use the half with the least number of elements. This
3590 * causes lower-numbered keys (aka logical file offsets) to recurse through
3591 * fewer indirect blocks and higher-numbered keys to recurse through more.
3592 * This also has the risk of not moving enough elements to the new indirect
3593 * block and being forced to create several indirect blocks before the element
3596 * Must be called with an exclusively locked parent.
3598 * NOTE: *errorp set to HAMMER_ERROR_* flags
3600 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3601 hammer2_key_t *keyp, int keybits,
3602 hammer2_blockref_t *base, int count);
3603 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3604 hammer2_key_t *keyp, int keybits,
3605 hammer2_blockref_t *base, int count,
3607 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3608 hammer2_key_t *keyp, int keybits,
3609 hammer2_blockref_t *base, int count,
3613 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3614 hammer2_key_t create_key, int create_bits,
3615 hammer2_tid_t mtid, int for_type, int *errorp)
3618 hammer2_blockref_t *base;
3619 hammer2_blockref_t *bref;
3620 hammer2_blockref_t bcopy;
3621 hammer2_chain_t *chain;
3622 hammer2_chain_t *ichain;
3623 hammer2_chain_t dummy;
3624 hammer2_key_t key = create_key;
3625 hammer2_key_t key_beg;
3626 hammer2_key_t key_end;
3627 hammer2_key_t key_next;
3628 int keybits = create_bits;
3636 int maxloops = 300000;
3639 * Calculate the base blockref pointer or NULL if the chain
3640 * is known to be empty. We need to calculate the array count
3641 * for RB lookups either way.
3644 KKASSERT(hammer2_mtx_owned(&parent->lock));
3647 * Pre-modify the parent now to avoid having to deal with error
3648 * processing if we tried to later (in the middle of our loop).
3650 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3652 kprintf("hammer2_create_indirect: error %08x %s\n",
3653 *errorp, hammer2_error_str(*errorp));
3657 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3658 base = hammer2_chain_base_and_count(parent, &count);
3661 * dummy used in later chain allocation (no longer used for lookups).
3663 bzero(&dummy, sizeof(dummy));
3666 * How big should our new indirect block be? It has to be at least
3667 * as large as its parent for splits to work properly.
3669 * The freemap uses a specific indirect block size. The number of
3670 * levels are built dynamically and ultimately depend on the size
3671 * volume. Because freemap blocks are taken from the reserved areas
3672 * of the volume our goal is efficiency (fewer levels) and not so
3673 * much to save disk space.
3675 * The first indirect block level for a directory usually uses
3676 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3677 * the hash mechanism, this typically gives us a nominal
3678 * 32 * 4 entries with one level of indirection.
3680 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3681 * indirect blocks. The initial 4 entries in the inode gives us
3682 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3683 * of indirection gives us 137GB, and so forth. H2 can support
3684 * huge file sizes but they are not typical, so we try to stick
3685 * with compactness and do not use a larger indirect block size.
3687 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3688 * due to the way indirect blocks are created this usually winds
3689 * up being extremely inefficient for small files. Even though
3690 * 16KB requires more levels of indirection for very large files,
3691 * the 16KB records can be ganged together into 64KB DIOs.
3693 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3694 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3695 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3696 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3697 if (parent->data->ipdata.meta.type ==
3698 HAMMER2_OBJTYPE_DIRECTORY)
3699 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3701 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3704 nbytes = HAMMER2_IND_BYTES_NOM;
3706 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3707 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3708 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3709 nbytes = count * sizeof(hammer2_blockref_t);
3711 ncount = nbytes / sizeof(hammer2_blockref_t);
3714 * When creating an indirect block for a freemap node or leaf
3715 * the key/keybits must be fitted to static radix levels because
3716 * particular radix levels use particular reserved blocks in the
3719 * This routine calculates the key/radix of the indirect block
3720 * we need to create, and whether it is on the high-side or the
3724 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3725 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3726 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3729 case HAMMER2_BREF_TYPE_DATA:
3730 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3731 base, count, ncount);
3733 case HAMMER2_BREF_TYPE_DIRENT:
3734 case HAMMER2_BREF_TYPE_INODE:
3735 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3736 base, count, ncount);
3739 panic("illegal indirect block for bref type %d", for_type);
3744 * Normalize the key for the radix being represented, keeping the
3745 * high bits and throwing away the low bits.
3747 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3750 * Ok, create our new indirect block
3752 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3753 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3754 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3756 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3758 dummy.bref.key = key;
3759 dummy.bref.keybits = keybits;
3760 dummy.bref.data_off = hammer2_getradix(nbytes);
3761 dummy.bref.methods =
3762 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3763 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3765 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3766 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3767 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3768 /* ichain has one ref at this point */
3771 * We have to mark it modified to allocate its block, but use
3772 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3773 * it won't be acted upon by the flush code.
3775 *errorp = hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3777 kprintf("hammer2_alloc_indirect: error %08x %s\n",
3778 *errorp, hammer2_error_str(*errorp));
3779 hammer2_chain_unlock(ichain);
3780 hammer2_chain_drop(ichain);
3785 * Iterate the original parent and move the matching brefs into
3786 * the new indirect block.
3788 * XXX handle flushes.
3791 key_end = HAMMER2_KEY_MAX;
3792 key_next = 0; /* avoid gcc warnings */
3793 hammer2_spin_ex(&parent->core.spin);
3799 * Parent may have been modified, relocating its block array.
3800 * Reload the base pointer.
3802 base = hammer2_chain_base_and_count(parent, &count);
3804 if (++loops > 100000) {
3805 hammer2_spin_unex(&parent->core.spin);
3806 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3807 reason, parent, base, count, key_next);
3811 * NOTE: spinlock stays intact, returned chain (if not NULL)
3812 * is not referenced or locked which means that we
3813 * cannot safely check its flagged / deletion status
3816 chain = hammer2_combined_find(parent, base, count,
3820 generation = parent->core.generation;
3823 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3826 * Skip keys that are not within the key/radix of the new
3827 * indirect block. They stay in the parent.
3829 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3830 (key ^ bref->key)) != 0) {
3831 goto next_key_spinlocked;
3835 * Load the new indirect block by acquiring the related
3836 * chains (potentially from media as it might not be
3837 * in-memory). Then move it to the new parent (ichain).
3839 * chain is referenced but not locked. We must lock the
3840 * chain to obtain definitive state.
3844 * Use chain already present in the RBTREE
3846 hammer2_chain_ref(chain);
3847 hammer2_spin_unex(&parent->core.spin);
3848 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3851 * Get chain for blockref element. _get returns NULL
3852 * on insertion race.
3855 hammer2_spin_unex(&parent->core.spin);
3856 chain = hammer2_chain_get(parent, generation, &bcopy);
3857 if (chain == NULL) {
3859 hammer2_spin_ex(&parent->core.spin);
3862 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3863 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3865 hammer2_chain_unlock(chain);
3866 hammer2_chain_drop(chain);
3867 hammer2_spin_ex(&parent->core.spin);
3873 * This is always live so if the chain has been deleted
3874 * we raced someone and we have to retry.
3876 * NOTE: Lookups can race delete-duplicate because
3877 * delete-duplicate does not lock the parent's core
3878 * (they just use the spinlock on the core).
3880 * (note reversed logic for this one)
3882 if (chain->parent != parent ||
3883 (chain->flags & HAMMER2_CHAIN_DELETED)) {
3884 hammer2_chain_unlock(chain);
3885 hammer2_chain_drop(chain);
3886 kprintf("hammer2_chain_create_indirect "
3887 "RETRY (%p,%p)->%p %08x\n",
3888 parent, chain->parent, chain, chain->flags);
3889 hammer2_spin_ex(&parent->core.spin);
3894 * Shift the chain to the indirect block.
3896 * WARNING! No reason for us to load chain data, pass NOSTATS
3897 * to prevent delete/insert from trying to access
3898 * inode stats (and thus asserting if there is no
3899 * chain->data loaded).
3901 * WARNING! The (parent, chain) deletion may modify the parent
3902 * and invalidate the base pointer.
3904 * WARNING! Parent must already be marked modified, so we
3905 * can assume that chain_delete always suceeds.
3907 error = hammer2_chain_delete(parent, chain, mtid, 0);
3908 KKASSERT(error == 0);
3909 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3910 hammer2_chain_unlock(chain);
3911 hammer2_chain_drop(chain);
3912 KKASSERT(parent->refs > 0);
3914 base = NULL; /* safety */
3915 hammer2_spin_ex(&parent->core.spin);
3916 next_key_spinlocked:
3917 if (--maxloops == 0)
3918 panic("hammer2_chain_create_indirect: maxloops");
3920 if (key_next == 0 || key_next > key_end)
3925 hammer2_spin_unex(&parent->core.spin);
3928 * Insert the new indirect block into the parent now that we've
3929 * cleared out some entries in the parent. We calculated a good
3930 * insertion index in the loop above (ichain->index).
3932 * We don't have to set UPDATE here because we mark ichain
3933 * modified down below (so the normal modified -> flush -> set-moved
3934 * sequence applies).
3936 * The insertion shouldn't race as this is a completely new block
3937 * and the parent is locked.
3939 base = NULL; /* safety, parent modify may change address */
3940 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3941 KKASSERT(parent->core.live_count < count);
3942 hammer2_chain_insert(parent, ichain,
3943 HAMMER2_CHAIN_INSERT_SPIN |
3944 HAMMER2_CHAIN_INSERT_LIVE,
3948 * Make sure flushes propogate after our manual insertion.
3950 hammer2_chain_setflush(ichain);
3951 hammer2_chain_setflush(parent);
3954 * Figure out what to return.
3956 if (~(((hammer2_key_t)1 << keybits) - 1) &
3957 (create_key ^ key)) {
3959 * Key being created is outside the key range,
3960 * return the original parent.
3962 hammer2_chain_unlock(ichain);
3963 hammer2_chain_drop(ichain);
3966 * Otherwise its in the range, return the new parent.
3967 * (leave both the new and old parent locked).
3976 * Do maintenance on an indirect chain. Both parent and chain are locked.
3978 * Returns non-zero if (chain) is deleted, either due to being empty or
3979 * because its children were safely moved into the parent.
3982 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
3983 hammer2_chain_t *chain)
3985 hammer2_blockref_t *chain_base;
3986 hammer2_blockref_t *base;
3987 hammer2_blockref_t *bref;
3988 hammer2_blockref_t bcopy;
3989 hammer2_key_t key_next;
3990 hammer2_key_t key_beg;
3991 hammer2_key_t key_end;
3992 hammer2_chain_t *sub;
3999 * Make sure we have an accurate live_count
4001 if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4002 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4003 base = &chain->data->npdata[0];
4004 count = chain->bytes / sizeof(hammer2_blockref_t);
4005 hammer2_chain_countbrefs(chain, base, count);
4009 * If the indirect block is empty we can delete it.
4010 * (ignore deletion error)
4012 if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4013 hammer2_chain_delete(parent, chain,
4014 chain->bref.modify_tid,
4015 HAMMER2_DELETE_PERMANENT);
4019 base = hammer2_chain_base_and_count(parent, &count);
4021 if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4022 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4023 hammer2_chain_countbrefs(parent, base, count);
4027 * Determine if we can collapse chain into parent, calculate
4028 * hysteresis for chain emptiness.
4030 if (parent->core.live_count + chain->core.live_count - 1 > count)
4032 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4033 if (chain->core.live_count > chain_count * 3 / 4)
4037 * Ok, theoretically we can collapse chain's contents into
4038 * parent. chain is locked, but any in-memory children of chain
4039 * are not. For this to work, we must be able to dispose of any
4040 * in-memory children of chain.
4042 * For now require that there are no in-memory children of chain.
4044 * WARNING! Both chain and parent must remain locked across this
4049 * Parent must be marked modified. Don't try to collapse it if we
4050 * can't mark it modified. Once modified, destroy chain to make room
4051 * and to get rid of what will be a conflicting key (this is included
4052 * in the calculation above). Finally, move the children of chain
4053 * into chain's parent.
4055 * This order creates an accounting problem for bref.embed.stats
4056 * because we destroy chain before we remove its children. Any
4057 * elements whos blockref is already synchronized will be counted
4058 * twice. To deal with the problem we clean out chain's stats prior
4061 error = hammer2_chain_modify(parent, 0, 0, 0);
4063 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4064 hammer2_error_str(error));
4067 error = hammer2_chain_modify(chain, chain->bref.modify_tid, 0, 0);
4069 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4070 hammer2_error_str(error));
4074 chain->bref.embed.stats.inode_count = 0;
4075 chain->bref.embed.stats.data_count = 0;
4076 error = hammer2_chain_delete(parent, chain,
4077 chain->bref.modify_tid,
4078 HAMMER2_DELETE_PERMANENT);
4079 KKASSERT(error == 0);
4082 * The combined_find call requires core.spin to be held. One would
4083 * think there wouldn't be any conflicts since we hold chain
4084 * exclusively locked, but the caching mechanism for 0-ref children
4085 * does not require a chain lock.
4087 hammer2_spin_ex(&chain->core.spin);
4091 key_end = HAMMER2_KEY_MAX;
4093 chain_base = &chain->data->npdata[0];
4094 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4095 sub = hammer2_combined_find(chain, chain_base, chain_count,
4099 generation = chain->core.generation;
4102 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4105 hammer2_chain_ref(sub);
4106 hammer2_spin_unex(&chain->core.spin);
4107 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4108 if (sub->parent != chain ||
4109 (sub->flags & HAMMER2_CHAIN_DELETED)) {
4110 hammer2_chain_unlock(sub);
4111 hammer2_chain_drop(sub);
4112 hammer2_spin_ex(&chain->core.spin);
4117 hammer2_spin_unex(&chain->core.spin);
4118 sub = hammer2_chain_get(chain, generation, &bcopy);
4120 hammer2_spin_ex(&chain->core.spin);
4123 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4124 if (bcmp(&bcopy, bref, sizeof(bcopy)) != 0) {
4125 hammer2_chain_unlock(sub);
4126 hammer2_chain_drop(sub);
4127 hammer2_spin_ex(&chain->core.spin);
4131 error = hammer2_chain_delete(chain, sub,
4132 sub->bref.modify_tid, 0);
4133 KKASSERT(error == 0);
4134 hammer2_chain_rename(NULL, &parent, sub,
4135 sub->bref.modify_tid,
4136 HAMMER2_INSERT_SAMEPARENT);
4137 hammer2_chain_unlock(sub);
4138 hammer2_chain_drop(sub);
4139 hammer2_spin_ex(&chain->core.spin);
4145 hammer2_spin_unex(&chain->core.spin);
4151 * Freemap indirect blocks
4153 * Calculate the keybits and highside/lowside of the freemap node the
4154 * caller is creating.
4156 * This routine will specify the next higher-level freemap key/radix
4157 * representing the lowest-ordered set. By doing so, eventually all
4158 * low-ordered sets will be moved one level down.
4160 * We have to be careful here because the freemap reserves a limited
4161 * number of blocks for a limited number of levels. So we can't just
4162 * push indiscriminately.
4165 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4166 int keybits, hammer2_blockref_t *base, int count)
4168 hammer2_chain_t *chain;
4169 hammer2_blockref_t *bref;
4171 hammer2_key_t key_beg;
4172 hammer2_key_t key_end;
4173 hammer2_key_t key_next;
4176 int maxloops = 300000;
4184 * Calculate the range of keys in the array being careful to skip
4185 * slots which are overridden with a deletion.
4188 key_end = HAMMER2_KEY_MAX;
4189 hammer2_spin_ex(&parent->core.spin);
4192 if (--maxloops == 0) {
4193 panic("indkey_freemap shit %p %p:%d\n",
4194 parent, base, count);
4196 chain = hammer2_combined_find(parent, base, count,
4208 * Skip deleted chains.
4210 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4211 if (key_next == 0 || key_next > key_end)
4218 * Use the full live (not deleted) element for the scan
4219 * iteration. HAMMER2 does not allow partial replacements.
4221 * XXX should be built into hammer2_combined_find().
4223 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4225 if (keybits > bref->keybits) {
4227 keybits = bref->keybits;
4228 } else if (keybits == bref->keybits && bref->key < key) {
4235 hammer2_spin_unex(&parent->core.spin);
4238 * Return the keybits for a higher-level FREEMAP_NODE covering
4242 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4243 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4245 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4246 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4248 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4249 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4251 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4252 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4254 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4255 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4257 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4258 panic("hammer2_chain_indkey_freemap: level too high");
4261 panic("hammer2_chain_indkey_freemap: bad radix");
4270 * File indirect blocks
4272 * Calculate the key/keybits for the indirect block to create by scanning
4273 * existing keys. The key being created is also passed in *keyp and can be
4274 * inside or outside the indirect block. Regardless, the indirect block
4275 * must hold at least two keys in order to guarantee sufficient space.
4277 * We use a modified version of the freemap's fixed radix tree, but taylored
4278 * for file data. Basically we configure an indirect block encompassing the
4282 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4283 int keybits, hammer2_blockref_t *base, int count,
4286 hammer2_chain_t *chain;
4287 hammer2_blockref_t *bref;
4289 hammer2_key_t key_beg;
4290 hammer2_key_t key_end;
4291 hammer2_key_t key_next;
4295 int maxloops = 300000;
4303 * Calculate the range of keys in the array being careful to skip
4304 * slots which are overridden with a deletion.
4306 * Locate the smallest key.
4309 key_end = HAMMER2_KEY_MAX;
4310 hammer2_spin_ex(&parent->core.spin);
4313 if (--maxloops == 0) {
4314 panic("indkey_freemap shit %p %p:%d\n",
4315 parent, base, count);
4317 chain = hammer2_combined_find(parent, base, count,
4329 * Skip deleted chains.
4331 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4332 if (key_next == 0 || key_next > key_end)
4339 * Use the full live (not deleted) element for the scan
4340 * iteration. HAMMER2 does not allow partial replacements.
4342 * XXX should be built into hammer2_combined_find().
4344 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4346 if (keybits > bref->keybits) {
4348 keybits = bref->keybits;
4349 } else if (keybits == bref->keybits && bref->key < key) {
4356 hammer2_spin_unex(&parent->core.spin);
4359 * Calculate the static keybits for a higher-level indirect block
4360 * that contains the key.
4365 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4366 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4368 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4369 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4371 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4372 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4375 panic("bad ncount %d\n", ncount);
4381 * The largest radix that can be returned for an indirect block is
4382 * 63 bits. (The largest practical indirect block radix is actually
4383 * 62 bits because the top-level inode or volume root contains four
4384 * entries, but allow 63 to be returned).
4389 return keybits + nradix;
4395 * Directory indirect blocks.
4397 * Covers both the inode index (directory of inodes), and directory contents
4398 * (filenames hardlinked to inodes).
4400 * Because directory keys are hashed we generally try to cut the space in
4401 * half. We accomodate the inode index (which tends to have linearly
4402 * increasing inode numbers) by ensuring that the keyspace is at least large
4403 * enough to fill up the indirect block being created.
4406 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4407 int keybits, hammer2_blockref_t *base, int count,
4410 hammer2_blockref_t *bref;
4411 hammer2_chain_t *chain;
4412 hammer2_key_t key_beg;
4413 hammer2_key_t key_end;
4414 hammer2_key_t key_next;
4419 int maxloops = 300000;
4422 * Shortcut if the parent is the inode. In this situation the
4423 * parent has 4+1 directory entries and we are creating an indirect
4424 * block capable of holding many more.
4426 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4435 * Calculate the range of keys in the array being careful to skip
4436 * slots which are overridden with a deletion.
4439 key_end = HAMMER2_KEY_MAX;
4440 hammer2_spin_ex(&parent->core.spin);
4443 if (--maxloops == 0) {
4444 panic("indkey_freemap shit %p %p:%d\n",
4445 parent, base, count);
4447 chain = hammer2_combined_find(parent, base, count,
4461 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4462 if (key_next == 0 || key_next > key_end)
4469 * Use the full live (not deleted) element for the scan
4470 * iteration. HAMMER2 does not allow partial replacements.
4472 * XXX should be built into hammer2_combined_find().
4474 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4477 * Expand our calculated key range (key, keybits) to fit
4478 * the scanned key. nkeybits represents the full range
4479 * that we will later cut in half (two halves @ nkeybits - 1).
4482 if (nkeybits < bref->keybits) {
4483 if (bref->keybits > 64) {
4484 kprintf("bad bref chain %p bref %p\n",
4488 nkeybits = bref->keybits;
4490 while (nkeybits < 64 &&
4491 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4492 (key ^ bref->key)) != 0) {
4497 * If the new key range is larger we have to determine
4498 * which side of the new key range the existing keys fall
4499 * under by checking the high bit, then collapsing the
4500 * locount into the hicount or vise-versa.
4502 if (keybits != nkeybits) {
4503 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4514 * The newly scanned key will be in the lower half or the
4515 * upper half of the (new) key range.
4517 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4526 hammer2_spin_unex(&parent->core.spin);
4527 bref = NULL; /* now invalid (safety) */
4530 * Adjust keybits to represent half of the full range calculated
4531 * above (radix 63 max) for our new indirect block.
4536 * Expand keybits to hold at least ncount elements. ncount will be
4537 * a power of 2. This is to try to completely fill leaf nodes (at
4538 * least for keys which are not hashes).
4540 * We aren't counting 'in' or 'out', we are counting 'high side'
4541 * and 'low side' based on the bit at (1LL << keybits). We want
4542 * everything to be inside in these cases so shift it all to
4543 * the low or high side depending on the new high bit.
4545 while (((hammer2_key_t)1 << keybits) < ncount) {
4547 if (key & ((hammer2_key_t)1 << keybits)) {
4556 if (hicount > locount)
4557 key |= (hammer2_key_t)1 << keybits;
4559 key &= ~(hammer2_key_t)1 << keybits;
4569 * Directory indirect blocks.
4571 * Covers both the inode index (directory of inodes), and directory contents
4572 * (filenames hardlinked to inodes).
4574 * Because directory keys are hashed we generally try to cut the space in
4575 * half. We accomodate the inode index (which tends to have linearly
4576 * increasing inode numbers) by ensuring that the keyspace is at least large
4577 * enough to fill up the indirect block being created.
4580 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4581 int keybits, hammer2_blockref_t *base, int count,
4584 hammer2_blockref_t *bref;
4585 hammer2_chain_t *chain;
4586 hammer2_key_t key_beg;
4587 hammer2_key_t key_end;
4588 hammer2_key_t key_next;
4593 int maxloops = 300000;
4596 * Shortcut if the parent is the inode. In this situation the
4597 * parent has 4+1 directory entries and we are creating an indirect
4598 * block capable of holding many more.
4600 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4609 * Calculate the range of keys in the array being careful to skip
4610 * slots which are overridden with a deletion.
4613 key_end = HAMMER2_KEY_MAX;
4614 hammer2_spin_ex(&parent->core.spin);
4617 if (--maxloops == 0) {
4618 panic("indkey_freemap shit %p %p:%d\n",
4619 parent, base, count);
4621 chain = hammer2_combined_find(parent, base, count,
4635 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4636 if (key_next == 0 || key_next > key_end)
4643 * Use the full live (not deleted) element for the scan
4644 * iteration. HAMMER2 does not allow partial replacements.
4646 * XXX should be built into hammer2_combined_find().
4648 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4651 * Expand our calculated key range (key, keybits) to fit
4652 * the scanned key. nkeybits represents the full range
4653 * that we will later cut in half (two halves @ nkeybits - 1).
4656 if (nkeybits < bref->keybits) {
4657 if (bref->keybits > 64) {
4658 kprintf("bad bref chain %p bref %p\n",
4662 nkeybits = bref->keybits;
4664 while (nkeybits < 64 &&
4665 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4666 (key ^ bref->key)) != 0) {
4671 * If the new key range is larger we have to determine
4672 * which side of the new key range the existing keys fall
4673 * under by checking the high bit, then collapsing the
4674 * locount into the hicount or vise-versa.
4676 if (keybits != nkeybits) {
4677 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4688 * The newly scanned key will be in the lower half or the
4689 * upper half of the (new) key range.
4691 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4700 hammer2_spin_unex(&parent->core.spin);
4701 bref = NULL; /* now invalid (safety) */
4704 * Adjust keybits to represent half of the full range calculated
4705 * above (radix 63 max) for our new indirect block.
4710 * Expand keybits to hold at least ncount elements. ncount will be
4711 * a power of 2. This is to try to completely fill leaf nodes (at
4712 * least for keys which are not hashes).
4714 * We aren't counting 'in' or 'out', we are counting 'high side'
4715 * and 'low side' based on the bit at (1LL << keybits). We want
4716 * everything to be inside in these cases so shift it all to
4717 * the low or high side depending on the new high bit.
4719 while (((hammer2_key_t)1 << keybits) < ncount) {
4721 if (key & ((hammer2_key_t)1 << keybits)) {
4730 if (hicount > locount)
4731 key |= (hammer2_key_t)1 << keybits;
4733 key &= ~(hammer2_key_t)1 << keybits;
4743 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4746 * Both parent and chain must be locked exclusively.
4748 * This function will modify the parent if the blockref requires removal
4749 * from the parent's block table.
4751 * This function is NOT recursive. Any entity already pushed into the
4752 * chain (such as an inode) may still need visibility into its contents,
4753 * as well as the ability to read and modify the contents. For example,
4754 * for an unlinked file which is still open.
4756 * Also note that the flusher is responsible for cleaning up empty
4760 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4761 hammer2_tid_t mtid, int flags)
4765 KKASSERT(hammer2_mtx_owned(&chain->lock));
4768 * Nothing to do if already marked.
4770 * We need the spinlock on the core whos RBTREE contains chain
4771 * to protect against races.
4773 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4774 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4775 chain->parent == parent);
4776 error = _hammer2_chain_delete_helper(parent, chain,
4781 * Permanent deletions mark the chain as destroyed.
4784 if (flags & HAMMER2_DELETE_PERMANENT)
4785 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4786 hammer2_chain_setflush(chain);
4793 * Returns the index of the nearest element in the blockref array >= elm.
4794 * Returns (count) if no element could be found.
4796 * Sets *key_nextp to the next key for loop purposes but does not modify
4797 * it if the next key would be higher than the current value of *key_nextp.
4798 * Note that *key_nexp can overflow to 0, which should be tested by the
4801 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4802 * held through the operation.
4805 hammer2_base_find(hammer2_chain_t *parent,
4806 hammer2_blockref_t *base, int count,
4807 hammer2_key_t *key_nextp,
4808 hammer2_key_t key_beg, hammer2_key_t key_end)
4810 hammer2_blockref_t *scan;
4811 hammer2_key_t scan_end;
4816 * Require the live chain's already have their core's counted
4817 * so we can optimize operations.
4819 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4824 if (count == 0 || base == NULL)
4828 * Sequential optimization using parent->cache_index. This is
4829 * the most likely scenario.
4831 * We can avoid trailing empty entries on live chains, otherwise
4832 * we might have to check the whole block array.
4834 i = parent->cache_index; /* SMP RACE OK */
4836 limit = parent->core.live_zero;
4841 KKASSERT(i < count);
4847 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4851 parent->cache_index = i;
4854 * Search forwards, stop when we find a scan element which
4855 * encloses the key or until we know that there are no further
4859 if (scan->type != 0) {
4860 scan_end = scan->key +
4861 ((hammer2_key_t)1 << scan->keybits) - 1;
4862 if (scan->key > key_beg || scan_end >= key_beg)
4871 parent->cache_index = i;
4875 scan_end = scan->key +
4876 ((hammer2_key_t)1 << scan->keybits);
4877 if (scan_end && (*key_nextp > scan_end ||
4879 *key_nextp = scan_end;
4887 * Do a combined search and return the next match either from the blockref
4888 * array or from the in-memory chain. Sets *bresp to the returned bref in
4889 * both cases, or sets it to NULL if the search exhausted. Only returns
4890 * a non-NULL chain if the search matched from the in-memory chain.
4892 * When no in-memory chain has been found and a non-NULL bref is returned
4896 * The returned chain is not locked or referenced. Use the returned bref
4897 * to determine if the search exhausted or not. Iterate if the base find
4898 * is chosen but matches a deleted chain.
4900 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4901 * held through the operation.
4904 hammer2_combined_find(hammer2_chain_t *parent,
4905 hammer2_blockref_t *base, int count,
4906 hammer2_key_t *key_nextp,
4907 hammer2_key_t key_beg, hammer2_key_t key_end,
4908 hammer2_blockref_t **bresp)
4910 hammer2_blockref_t *bref;
4911 hammer2_chain_t *chain;
4915 * Lookup in block array and in rbtree.
4917 *key_nextp = key_end + 1;
4918 i = hammer2_base_find(parent, base, count, key_nextp,
4920 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4925 if (i == count && chain == NULL) {
4931 * Only chain matched.
4934 bref = &chain->bref;
4939 * Only blockref matched.
4941 if (chain == NULL) {
4947 * Both in-memory and blockref matched, select the nearer element.
4949 * If both are flush with the left-hand side or both are the
4950 * same distance away, select the chain. In this situation the
4951 * chain must have been loaded from the matching blockmap.
4953 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4954 chain->bref.key == base[i].key) {
4955 KKASSERT(chain->bref.key == base[i].key);
4956 bref = &chain->bref;
4961 * Select the nearer key
4963 if (chain->bref.key < base[i].key) {
4964 bref = &chain->bref;
4971 * If the bref is out of bounds we've exhausted our search.
4974 if (bref->key > key_end) {
4984 * Locate the specified block array element and delete it. The element
4987 * The spin lock on the related chain must be held.
4989 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4990 * need to be adjusted when we commit the media change.
4993 hammer2_base_delete(hammer2_chain_t *parent,
4994 hammer2_blockref_t *base, int count,
4995 hammer2_chain_t *chain)
4997 hammer2_blockref_t *elm = &chain->bref;
4998 hammer2_blockref_t *scan;
4999 hammer2_key_t key_next;
5003 * Delete element. Expect the element to exist.
5005 * XXX see caller, flush code not yet sophisticated enough to prevent
5006 * re-flushed in some cases.
5008 key_next = 0; /* max range */
5009 i = hammer2_base_find(parent, base, count, &key_next,
5010 elm->key, elm->key);
5012 if (i == count || scan->type == 0 ||
5013 scan->key != elm->key ||
5014 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
5015 scan->keybits != elm->keybits)) {
5016 hammer2_spin_unex(&parent->core.spin);
5017 panic("delete base %p element not found at %d/%d elm %p\n",
5018 base, i, count, elm);
5023 * Update stats and zero the entry.
5025 * NOTE: Handle radix == 0 (0 bytes) case.
5027 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5028 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5029 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5031 switch(scan->type) {
5032 case HAMMER2_BREF_TYPE_INODE:
5033 --parent->bref.embed.stats.inode_count;
5035 case HAMMER2_BREF_TYPE_DATA:
5036 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5037 atomic_set_int(&chain->flags,
5038 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5040 if (parent->bref.leaf_count)
5041 --parent->bref.leaf_count;
5044 case HAMMER2_BREF_TYPE_INDIRECT:
5045 if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5046 parent->bref.embed.stats.data_count -=
5047 scan->embed.stats.data_count;
5048 parent->bref.embed.stats.inode_count -=
5049 scan->embed.stats.inode_count;
5051 if (scan->type == HAMMER2_BREF_TYPE_INODE)
5053 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5054 atomic_set_int(&chain->flags,
5055 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5057 if (parent->bref.leaf_count <= scan->leaf_count)
5058 parent->bref.leaf_count = 0;
5060 parent->bref.leaf_count -= scan->leaf_count;
5063 case HAMMER2_BREF_TYPE_DIRENT:
5064 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5065 atomic_set_int(&chain->flags,
5066 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5068 if (parent->bref.leaf_count)
5069 --parent->bref.leaf_count;
5075 bzero(scan, sizeof(*scan));
5078 * We can only optimize parent->core.live_zero for live chains.
5080 if (parent->core.live_zero == i + 1) {
5081 while (--i >= 0 && base[i].type == 0)
5083 parent->core.live_zero = i + 1;
5087 * Clear appropriate blockmap flags in chain.
5089 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
5090 HAMMER2_CHAIN_BMAPUPD);
5094 * Insert the specified element. The block array must not already have the
5095 * element and must have space available for the insertion.
5097 * The spin lock on the related chain must be held.
5099 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5100 * need to be adjusted when we commit the media change.
5103 hammer2_base_insert(hammer2_chain_t *parent,
5104 hammer2_blockref_t *base, int count,
5105 hammer2_chain_t *chain, hammer2_blockref_t *elm)
5107 hammer2_key_t key_next;
5116 * Insert new element. Expect the element to not already exist
5117 * unless we are replacing it.
5119 * XXX see caller, flush code not yet sophisticated enough to prevent
5120 * re-flushed in some cases.
5122 key_next = 0; /* max range */
5123 i = hammer2_base_find(parent, base, count, &key_next,
5124 elm->key, elm->key);
5127 * Shortcut fill optimization, typical ordered insertion(s) may not
5130 KKASSERT(i >= 0 && i <= count);
5133 * Set appropriate blockmap flags in chain (if not NULL)
5136 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
5139 * Update stats and zero the entry
5141 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5142 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5143 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5146 case HAMMER2_BREF_TYPE_INODE:
5147 ++parent->bref.embed.stats.inode_count;
5149 case HAMMER2_BREF_TYPE_DATA:
5150 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5151 ++parent->bref.leaf_count;
5153 case HAMMER2_BREF_TYPE_INDIRECT:
5154 if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5155 parent->bref.embed.stats.data_count +=
5156 elm->embed.stats.data_count;
5157 parent->bref.embed.stats.inode_count +=
5158 elm->embed.stats.inode_count;
5160 if (elm->type == HAMMER2_BREF_TYPE_INODE)
5162 if (parent->bref.leaf_count + elm->leaf_count <
5163 HAMMER2_BLOCKREF_LEAF_MAX) {
5164 parent->bref.leaf_count += elm->leaf_count;
5166 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5169 case HAMMER2_BREF_TYPE_DIRENT:
5170 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5171 ++parent->bref.leaf_count;
5179 * We can only optimize parent->core.live_zero for live chains.
5181 if (i == count && parent->core.live_zero < count) {
5182 i = parent->core.live_zero++;
5187 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5188 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5189 hammer2_spin_unex(&parent->core.spin);
5190 panic("insert base %p overlapping elements at %d elm %p\n",
5195 * Try to find an empty slot before or after.
5199 while (j > 0 || k < count) {
5201 if (j >= 0 && base[j].type == 0) {
5205 bcopy(&base[j+1], &base[j],
5206 (i - j - 1) * sizeof(*base));
5212 if (k < count && base[k].type == 0) {
5213 bcopy(&base[i], &base[i+1],
5214 (k - i) * sizeof(hammer2_blockref_t));
5218 * We can only update parent->core.live_zero for live
5221 if (parent->core.live_zero <= k)
5222 parent->core.live_zero = k + 1;
5227 panic("hammer2_base_insert: no room!");
5234 for (l = 0; l < count; ++l) {
5236 key_next = base[l].key +
5237 ((hammer2_key_t)1 << base[l].keybits) - 1;
5241 while (++l < count) {
5243 if (base[l].key <= key_next)
5244 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5245 key_next = base[l].key +
5246 ((hammer2_key_t)1 << base[l].keybits) - 1;
5256 * Sort the blockref array for the chain. Used by the flush code to
5257 * sort the blockref[] array.
5259 * The chain must be exclusively locked AND spin-locked.
5261 typedef hammer2_blockref_t *hammer2_blockref_p;
5265 hammer2_base_sort_callback(const void *v1, const void *v2)
5267 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5268 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5271 * Make sure empty elements are placed at the end of the array
5273 if (bref1->type == 0) {
5274 if (bref2->type == 0)
5277 } else if (bref2->type == 0) {
5284 if (bref1->key < bref2->key)
5286 if (bref1->key > bref2->key)
5292 hammer2_base_sort(hammer2_chain_t *chain)
5294 hammer2_blockref_t *base;
5297 switch(chain->bref.type) {
5298 case HAMMER2_BREF_TYPE_INODE:
5300 * Special shortcut for embedded data returns the inode
5301 * itself. Callers must detect this condition and access
5302 * the embedded data (the strategy code does this for us).
5304 * This is only applicable to regular files and softlinks.
5306 if (chain->data->ipdata.meta.op_flags &
5307 HAMMER2_OPFLAG_DIRECTDATA) {
5310 base = &chain->data->ipdata.u.blockset.blockref[0];
5311 count = HAMMER2_SET_COUNT;
5313 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5314 case HAMMER2_BREF_TYPE_INDIRECT:
5316 * Optimize indirect blocks in the INITIAL state to avoid
5319 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5320 base = &chain->data->npdata[0];
5321 count = chain->bytes / sizeof(hammer2_blockref_t);
5323 case HAMMER2_BREF_TYPE_VOLUME:
5324 base = &chain->data->voldata.sroot_blockset.blockref[0];
5325 count = HAMMER2_SET_COUNT;
5327 case HAMMER2_BREF_TYPE_FREEMAP:
5328 base = &chain->data->blkset.blockref[0];
5329 count = HAMMER2_SET_COUNT;
5332 kprintf("hammer2_chain_lookup: unrecognized "
5333 "blockref(A) type: %d",
5336 tsleep(&base, 0, "dead", 0);
5337 panic("hammer2_chain_lookup: unrecognized "
5338 "blockref(A) type: %d",
5340 base = NULL; /* safety */
5341 count = 0; /* safety */
5343 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5349 * Chain memory management
5352 hammer2_chain_wait(hammer2_chain_t *chain)
5354 tsleep(chain, 0, "chnflw", 1);
5357 const hammer2_media_data_t *
5358 hammer2_chain_rdata(hammer2_chain_t *chain)
5360 KKASSERT(chain->data != NULL);
5361 return (chain->data);
5364 hammer2_media_data_t *
5365 hammer2_chain_wdata(hammer2_chain_t *chain)
5367 KKASSERT(chain->data != NULL);
5368 return (chain->data);
5372 * Set the check data for a chain. This can be a heavy-weight operation
5373 * and typically only runs on-flush. For file data check data is calculated
5374 * when the logical buffers are flushed.
5377 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5379 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5381 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5382 case HAMMER2_CHECK_NONE:
5384 case HAMMER2_CHECK_DISABLED:
5386 case HAMMER2_CHECK_ISCSI32:
5387 chain->bref.check.iscsi32.value =
5388 hammer2_icrc32(bdata, chain->bytes);
5390 case HAMMER2_CHECK_XXHASH64:
5391 chain->bref.check.xxhash64.value =
5392 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5394 case HAMMER2_CHECK_SHA192:
5396 SHA256_CTX hash_ctx;
5398 uint8_t digest[SHA256_DIGEST_LENGTH];
5399 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5402 SHA256_Init(&hash_ctx);
5403 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5404 SHA256_Final(u.digest, &hash_ctx);
5405 u.digest64[2] ^= u.digest64[3];
5407 chain->bref.check.sha192.data,
5408 sizeof(chain->bref.check.sha192.data));
5411 case HAMMER2_CHECK_FREEMAP:
5412 chain->bref.check.freemap.icrc32 =
5413 hammer2_icrc32(bdata, chain->bytes);
5416 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5417 chain->bref.methods);
5423 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5429 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5432 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5433 case HAMMER2_CHECK_NONE:
5436 case HAMMER2_CHECK_DISABLED:
5439 case HAMMER2_CHECK_ISCSI32:
5440 check32 = hammer2_icrc32(bdata, chain->bytes);
5441 r = (chain->bref.check.iscsi32.value == check32);
5443 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5444 "(flags=%08x, bref/data %08x/%08x)\n",
5445 chain->bref.data_off,
5447 chain->bref.methods,
5449 chain->bref.check.iscsi32.value,
5452 hammer2_check_icrc32 += chain->bytes;
5454 case HAMMER2_CHECK_XXHASH64:
5455 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5456 r = (chain->bref.check.xxhash64.value == check64);
5458 kprintf("chain %016jx.%02x key=%016jx "
5459 "meth=%02x CHECK FAIL "
5460 "(flags=%08x, bref/data %016jx/%016jx)\n",
5461 chain->bref.data_off,
5464 chain->bref.methods,
5466 chain->bref.check.xxhash64.value,
5469 hammer2_check_xxhash64 += chain->bytes;
5471 case HAMMER2_CHECK_SHA192:
5473 SHA256_CTX hash_ctx;
5475 uint8_t digest[SHA256_DIGEST_LENGTH];
5476 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5479 SHA256_Init(&hash_ctx);
5480 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5481 SHA256_Final(u.digest, &hash_ctx);
5482 u.digest64[2] ^= u.digest64[3];
5484 chain->bref.check.sha192.data,
5485 sizeof(chain->bref.check.sha192.data)) == 0) {
5489 kprintf("chain %016jx.%02x meth=%02x "
5491 chain->bref.data_off,
5493 chain->bref.methods);
5497 case HAMMER2_CHECK_FREEMAP:
5498 r = (chain->bref.check.freemap.icrc32 ==
5499 hammer2_icrc32(bdata, chain->bytes));
5501 kprintf("chain %016jx.%02x meth=%02x "
5503 chain->bref.data_off,
5505 chain->bref.methods);
5506 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5507 chain->bref.check.freemap.icrc32,
5508 hammer2_icrc32(bdata, chain->bytes),
5511 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5512 chain->dio, chain->dio->bp->b_loffset,
5513 chain->dio->bp->b_bufsize, bdata,
5514 chain->dio->bp->b_data);
5519 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5520 chain->bref.methods);
5528 * Acquire the chain and parent representing the specified inode for the
5529 * device at the specified cluster index.
5531 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5533 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5534 * will be NULL. *parentp may still be set error or not, or NULL if the
5535 * parent itself could not be resolved.
5537 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5538 * *parentp and *chainp will be unlocked if not NULL.
5541 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5542 int clindex, int flags,
5543 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5545 hammer2_chain_t *parent;
5546 hammer2_chain_t *rchain;
5547 hammer2_key_t key_dummy;
5551 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5552 HAMMER2_RESOLVE_SHARED : 0;
5555 * Caller expects us to replace these.
5558 hammer2_chain_unlock(*chainp);
5559 hammer2_chain_drop(*chainp);
5563 hammer2_chain_unlock(*parentp);
5564 hammer2_chain_drop(*parentp);
5569 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5570 * inodes from root directory entries in the key lookup).
5572 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5575 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5579 error = HAMMER2_ERROR_EIO;
5588 * Used by the bulkscan code to snapshot the synchronized storage for
5589 * a volume, allowing it to be scanned concurrently against normal
5593 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5595 hammer2_chain_t *copy;
5597 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5598 copy->data = kmalloc(sizeof(copy->data->voldata),
5601 hammer2_voldata_lock(hmp);
5602 copy->data->voldata = hmp->volsync;
5603 hammer2_voldata_unlock(hmp);
5609 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5611 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5612 KKASSERT(copy->data);
5613 kfree(copy->data, copy->hmp->mchain);
5615 atomic_add_long(&hammer2_chain_allocs, -1);
5616 hammer2_chain_drop(copy);
5620 * Returns non-zero if the chain (INODE or DIRENT) matches the
5624 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5627 const hammer2_inode_data_t *ripdata;
5628 const hammer2_dirent_head_t *den;
5630 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5631 ripdata = &chain->data->ipdata;
5632 if (ripdata->meta.name_len == name_len &&
5633 bcmp(ripdata->filename, name, name_len) == 0) {
5637 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5638 chain->bref.embed.dirent.namlen == name_len) {
5639 den = &chain->bref.embed.dirent;
5640 if (name_len > sizeof(chain->bref.check.buf) &&
5641 bcmp(chain->data->buf, name, name_len) == 0) {
5644 if (name_len <= sizeof(chain->bref.check.buf) &&
5645 bcmp(chain->bref.check.buf, name, name_len) == 0) {