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 int hammer2_indirect_optimize; /* XXX SYSCTL */
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70 hammer2_chain_t *parent,
71 hammer2_key_t key, int keybits,
72 hammer2_tid_t mtid, int for_type, int *errorp);
73 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain,
75 static hammer2_chain_t *hammer2_combined_find(
76 hammer2_chain_t *parent,
77 hammer2_blockref_t *base, int count,
78 int *cache_indexp, hammer2_key_t *key_nextp,
79 hammer2_key_t key_beg, hammer2_key_t key_end,
80 hammer2_blockref_t **bresp);
83 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
84 * overlap in the RB trees. Deleted chains are moved from rbtree to either
87 * Chains in delete-duplicate sequences can always iterate through core_entry
88 * to locate the live version of the chain.
90 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
92 extern int h2timer[32];
96 #define TIMER(which) do { \
98 h2timer[h2lid] += (int)(ticks - h2last);\
104 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
106 hammer2_key_t c1_beg;
107 hammer2_key_t c1_end;
108 hammer2_key_t c2_beg;
109 hammer2_key_t c2_end;
112 * Compare chains. Overlaps are not supposed to happen and catch
113 * any software issues early we count overlaps as a match.
115 c1_beg = chain1->bref.key;
116 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
117 c2_beg = chain2->bref.key;
118 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
120 if (c1_end < c2_beg) /* fully to the left */
122 if (c1_beg > c2_end) /* fully to the right */
124 return(0); /* overlap (must not cross edge boundary) */
129 hammer2_isclusterable(hammer2_chain_t *chain)
131 if (hammer2_cluster_enable) {
132 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
133 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
134 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
142 * Make a chain visible to the flusher. The flusher needs to be able to
143 * do flushes of subdirectory chains or single files so it does a top-down
144 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
145 * or UPDATE chains and flushes back up the chain to the volume root.
147 * This routine sets ONFLUSH upward until it hits the volume root. For
148 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
149 * Extra ONFLUSH flagging doesn't hurt the filesystem.
152 hammer2_chain_setflush(hammer2_chain_t *chain)
154 hammer2_chain_t *parent;
156 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
157 hammer2_spin_sh(&chain->core.spin);
158 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
159 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
160 if ((parent = chain->parent) == NULL)
162 hammer2_spin_sh(&parent->core.spin);
163 hammer2_spin_unsh(&chain->core.spin);
166 hammer2_spin_unsh(&chain->core.spin);
171 * Allocate a new disconnected chain element representing the specified
172 * bref. chain->refs is set to 1 and the passed bref is copied to
173 * chain->bref. chain->bytes is derived from the bref.
175 * chain->pmp inherits pmp unless the chain is an inode (other than the
178 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
181 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
182 hammer2_blockref_t *bref)
184 hammer2_chain_t *chain;
185 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
187 atomic_add_long(&hammer2_chain_allocs, 1);
190 * Construct the appropriate system structure.
193 case HAMMER2_BREF_TYPE_INODE:
194 case HAMMER2_BREF_TYPE_INDIRECT:
195 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
196 case HAMMER2_BREF_TYPE_DATA:
197 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
199 * Chain's are really only associated with the hmp but we
200 * maintain a pmp association for per-mount memory tracking
201 * purposes. The pmp can be NULL.
203 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
205 case HAMMER2_BREF_TYPE_VOLUME:
206 case HAMMER2_BREF_TYPE_FREEMAP:
208 * Only hammer2_chain_bulksnap() calls this function with these
211 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
215 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
220 * Initialize the new chain structure. pmp must be set to NULL for
221 * chains belonging to the super-root topology of a device mount.
223 if (pmp == hmp->spmp)
229 chain->bytes = bytes;
231 chain->flags = HAMMER2_CHAIN_ALLOCATED;
234 * Set the PFS boundary flag if this chain represents a PFS root.
236 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
237 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
238 hammer2_chain_core_init(chain);
244 * Initialize a chain's core structure. This structure used to be allocated
245 * but is now embedded.
247 * The core is not locked. No additional refs on the chain are made.
248 * (trans) must not be NULL if (core) is not NULL.
251 hammer2_chain_core_init(hammer2_chain_t *chain)
254 * Fresh core under nchain (no multi-homing of ochain's
257 RB_INIT(&chain->core.rbtree); /* live chains */
258 hammer2_mtx_init(&chain->lock, "h2chain");
262 * Add a reference to a chain element, preventing its destruction.
264 * (can be called with spinlock held)
267 hammer2_chain_ref(hammer2_chain_t *chain)
269 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
271 * 0->non-zero transition must ensure that chain is removed
274 * NOTE: Already holding lru_spin here so we cannot call
275 * hammer2_chain_ref() to get it off lru_list, do
278 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
279 hammer2_pfs_t *pmp = chain->pmp;
280 hammer2_spin_ex(&pmp->lru_spin);
281 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
282 atomic_add_int(&pmp->lru_count, -1);
283 atomic_clear_int(&chain->flags,
284 HAMMER2_CHAIN_ONLRU);
285 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
287 hammer2_spin_unex(&pmp->lru_spin);
291 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
297 * Insert the chain in the core rbtree.
299 * Normal insertions are placed in the live rbtree. Insertion of a deleted
300 * chain is a special case used by the flush code that is placed on the
301 * unstaged deleted list to avoid confusing the live view.
303 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
304 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
305 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
309 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
310 int flags, int generation)
312 hammer2_chain_t *xchain;
315 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
316 hammer2_spin_ex(&parent->core.spin);
319 * Interlocked by spinlock, check for race
321 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
322 parent->core.generation != generation) {
330 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
331 KASSERT(xchain == NULL,
332 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
333 chain, xchain, chain->bref.key));
334 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
335 chain->parent = parent;
336 ++parent->core.chain_count;
337 ++parent->core.generation; /* XXX incs for _get() too, XXX */
340 * We have to keep track of the effective live-view blockref count
341 * so the create code knows when to push an indirect block.
343 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
344 atomic_add_int(&parent->core.live_count, 1);
346 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
347 hammer2_spin_unex(&parent->core.spin);
352 * Drop the caller's reference to the chain. When the ref count drops to
353 * zero this function will try to disassociate the chain from its parent and
354 * deallocate it, then recursely drop the parent using the implied ref
355 * from the chain's chain->parent.
357 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
360 hammer2_chain_drop(hammer2_chain_t *chain)
364 if (hammer2_debug & 0x200000)
367 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
371 KKASSERT(chain->refs > 0);
379 chain = hammer2_chain_lastdrop(chain);
381 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
383 /* retry the same chain */
389 * Safe handling of the 1->0 transition on chain. Returns a chain for
390 * recursive drop or NULL, possibly returning the same chain if the atomic
393 * When two chains need to be recursively dropped we use the chain we
394 * would otherwise free to placehold the additional chain. It's a bit
395 * convoluted but we can't just recurse without potentially blowing out
398 * The chain cannot be freed if it has any children.
399 * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
400 * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
402 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
406 hammer2_chain_lastdrop(hammer2_chain_t *chain)
410 hammer2_chain_t *parent;
411 hammer2_chain_t *rdrop;
415 * Critical field access.
417 hammer2_spin_ex(&chain->core.spin);
419 if ((parent = chain->parent) != NULL) {
421 * If the chain has a parent the UPDATE bit prevents scrapping
422 * as the chain is needed to properly flush the parent. Try
423 * to complete the 1->0 transition and return NULL. Retry
424 * (return chain) if we are unable to complete the 1->0
425 * transition, else return NULL (nothing more to do).
427 * If the chain has a parent the MODIFIED bit prevents
430 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
432 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
433 HAMMER2_CHAIN_MODIFIED)) {
434 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
435 dio = hammer2_chain_drop_data(chain, 0);
436 hammer2_spin_unex(&chain->core.spin);
438 hammer2_io_bqrelse(&dio);
441 hammer2_spin_unex(&chain->core.spin);
445 /* spinlock still held */
448 * The chain has no parent and can be flagged for destruction.
449 * Since it has no parent, UPDATE can also be cleared.
451 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
452 if (chain->flags & HAMMER2_CHAIN_UPDATE)
453 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
456 * If the chain has children or if it has been MODIFIED and
457 * also recorded for DEDUP, we must still flush the chain.
459 * In the case where it has children, the DESTROY flag test
460 * in the flush code will prevent unnecessary flushes of
461 * MODIFIED chains that are not flagged DEDUP so don't worry
464 if (chain->core.chain_count ||
465 (chain->flags & (HAMMER2_CHAIN_MODIFIED |
466 HAMMER2_CHAIN_DEDUP)) ==
467 (HAMMER2_CHAIN_MODIFIED |
468 HAMMER2_CHAIN_DEDUP)) {
470 * Put on flushq (should ensure refs > 1), retry
473 hammer2_spin_unex(&chain->core.spin);
474 hammer2_delayed_flush(chain);
475 return(chain); /* retry drop */
479 * Otherwise we can scrap the MODIFIED bit if it is set,
480 * and continue along the freeing path.
482 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
483 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
484 atomic_add_long(&hammer2_count_modified_chains, -1);
486 /* spinlock still held */
489 /* spinlock still held */
493 * If any children exist we must leave the chain intact with refs == 0.
494 * They exist because chains are retained below us which have refs or
495 * may require flushing. This case can occur when parent != NULL.
497 * Retry (return chain) if we fail to transition the refs to 0, else
498 * return NULL indication nothing more to do.
500 * Chains with children are NOT put on the LRU list.
502 if (chain->core.chain_count) {
504 hammer2_spin_ex(&parent->core.spin);
505 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
506 dio = hammer2_chain_drop_data(chain, 1);
507 hammer2_spin_unex(&chain->core.spin);
509 hammer2_spin_unex(&parent->core.spin);
512 hammer2_io_bqrelse(&dio);
514 hammer2_spin_unex(&chain->core.spin);
516 hammer2_spin_unex(&parent->core.spin);
520 /* spinlock still held */
521 /* no chains left under us */
524 * chain->core has no children left so no accessors can get to our
525 * chain from there. Now we have to lock the parent core to interlock
526 * remaining possible accessors that might bump chain's refs before
527 * we can safely drop chain's refs with intent to free the chain.
530 pmp = chain->pmp; /* can be NULL */
533 parent = chain->parent;
536 * WARNING! chain's spin lock is still held here, and other spinlocks
537 * will be acquired and released in the code below. We
538 * cannot be making fancy procedure calls!
542 * We can cache the chain if it is associated with a pmp
543 * and not flagged as being destroyed or requesting a full
544 * release. In this situation the chain is not removed
545 * from its parent, i.e. it can still be looked up.
547 * We intentionally do not cache DATA chains because these
548 * were likely used to load data into the logical buffer cache
549 * and will not be accessed again for some time.
552 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
554 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
556 hammer2_spin_ex(&parent->core.spin);
557 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
559 * 1->0 transition failed, retry. Do not drop
560 * the chain's data yet!
563 hammer2_spin_unex(&parent->core.spin);
564 hammer2_spin_unex(&chain->core.spin);
570 * Success, be sure to clean out the chain's data
571 * before putting it on a queue that it might be
574 dio = hammer2_chain_drop_data(chain, 1);
576 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
577 hammer2_spin_ex(&pmp->lru_spin);
578 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
579 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
582 * If we are over the LRU limit we need to drop something.
584 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
585 rdrop = TAILQ_FIRST(&pmp->lru_list);
586 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
587 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
588 atomic_add_int(&rdrop->refs, 1);
589 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
591 atomic_add_int(&pmp->lru_count, 1);
593 hammer2_spin_unex(&pmp->lru_spin);
595 hammer2_spin_unex(&parent->core.spin);
596 parent = NULL; /* safety */
598 hammer2_spin_unex(&chain->core.spin);
600 hammer2_io_bqrelse(&dio);
607 * Spinlock the parent and try to drop the last ref on chain.
608 * On success determine if we should dispose of the chain
609 * (remove the chain from its parent, etc).
611 * (normal core locks are top-down recursive but we define
612 * core spinlocks as bottom-up recursive, so this is safe).
615 hammer2_spin_ex(&parent->core.spin);
616 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
618 * 1->0 transition failed, retry.
620 hammer2_spin_unex(&parent->core.spin);
621 dio = hammer2_chain_drop_data(chain, 0);
622 hammer2_spin_unex(&chain->core.spin);
624 hammer2_io_bqrelse(&dio);
629 * 1->0 transition successful, remove chain from the
632 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
633 RB_REMOVE(hammer2_chain_tree,
634 &parent->core.rbtree, chain);
635 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
636 --parent->core.chain_count;
637 chain->parent = NULL;
641 * If our chain was the last chain in the parent's core the
642 * core is now empty and its parent might have to be
643 * re-dropped if it has 0 refs.
645 if (parent->core.chain_count == 0) {
647 atomic_add_int(&rdrop->refs, 1);
649 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
653 hammer2_spin_unex(&parent->core.spin);
654 parent = NULL; /* safety */
659 * Successful 1->0 transition and the chain can be destroyed now.
661 * We still have the core spinlock, and core's chain_count is 0.
662 * Any parent spinlock is gone.
664 hammer2_spin_unex(&chain->core.spin);
665 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
666 chain->core.chain_count == 0);
669 * All spin locks are gone, no pointers remain to the chain, finish
672 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
673 HAMMER2_CHAIN_MODIFIED)) == 0);
674 dio = hammer2_chain_drop_data(chain, 1);
676 hammer2_io_bqrelse(&dio);
679 * Once chain resources are gone we can use the now dead chain
680 * structure to placehold what might otherwise require a recursive
681 * drop, because we have potentially two things to drop and can only
682 * return one directly.
684 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
685 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
687 kfree(chain, hmp->mchain);
691 * Possible chaining loop when parent re-drop needed.
697 * On either last lock release or last drop
699 static hammer2_io_t *
700 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
704 if ((dio = chain->dio) != NULL) {
708 switch(chain->bref.type) {
709 case HAMMER2_BREF_TYPE_VOLUME:
710 case HAMMER2_BREF_TYPE_FREEMAP:
715 KKASSERT(chain->data == NULL);
723 * Lock a referenced chain element, acquiring its data with I/O if necessary,
724 * and specify how you would like the data to be resolved.
726 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
728 * The lock is allowed to recurse, multiple locking ops will aggregate
729 * the requested resolve types. Once data is assigned it will not be
730 * removed until the last unlock.
732 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
733 * (typically used to avoid device/logical buffer
736 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
737 * the INITIAL-create state (indirect blocks only).
739 * Do not resolve data elements for DATA chains.
740 * (typically used to avoid device/logical buffer
743 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
745 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
746 * it will be locked exclusive.
748 * NOTE: Embedded elements (volume header, inodes) are always resolved
751 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
752 * element will instantiate and zero its buffer, and flush it on
755 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
756 * so as not to instantiate a device buffer, which could alias against
757 * a logical file buffer. However, if ALWAYS is specified the
758 * device buffer will be instantiated anyway.
760 * WARNING! This function blocks on I/O if data needs to be fetched. This
761 * blocking can run concurrent with other compatible lock holders
762 * who do not need data returning. The lock is not upgraded to
763 * exclusive during a data fetch, a separate bit is used to
764 * interlock I/O. However, an exclusive lock holder can still count
765 * on being interlocked against an I/O fetch managed by a shared
769 hammer2_chain_lock(hammer2_chain_t *chain, int how)
772 * Ref and lock the element. Recursive locks are allowed.
774 KKASSERT(chain->refs > 0);
775 atomic_add_int(&chain->lockcnt, 1);
779 * Get the appropriate lock.
781 if (how & HAMMER2_RESOLVE_SHARED)
782 hammer2_mtx_sh(&chain->lock);
784 hammer2_mtx_ex(&chain->lock);
785 ++curthread->td_tracker;
789 * If we already have a valid data pointer no further action is
797 * Do we have to resolve the data?
799 switch(how & HAMMER2_RESOLVE_MASK) {
800 case HAMMER2_RESOLVE_NEVER:
802 case HAMMER2_RESOLVE_MAYBE:
803 if (chain->flags & HAMMER2_CHAIN_INITIAL)
805 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
808 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
810 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
814 case HAMMER2_RESOLVE_ALWAYS:
820 * Caller requires data
822 hammer2_chain_load_data(chain);
826 * Downgrade an exclusive chain lock to a shared chain lock.
828 * NOTE: There is no upgrade equivalent due to the ease of
829 * deadlocks in that direction.
832 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
834 hammer2_mtx_downgrade(&chain->lock);
838 * Obtains a second shared lock on the chain, does not account the second
839 * shared lock as being owned by the current thread.
841 * Caller must already own a shared lock on this chain.
843 * The lock function is required to obtain the second shared lock without
844 * blocking on pending exclusive requests.
847 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
849 hammer2_mtx_sh_again(&chain->lock);
850 atomic_add_int(&chain->lockcnt, 1);
851 /* do not count in td_tracker for this thread */
855 * Accounts for a shared lock that was pushed to us as being owned by our
859 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
861 ++curthread->td_tracker;
865 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
866 * may be of any type.
868 * Once chain->data is set it cannot be disposed of until all locks are
872 hammer2_chain_load_data(hammer2_chain_t *chain)
874 hammer2_blockref_t *bref;
880 * Degenerate case, data already present.
887 KKASSERT(hmp != NULL);
890 * Gain the IOINPROG bit, interlocked block.
896 oflags = chain->flags;
898 if (oflags & HAMMER2_CHAIN_IOINPROG) {
899 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
900 tsleep_interlock(&chain->flags, 0);
901 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
902 tsleep(&chain->flags, PINTERLOCKED,
907 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
908 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
917 * We own CHAIN_IOINPROG
919 * Degenerate case if we raced another load.
925 * We must resolve to a device buffer, either by issuing I/O or
926 * by creating a zero-fill element. We do not mark the buffer
927 * dirty when creating a zero-fill element (the hammer2_chain_modify()
928 * API must still be used to do that).
930 * The device buffer is variable-sized in powers of 2 down
931 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
932 * chunk always contains buffers of the same size. (XXX)
934 * The minimum physical IO size may be larger than the variable
940 * The getblk() optimization can only be used on newly created
941 * elements if the physical block size matches the request.
943 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
944 error = hammer2_io_new(hmp, bref->type,
945 bref->data_off, chain->bytes,
948 error = hammer2_io_bread(hmp, bref->type,
949 bref->data_off, chain->bytes,
951 hammer2_adjreadcounter(&chain->bref, chain->bytes);
955 chain->error = HAMMER2_ERROR_IO;
956 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
957 (intmax_t)bref->data_off, error);
958 hammer2_io_bqrelse(&chain->dio);
964 * NOTE: A locked chain's data cannot be modified without first
965 * calling hammer2_chain_modify().
969 * Clear INITIAL. In this case we used io_new() and the buffer has
970 * been zero'd and marked dirty.
972 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
973 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
974 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
975 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
976 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
978 * check data not currently synchronized due to
979 * modification. XXX assumes data stays in the buffer
980 * cache, which might not be true (need biodep on flush
981 * to calculate crc? or simple crc?).
983 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
987 if (hammer2_io_crc_good(chain, &mask)) {
988 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
989 } else if (hammer2_chain_testcheck(chain, bdata) == 0) {
990 kprintf("chain %016jx.%02x meth=%02x "
991 "CHECK FAIL %08x (flags=%08x)\n",
992 chain->bref.data_off,
995 hammer2_icrc32(bdata, chain->bytes),
997 chain->error = HAMMER2_ERROR_CHECK;
999 hammer2_io_crc_setmask(chain->dio, mask);
1001 kprintf("chain %02x %016jx %u\n",
1002 chain->bref.type, chain->bref.key,
1005 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1011 * Setup the data pointer, either pointing it to an embedded data
1012 * structure and copying the data from the buffer, or pointing it
1015 * The buffer is not retained when copying to an embedded data
1016 * structure in order to avoid potential deadlocks or recursions
1017 * on the same physical buffer.
1019 * WARNING! Other threads can start using the data the instant we
1020 * set chain->data non-NULL.
1022 switch (bref->type) {
1023 case HAMMER2_BREF_TYPE_VOLUME:
1024 case HAMMER2_BREF_TYPE_FREEMAP:
1026 * Copy data from bp to embedded buffer
1028 panic("hammer2_chain_lock: called on unresolved volume header");
1030 case HAMMER2_BREF_TYPE_INODE:
1031 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1032 case HAMMER2_BREF_TYPE_INDIRECT:
1033 case HAMMER2_BREF_TYPE_DATA:
1034 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1037 * Point data at the device buffer and leave dio intact.
1039 chain->data = (void *)bdata;
1044 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1051 oflags = chain->flags;
1052 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1053 HAMMER2_CHAIN_IOSIGNAL);
1054 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1055 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1056 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1057 wakeup(&chain->flags);
1065 * Unlock and deref a chain element.
1067 * Remember that the presence of children under chain prevent the chain's
1068 * destruction but do not add additional references, so the dio will still
1072 hammer2_chain_unlock(hammer2_chain_t *chain)
1076 --curthread->td_tracker;
1078 * If multiple locks are present (or being attempted) on this
1079 * particular chain we can just unlock, drop refs, and return.
1081 * Otherwise fall-through on the 1->0 transition.
1084 lockcnt = chain->lockcnt;
1085 KKASSERT(lockcnt > 0);
1088 if (atomic_cmpset_int(&chain->lockcnt,
1089 lockcnt, lockcnt - 1)) {
1090 hammer2_mtx_unlock(&chain->lock);
1094 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1101 * Normally we want to disassociate the data on the last unlock,
1102 * but leave it intact if persist_refs is non-zero. The persist-data
1103 * user modifies persist_refs only while holding the chain locked
1104 * so there should be no race on the last unlock here.
1106 * NOTE: If this was a shared lock we have to temporarily upgrade it
1107 * to prevent data load races. We can only do this non-blocking,
1108 * and unlock/relock-excl can deadlock. If the try fails it
1109 * means someone else got a shared or exclusive lock while we
1110 * we bandying about.
1112 if (chain->persist_refs == 0) {
1115 if (hammer2_mtx_upgrade_try(&chain->lock) == 0 &&
1116 chain->lockcnt == 0) {
1117 dio = hammer2_chain_drop_data(chain, 0);
1119 hammer2_io_bqrelse(&dio);
1122 hammer2_mtx_unlock(&chain->lock);
1126 * Helper to obtain the blockref[] array base and count for a chain.
1128 * XXX Not widely used yet, various use cases need to be validated and
1129 * converted to use this function.
1132 hammer2_blockref_t *
1133 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1135 hammer2_blockref_t *base;
1138 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1141 switch(parent->bref.type) {
1142 case HAMMER2_BREF_TYPE_INODE:
1143 count = HAMMER2_SET_COUNT;
1145 case HAMMER2_BREF_TYPE_INDIRECT:
1146 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1147 count = parent->bytes / sizeof(hammer2_blockref_t);
1149 case HAMMER2_BREF_TYPE_VOLUME:
1150 count = HAMMER2_SET_COUNT;
1152 case HAMMER2_BREF_TYPE_FREEMAP:
1153 count = HAMMER2_SET_COUNT;
1156 panic("hammer2_chain_create_indirect: "
1157 "unrecognized blockref type: %d",
1163 switch(parent->bref.type) {
1164 case HAMMER2_BREF_TYPE_INODE:
1165 base = &parent->data->ipdata.u.blockset.blockref[0];
1166 count = HAMMER2_SET_COUNT;
1168 case HAMMER2_BREF_TYPE_INDIRECT:
1169 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1170 base = &parent->data->npdata[0];
1171 count = parent->bytes / sizeof(hammer2_blockref_t);
1173 case HAMMER2_BREF_TYPE_VOLUME:
1174 base = &parent->data->voldata.
1175 sroot_blockset.blockref[0];
1176 count = HAMMER2_SET_COUNT;
1178 case HAMMER2_BREF_TYPE_FREEMAP:
1179 base = &parent->data->blkset.blockref[0];
1180 count = HAMMER2_SET_COUNT;
1183 panic("hammer2_chain_create_indirect: "
1184 "unrecognized blockref type: %d",
1196 * This counts the number of live blockrefs in a block array and
1197 * also calculates the point at which all remaining blockrefs are empty.
1198 * This routine can only be called on a live chain (DUPLICATED flag not set).
1200 * NOTE: Flag is not set until after the count is complete, allowing
1201 * callers to test the flag without holding the spinlock.
1203 * NOTE: If base is NULL the related chain is still in the INITIAL
1204 * state and there are no blockrefs to count.
1206 * NOTE: live_count may already have some counts accumulated due to
1207 * creation and deletion and could even be initially negative.
1210 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1211 hammer2_blockref_t *base, int count)
1213 hammer2_spin_ex(&chain->core.spin);
1214 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1216 while (--count >= 0) {
1217 if (base[count].type)
1220 chain->core.live_zero = count + 1;
1221 while (count >= 0) {
1222 if (base[count].type)
1223 atomic_add_int(&chain->core.live_count,
1228 chain->core.live_zero = 0;
1230 /* else do not modify live_count */
1231 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1233 hammer2_spin_unex(&chain->core.spin);
1237 * Resize the chain's physical storage allocation in-place. This function does
1238 * not adjust the data pointer and must be followed by (typically) a
1239 * hammer2_chain_modify() call to copy any old data over and adjust the
1242 * Chains can be resized smaller without reallocating the storage. Resizing
1243 * larger will reallocate the storage. Excess or prior storage is reclaimed
1244 * asynchronously at a later time.
1246 * Must be passed an exclusively locked parent and chain.
1248 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1249 * to avoid instantiating a device buffer that conflicts with the vnode data
1250 * buffer. However, because H2 can compress or encrypt data, the chain may
1251 * have a dio assigned to it in those situations, and they do not conflict.
1253 * XXX return error if cannot resize.
1256 hammer2_chain_resize(hammer2_inode_t *ip,
1257 hammer2_chain_t *parent, hammer2_chain_t *chain,
1258 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1259 int nradix, int flags)
1268 * Only data and indirect blocks can be resized for now.
1269 * (The volu root, inodes, and freemap elements use a fixed size).
1271 KKASSERT(chain != &hmp->vchain);
1272 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1273 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1274 KKASSERT(chain->parent == parent);
1277 * Nothing to do if the element is already the proper size
1279 obytes = chain->bytes;
1280 nbytes = 1U << nradix;
1281 if (obytes == nbytes)
1285 * Make sure the old data is instantiated so we can copy it. If this
1286 * is a data block, the device data may be superfluous since the data
1287 * might be in a logical block, but compressed or encrypted data is
1290 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1292 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1295 * Relocate the block, even if making it smaller (because different
1296 * block sizes may be in different regions).
1298 * (data blocks only, we aren't copying the storage here).
1300 hammer2_freemap_alloc(chain, nbytes);
1301 chain->bytes = nbytes;
1302 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1305 * We don't want the followup chain_modify() to try to copy data
1306 * from the old (wrong-sized) buffer. It won't know how much to
1307 * copy. This case should only occur during writes when the
1308 * originator already has the data to write in-hand.
1311 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1312 hammer2_io_brelse(&chain->dio);
1318 * Set the chain modified so its data can be changed by the caller.
1320 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1321 * is a CLC (cluster level change) field and is not updated by parent
1322 * propagation during a flush.
1324 * If the caller passes a non-zero dedup_off we assign data_off to that
1325 * instead of allocating a ne block. Caller must not modify the data already
1326 * present at the target offset.
1329 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1330 hammer2_off_t dedup_off, int flags)
1332 hammer2_blockref_t obref;
1341 obref = chain->bref;
1342 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1345 * Data is not optional for freemap chains (we must always be sure
1346 * to copy the data on COW storage allocations).
1348 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1349 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1350 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1351 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1355 * Data must be resolved if already assigned, unless explicitly
1356 * flagged otherwise.
1358 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1359 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1360 hammer2_chain_load_data(chain);
1364 * Set MODIFIED to indicate that the chain has been modified.
1365 * Set UPDATE to ensure that the blockref is updated in the parent.
1367 if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1368 (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1370 * Modified already set but a new allocation is needed
1371 * anyway because we recorded this data_off for possible
1375 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1377 * Must set modified bit.
1379 atomic_add_long(&hammer2_count_modified_chains, 1);
1380 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1381 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1385 * Already flagged modified, no new allocation is needed.
1391 * Flag parent update required, clear DEDUP flag (already processed
1394 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1395 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1396 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1399 * The modification or re-modification requires an allocation and
1402 * If dedup_off is non-zero, caller already has a data offset
1403 * containing the caller's desired data. The dedup offset is
1404 * allowed to be in a partially free state and we must be sure
1405 * to reset it to a fully allocated state to force two bulkfree
1406 * passes to free it again.
1408 * XXX can a chain already be marked MODIFIED without a data
1409 * assignment? If not, assert here instead of testing the case.
1411 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1412 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1416 chain->bref.data_off = dedup_off;
1417 chain->bytes = 1 << (dedup_off &
1418 HAMMER2_OFF_MASK_RADIX);
1419 atomic_set_int(&chain->flags,
1420 HAMMER2_CHAIN_DEDUP);
1421 hammer2_freemap_adjust(hmp, &chain->bref,
1422 HAMMER2_FREEMAP_DORECOVER);
1424 hammer2_freemap_alloc(chain, chain->bytes);
1426 /* XXX failed allocation */
1431 * Update mirror_tid and modify_tid. modify_tid is only updated
1432 * if not passed as zero (during flushes, parent propagation passes
1435 * NOTE: chain->pmp could be the device spmp.
1437 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1439 chain->bref.modify_tid = mtid;
1442 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1443 * requires updating as well as to tell the delete code that the
1444 * chain's blockref might not exactly match (in terms of physical size
1445 * or block offset) the one in the parent's blocktable. The base key
1446 * of course will still match.
1448 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1449 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1452 * Short-cut data blocks which the caller does not need an actual
1453 * data reference to (aka OPTDATA), as long as the chain does not
1454 * already have a data pointer to the data. This generally means
1455 * that the modifications are being done via the logical buffer cache.
1456 * The INITIAL flag relates only to the device data buffer and thus
1457 * remains unchange in this situation.
1459 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1460 (flags & HAMMER2_MODIFY_OPTDATA) &&
1461 chain->data == NULL) {
1466 * Clearing the INITIAL flag (for indirect blocks) indicates that
1467 * we've processed the uninitialized storage allocation.
1469 * If this flag is already clear we are likely in a copy-on-write
1470 * situation but we have to be sure NOT to bzero the storage if
1471 * no data is present.
1473 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1474 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1481 * Instantiate data buffer and possibly execute COW operation
1483 switch(chain->bref.type) {
1484 case HAMMER2_BREF_TYPE_VOLUME:
1485 case HAMMER2_BREF_TYPE_FREEMAP:
1487 * The data is embedded, no copy-on-write operation is
1490 KKASSERT(chain->dio == NULL);
1492 case HAMMER2_BREF_TYPE_INODE:
1493 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1494 case HAMMER2_BREF_TYPE_DATA:
1495 case HAMMER2_BREF_TYPE_INDIRECT:
1496 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1498 * Perform the copy-on-write operation
1500 * zero-fill or copy-on-write depending on whether
1501 * chain->data exists or not and set the dirty state for
1502 * the new buffer. hammer2_io_new() will handle the
1505 * If a dedup_off was supplied this is an existing block
1506 * and no COW, copy, or further modification is required.
1508 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1510 if (wasinitial && dedup_off == 0) {
1511 error = hammer2_io_new(hmp, chain->bref.type,
1512 chain->bref.data_off,
1513 chain->bytes, &dio);
1515 error = hammer2_io_bread(hmp, chain->bref.type,
1516 chain->bref.data_off,
1517 chain->bytes, &dio);
1519 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1522 * If an I/O error occurs make sure callers cannot accidently
1523 * modify the old buffer's contents and corrupt the filesystem.
1526 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1528 chain->error = HAMMER2_ERROR_IO;
1529 hammer2_io_brelse(&dio);
1530 hammer2_io_brelse(&chain->dio);
1535 bdata = hammer2_io_data(dio, chain->bref.data_off);
1539 * COW (unless a dedup).
1541 KKASSERT(chain->dio != NULL);
1542 if (chain->data != (void *)bdata && dedup_off == 0) {
1543 bcopy(chain->data, bdata, chain->bytes);
1545 } else if (wasinitial == 0) {
1547 * We have a problem. We were asked to COW but
1548 * we don't have any data to COW with!
1550 panic("hammer2_chain_modify: having a COW %p\n",
1555 * Retire the old buffer, replace with the new. Dirty or
1556 * redirty the new buffer.
1558 * WARNING! The system buffer cache may have already flushed
1559 * the buffer, so we must be sure to [re]dirty it
1560 * for further modification.
1562 * If dedup_off was supplied, the caller is not
1563 * expected to make any further modification to the
1567 hammer2_io_bqrelse(&chain->dio);
1568 chain->data = (void *)bdata;
1571 hammer2_io_setdirty(dio);
1574 panic("hammer2_chain_modify: illegal non-embedded type %d",
1581 * setflush on parent indicating that the parent must recurse down
1582 * to us. Do not call on chain itself which might already have it
1586 hammer2_chain_setflush(chain->parent);
1590 * Modify the chain associated with an inode.
1593 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1594 hammer2_tid_t mtid, int flags)
1596 hammer2_inode_modify(ip);
1597 hammer2_chain_modify(chain, mtid, 0, flags);
1601 * Volume header data locks
1604 hammer2_voldata_lock(hammer2_dev_t *hmp)
1606 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1610 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1612 lockmgr(&hmp->vollk, LK_RELEASE);
1616 hammer2_voldata_modify(hammer2_dev_t *hmp)
1618 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1619 atomic_add_long(&hammer2_count_modified_chains, 1);
1620 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1621 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1626 * This function returns the chain at the nearest key within the specified
1627 * range. The returned chain will be referenced but not locked.
1629 * This function will recurse through chain->rbtree as necessary and will
1630 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1631 * the iteration value is less than the current value of *key_nextp.
1633 * The caller should use (*key_nextp) to calculate the actual range of
1634 * the returned element, which will be (key_beg to *key_nextp - 1), because
1635 * there might be another element which is superior to the returned element
1638 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1639 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1640 * it will wind up being (key_end + 1).
1642 * WARNING! Must be called with child's spinlock held. Spinlock remains
1643 * held through the operation.
1645 struct hammer2_chain_find_info {
1646 hammer2_chain_t *best;
1647 hammer2_key_t key_beg;
1648 hammer2_key_t key_end;
1649 hammer2_key_t key_next;
1652 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1653 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1657 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1658 hammer2_key_t key_beg, hammer2_key_t key_end)
1660 struct hammer2_chain_find_info info;
1663 info.key_beg = key_beg;
1664 info.key_end = key_end;
1665 info.key_next = *key_nextp;
1667 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1668 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1670 *key_nextp = info.key_next;
1672 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1673 parent, key_beg, key_end, *key_nextp);
1681 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1683 struct hammer2_chain_find_info *info = data;
1684 hammer2_key_t child_beg;
1685 hammer2_key_t child_end;
1687 child_beg = child->bref.key;
1688 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1690 if (child_end < info->key_beg)
1692 if (child_beg > info->key_end)
1699 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1701 struct hammer2_chain_find_info *info = data;
1702 hammer2_chain_t *best;
1703 hammer2_key_t child_end;
1706 * WARNING! Do not discard DUPLICATED chains, it is possible that
1707 * we are catching an insertion half-way done. If a
1708 * duplicated chain turns out to be the best choice the
1709 * caller will re-check its flags after locking it.
1711 * WARNING! Layerq is scanned forwards, exact matches should keep
1712 * the existing info->best.
1714 if ((best = info->best) == NULL) {
1716 * No previous best. Assign best
1719 } else if (best->bref.key <= info->key_beg &&
1720 child->bref.key <= info->key_beg) {
1725 /*info->best = child;*/
1726 } else if (child->bref.key < best->bref.key) {
1728 * Child has a nearer key and best is not flush with key_beg.
1729 * Set best to child. Truncate key_next to the old best key.
1732 if (info->key_next > best->bref.key || info->key_next == 0)
1733 info->key_next = best->bref.key;
1734 } else if (child->bref.key == best->bref.key) {
1736 * If our current best is flush with the child then this
1737 * is an illegal overlap.
1739 * key_next will automatically be limited to the smaller of
1740 * the two end-points.
1746 * Keep the current best but truncate key_next to the child's
1749 * key_next will also automatically be limited to the smaller
1750 * of the two end-points (probably not necessary for this case
1751 * but we do it anyway).
1753 if (info->key_next > child->bref.key || info->key_next == 0)
1754 info->key_next = child->bref.key;
1758 * Always truncate key_next based on child's end-of-range.
1760 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1761 if (child_end && (info->key_next > child_end || info->key_next == 0))
1762 info->key_next = child_end;
1768 * Retrieve the specified chain from a media blockref, creating the
1769 * in-memory chain structure which reflects it.
1771 * To handle insertion races pass the INSERT_RACE flag along with the
1772 * generation number of the core. NULL will be returned if the generation
1773 * number changes before we have a chance to insert the chain. Insert
1774 * races can occur because the parent might be held shared.
1776 * Caller must hold the parent locked shared or exclusive since we may
1777 * need the parent's bref array to find our block.
1779 * WARNING! chain->pmp is always set to NULL for any chain representing
1780 * part of the super-root topology.
1783 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1784 hammer2_blockref_t *bref)
1786 hammer2_dev_t *hmp = parent->hmp;
1787 hammer2_chain_t *chain;
1791 * Allocate a chain structure representing the existing media
1792 * entry. Resulting chain has one ref and is not locked.
1794 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1795 chain = hammer2_chain_alloc(hmp, NULL, bref);
1797 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1798 /* ref'd chain returned */
1801 * Flag that the chain is in the parent's blockmap so delete/flush
1802 * knows what to do with it.
1804 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1807 * Link the chain into its parent. A spinlock is required to safely
1808 * access the RBTREE, and it is possible to collide with another
1809 * hammer2_chain_get() operation because the caller might only hold
1810 * a shared lock on the parent.
1812 * NOTE: Get races can occur quite often when we distribute
1813 * asynchronous read-aheads across multiple threads.
1815 KKASSERT(parent->refs > 0);
1816 error = hammer2_chain_insert(parent, chain,
1817 HAMMER2_CHAIN_INSERT_SPIN |
1818 HAMMER2_CHAIN_INSERT_RACE,
1821 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1822 /*kprintf("chain %p get race\n", chain);*/
1823 hammer2_chain_drop(chain);
1826 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1830 * Return our new chain referenced but not locked, or NULL if
1837 * Lookup initialization/completion API
1840 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1842 hammer2_chain_ref(parent);
1843 if (flags & HAMMER2_LOOKUP_SHARED) {
1844 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1845 HAMMER2_RESOLVE_SHARED);
1847 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1853 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1856 hammer2_chain_unlock(parent);
1857 hammer2_chain_drop(parent);
1862 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1864 hammer2_chain_t *oparent;
1865 hammer2_chain_t *nparent;
1868 * Be careful of order, oparent must be unlocked before nparent
1869 * is locked below to avoid a deadlock.
1872 hammer2_spin_ex(&oparent->core.spin);
1873 nparent = oparent->parent;
1874 hammer2_chain_ref(nparent);
1875 hammer2_spin_unex(&oparent->core.spin);
1877 hammer2_chain_unlock(oparent);
1878 hammer2_chain_drop(oparent);
1882 hammer2_chain_lock(nparent, how);
1889 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1890 * (*parentp) typically points to an inode but can also point to a related
1891 * indirect block and this function will recurse upwards and find the inode
1894 * (*parentp) must be exclusively locked and referenced and can be an inode
1895 * or an existing indirect block within the inode.
1897 * On return (*parentp) will be modified to point at the deepest parent chain
1898 * element encountered during the search, as a helper for an insertion or
1899 * deletion. The new (*parentp) will be locked and referenced and the old
1900 * will be unlocked and dereferenced (no change if they are both the same).
1902 * The matching chain will be returned exclusively locked. If NOLOCK is
1903 * requested the chain will be returned only referenced. Note that the
1904 * parent chain must always be locked shared or exclusive, matching the
1905 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1906 * when NOLOCK is specified but that complicates matters if *parentp must
1907 * inherit the chain.
1909 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1910 * data pointer or can otherwise be in flux.
1912 * NULL is returned if no match was found, but (*parentp) will still
1913 * potentially be adjusted.
1915 * If a fatal error occurs (typically an I/O error), a dummy chain is
1916 * returned with chain->error and error-identifying information set. This
1917 * chain will assert if you try to do anything fancy with it.
1919 * XXX Depending on where the error occurs we should allow continued iteration.
1921 * On return (*key_nextp) will point to an iterative value for key_beg.
1922 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1924 * This function will also recurse up the chain if the key is not within the
1925 * current parent's range. (*parentp) can never be set to NULL. An iteration
1926 * can simply allow (*parentp) to float inside the loop.
1928 * NOTE! chain->data is not always resolved. By default it will not be
1929 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1930 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1931 * BREF_TYPE_DATA as the device buffer can alias the logical file
1936 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1937 hammer2_key_t key_beg, hammer2_key_t key_end,
1938 int *cache_indexp, int flags)
1941 hammer2_chain_t *parent;
1942 hammer2_chain_t *chain;
1943 hammer2_blockref_t *base;
1944 hammer2_blockref_t *bref;
1945 hammer2_blockref_t bcopy;
1946 hammer2_key_t scan_beg;
1947 hammer2_key_t scan_end;
1949 int how_always = HAMMER2_RESOLVE_ALWAYS;
1950 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1953 int maxloops = 300000;
1957 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1958 how_maybe = how_always;
1959 how = HAMMER2_RESOLVE_ALWAYS;
1960 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1961 how = HAMMER2_RESOLVE_NEVER;
1963 how = HAMMER2_RESOLVE_MAYBE;
1965 if (flags & HAMMER2_LOOKUP_SHARED) {
1966 how_maybe |= HAMMER2_RESOLVE_SHARED;
1967 how_always |= HAMMER2_RESOLVE_SHARED;
1968 how |= HAMMER2_RESOLVE_SHARED;
1972 * Recurse (*parentp) upward if necessary until the parent completely
1973 * encloses the key range or we hit the inode.
1975 * This function handles races against the flusher doing a delete-
1976 * duplicate above us and re-homes the parent to the duplicate in
1977 * that case, otherwise we'd wind up recursing down a stale chain.
1982 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1983 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1984 scan_beg = parent->bref.key;
1985 scan_end = scan_beg +
1986 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1987 if (key_beg >= scan_beg && key_end <= scan_end)
1989 parent = hammer2_chain_getparent(parentp, how_maybe);
1994 if (--maxloops == 0)
1995 panic("hammer2_chain_lookup: maxloops");
1997 * Locate the blockref array. Currently we do a fully associative
1998 * search through the array.
2000 switch(parent->bref.type) {
2001 case HAMMER2_BREF_TYPE_INODE:
2003 * Special shortcut for embedded data returns the inode
2004 * itself. Callers must detect this condition and access
2005 * the embedded data (the strategy code does this for us).
2007 * This is only applicable to regular files and softlinks.
2009 if (parent->data->ipdata.meta.op_flags &
2010 HAMMER2_OPFLAG_DIRECTDATA) {
2011 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2013 *key_nextp = key_end + 1;
2016 hammer2_chain_ref(parent);
2017 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2018 hammer2_chain_lock(parent, how_always);
2019 *key_nextp = key_end + 1;
2022 base = &parent->data->ipdata.u.blockset.blockref[0];
2023 count = HAMMER2_SET_COUNT;
2025 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2026 case HAMMER2_BREF_TYPE_INDIRECT:
2028 * Handle MATCHIND on the parent
2030 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2031 scan_beg = parent->bref.key;
2032 scan_end = scan_beg +
2033 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2034 if (key_beg == scan_beg && key_end == scan_end) {
2036 hammer2_chain_ref(chain);
2037 hammer2_chain_lock(chain, how_maybe);
2038 *key_nextp = scan_end + 1;
2043 * Optimize indirect blocks in the INITIAL state to avoid
2046 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2049 if (parent->data == NULL) {
2050 kprintf("parent->data is NULL %p\n", parent);
2052 tsleep(parent, 0, "xxx", 0);
2054 base = &parent->data->npdata[0];
2056 count = parent->bytes / sizeof(hammer2_blockref_t);
2058 case HAMMER2_BREF_TYPE_VOLUME:
2059 base = &parent->data->voldata.sroot_blockset.blockref[0];
2060 count = HAMMER2_SET_COUNT;
2062 case HAMMER2_BREF_TYPE_FREEMAP:
2063 base = &parent->data->blkset.blockref[0];
2064 count = HAMMER2_SET_COUNT;
2067 kprintf("hammer2_chain_lookup: unrecognized "
2068 "blockref(B) type: %d",
2071 tsleep(&base, 0, "dead", 0);
2072 panic("hammer2_chain_lookup: unrecognized "
2073 "blockref(B) type: %d",
2075 base = NULL; /* safety */
2076 count = 0; /* safety */
2081 * Merged scan to find next candidate.
2083 * hammer2_base_*() functions require the parent->core.live_* fields
2084 * to be synchronized.
2086 * We need to hold the spinlock to access the block array and RB tree
2087 * and to interlock chain creation.
2089 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2090 hammer2_chain_countbrefs(parent, base, count);
2097 hammer2_spin_ex(&parent->core.spin);
2098 chain = hammer2_combined_find(parent, base, count,
2099 cache_indexp, key_nextp,
2102 generation = parent->core.generation;
2107 * Exhausted parent chain, iterate.
2111 hammer2_spin_unex(&parent->core.spin);
2112 if (key_beg == key_end) /* short cut single-key case */
2116 * Stop if we reached the end of the iteration.
2118 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2119 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2124 * Calculate next key, stop if we reached the end of the
2125 * iteration, otherwise go up one level and loop.
2127 key_beg = parent->bref.key +
2128 ((hammer2_key_t)1 << parent->bref.keybits);
2129 if (key_beg == 0 || key_beg > key_end)
2131 parent = hammer2_chain_getparent(parentp, how_maybe);
2136 * Selected from blockref or in-memory chain.
2138 if (chain == NULL) {
2141 hammer2_spin_unex(&parent->core.spin);
2142 chain = hammer2_chain_get(parent, generation,
2144 if (chain == NULL) {
2146 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2147 parent, key_beg, key_end);
2151 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2152 hammer2_chain_drop(chain);
2157 hammer2_chain_ref(chain);
2158 hammer2_spin_unex(&parent->core.spin);
2163 * chain is referenced but not locked. We must lock the chain
2164 * to obtain definitive DUPLICATED/DELETED state
2166 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2167 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2168 hammer2_chain_lock(chain, how_maybe);
2170 hammer2_chain_lock(chain, how);
2175 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2177 * NOTE: Chain's key range is not relevant as there might be
2178 * one-offs within the range that are not deleted.
2180 * NOTE: Lookups can race delete-duplicate because
2181 * delete-duplicate does not lock the parent's core
2182 * (they just use the spinlock on the core). We must
2183 * check for races by comparing the DUPLICATED flag before
2184 * releasing the spinlock with the flag after locking the
2187 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2188 hammer2_chain_unlock(chain);
2189 hammer2_chain_drop(chain);
2190 key_beg = *key_nextp;
2191 if (key_beg == 0 || key_beg > key_end)
2198 * If the chain element is an indirect block it becomes the new
2199 * parent and we loop on it. We must maintain our top-down locks
2200 * to prevent the flusher from interfering (i.e. doing a
2201 * delete-duplicate and leaving us recursing down a deleted chain).
2203 * The parent always has to be locked with at least RESOLVE_MAYBE
2204 * so we can access its data. It might need a fixup if the caller
2205 * passed incompatible flags. Be careful not to cause a deadlock
2206 * as a data-load requires an exclusive lock.
2208 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2209 * range is within the requested key range we return the indirect
2210 * block and do NOT loop. This is usually only used to acquire
2213 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2214 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2215 hammer2_chain_unlock(parent);
2216 hammer2_chain_drop(parent);
2217 *parentp = parent = chain;
2223 * All done, return the chain.
2225 * If the caller does not want a locked chain, replace the lock with
2226 * a ref. Perhaps this can eventually be optimized to not obtain the
2227 * lock in the first place for situations where the data does not
2228 * need to be resolved.
2231 if (flags & HAMMER2_LOOKUP_NOLOCK)
2232 hammer2_chain_unlock(chain);
2240 * After having issued a lookup we can iterate all matching keys.
2242 * If chain is non-NULL we continue the iteration from just after it's index.
2244 * If chain is NULL we assume the parent was exhausted and continue the
2245 * iteration at the next parent.
2247 * If a fatal error occurs (typically an I/O error), a dummy chain is
2248 * returned with chain->error and error-identifying information set. This
2249 * chain will assert if you try to do anything fancy with it.
2251 * XXX Depending on where the error occurs we should allow continued iteration.
2253 * parent must be locked on entry and remains locked throughout. chain's
2254 * lock status must match flags. Chain is always at least referenced.
2256 * WARNING! The MATCHIND flag does not apply to this function.
2259 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2260 hammer2_key_t *key_nextp,
2261 hammer2_key_t key_beg, hammer2_key_t key_end,
2262 int *cache_indexp, int flags)
2264 hammer2_chain_t *parent;
2268 * Calculate locking flags for upward recursion.
2270 how_maybe = HAMMER2_RESOLVE_MAYBE;
2271 if (flags & HAMMER2_LOOKUP_SHARED)
2272 how_maybe |= HAMMER2_RESOLVE_SHARED;
2277 * Calculate the next index and recalculate the parent if necessary.
2280 key_beg = chain->bref.key +
2281 ((hammer2_key_t)1 << chain->bref.keybits);
2282 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2283 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2284 hammer2_chain_unlock(chain);
2286 hammer2_chain_drop(chain);
2289 * chain invalid past this point, but we can still do a
2290 * pointer comparison w/parent.
2292 * Any scan where the lookup returned degenerate data embedded
2293 * in the inode has an invalid index and must terminate.
2295 if (chain == parent)
2297 if (key_beg == 0 || key_beg > key_end)
2300 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2301 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2303 * We reached the end of the iteration.
2308 * Continue iteration with next parent unless the current
2309 * parent covers the range.
2311 key_beg = parent->bref.key +
2312 ((hammer2_key_t)1 << parent->bref.keybits);
2313 if (key_beg == 0 || key_beg > key_end)
2315 parent = hammer2_chain_getparent(parentp, how_maybe);
2321 return (hammer2_chain_lookup(parentp, key_nextp,
2323 cache_indexp, flags));
2327 * The raw scan function is similar to lookup/next but does not seek to a key.
2328 * Blockrefs are iterated via first_bref = (parent, NULL) and
2329 * next_chain = (parent, bref).
2331 * The passed-in parent must be locked and its data resolved. The function
2332 * nominally returns a locked and referenced *chainp != NULL for chains
2333 * the caller might need to recurse on (and will dipose of any *chainp passed
2334 * in). The caller must check the chain->bref.type either way.
2336 * *chainp is not set for leaf elements.
2338 * This function takes a pointer to a stack-based bref structure whos
2339 * contents is updated for each iteration. The same pointer is returned,
2340 * or NULL when the iteration is complete. *firstp must be set to 1 for
2341 * the first ieration. This function will set it to 0.
2343 hammer2_blockref_t *
2344 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2345 hammer2_blockref_t *bref, int *firstp,
2346 int *cache_indexp, int flags)
2349 hammer2_blockref_t *base;
2350 hammer2_blockref_t *bref_ptr;
2352 hammer2_key_t next_key;
2353 hammer2_chain_t *chain = NULL;
2355 int how_always = HAMMER2_RESOLVE_ALWAYS;
2356 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2359 int maxloops = 300000;
2364 * Scan flags borrowed from lookup.
2366 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2367 how_maybe = how_always;
2368 how = HAMMER2_RESOLVE_ALWAYS;
2369 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2370 how = HAMMER2_RESOLVE_NEVER;
2372 how = HAMMER2_RESOLVE_MAYBE;
2374 if (flags & HAMMER2_LOOKUP_SHARED) {
2375 how_maybe |= HAMMER2_RESOLVE_SHARED;
2376 how_always |= HAMMER2_RESOLVE_SHARED;
2377 how |= HAMMER2_RESOLVE_SHARED;
2381 * Calculate key to locate first/next element, unlocking the previous
2382 * element as we go. Be careful, the key calculation can overflow.
2384 * (also reset bref to NULL)
2390 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2391 if ((chain = *chainp) != NULL) {
2393 hammer2_chain_unlock(chain);
2394 hammer2_chain_drop(chain);
2404 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2405 if (--maxloops == 0)
2406 panic("hammer2_chain_scan: maxloops");
2408 * Locate the blockref array. Currently we do a fully associative
2409 * search through the array.
2411 switch(parent->bref.type) {
2412 case HAMMER2_BREF_TYPE_INODE:
2414 * An inode with embedded data has no sub-chains.
2416 * WARNING! Bulk scan code may pass a static chain marked
2417 * as BREF_TYPE_INODE with a copy of the volume
2418 * root blockset to snapshot the volume.
2420 if (parent->data->ipdata.meta.op_flags &
2421 HAMMER2_OPFLAG_DIRECTDATA) {
2425 base = &parent->data->ipdata.u.blockset.blockref[0];
2426 count = HAMMER2_SET_COUNT;
2428 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2429 case HAMMER2_BREF_TYPE_INDIRECT:
2431 * Optimize indirect blocks in the INITIAL state to avoid
2434 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2437 if (parent->data == NULL)
2438 panic("parent->data is NULL");
2439 base = &parent->data->npdata[0];
2441 count = parent->bytes / sizeof(hammer2_blockref_t);
2443 case HAMMER2_BREF_TYPE_VOLUME:
2444 base = &parent->data->voldata.sroot_blockset.blockref[0];
2445 count = HAMMER2_SET_COUNT;
2447 case HAMMER2_BREF_TYPE_FREEMAP:
2448 base = &parent->data->blkset.blockref[0];
2449 count = HAMMER2_SET_COUNT;
2452 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2454 base = NULL; /* safety */
2455 count = 0; /* safety */
2459 * Merged scan to find next candidate.
2461 * hammer2_base_*() functions require the parent->core.live_* fields
2462 * to be synchronized.
2464 * We need to hold the spinlock to access the block array and RB tree
2465 * and to interlock chain creation.
2467 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2468 hammer2_chain_countbrefs(parent, base, count);
2472 hammer2_spin_ex(&parent->core.spin);
2473 chain = hammer2_combined_find(parent, base, count,
2474 cache_indexp, &next_key,
2475 key, HAMMER2_KEY_MAX,
2477 generation = parent->core.generation;
2480 * Exhausted parent chain, we're done.
2482 if (bref_ptr == NULL) {
2483 hammer2_spin_unex(&parent->core.spin);
2484 KKASSERT(chain == NULL);
2490 * Copy into the supplied stack-based blockref.
2495 * Selected from blockref or in-memory chain.
2497 if (chain == NULL) {
2498 switch(bref->type) {
2499 case HAMMER2_BREF_TYPE_INODE:
2500 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2501 case HAMMER2_BREF_TYPE_INDIRECT:
2502 case HAMMER2_BREF_TYPE_VOLUME:
2503 case HAMMER2_BREF_TYPE_FREEMAP:
2505 * Recursion, always get the chain
2507 hammer2_spin_unex(&parent->core.spin);
2508 chain = hammer2_chain_get(parent, generation, bref);
2509 if (chain == NULL) {
2510 kprintf("retry scan parent %p keys %016jx\n",
2514 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2515 hammer2_chain_drop(chain);
2522 * No recursion, do not waste time instantiating
2523 * a chain, just iterate using the bref.
2525 hammer2_spin_unex(&parent->core.spin);
2530 * Recursion or not we need the chain in order to supply
2533 hammer2_chain_ref(chain);
2534 hammer2_spin_unex(&parent->core.spin);
2538 * chain is referenced but not locked. We must lock the chain
2539 * to obtain definitive DUPLICATED/DELETED state
2542 hammer2_chain_lock(chain, how);
2545 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2547 * NOTE: chain's key range is not relevant as there might be
2548 * one-offs within the range that are not deleted.
2550 * NOTE: XXX this could create problems with scans used in
2551 * situations other than mount-time recovery.
2553 * NOTE: Lookups can race delete-duplicate because
2554 * delete-duplicate does not lock the parent's core
2555 * (they just use the spinlock on the core). We must
2556 * check for races by comparing the DUPLICATED flag before
2557 * releasing the spinlock with the flag after locking the
2560 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2561 hammer2_chain_unlock(chain);
2562 hammer2_chain_drop(chain);
2575 * All done, return the bref or NULL, supply chain if necessary.
2583 * Create and return a new hammer2 system memory structure of the specified
2584 * key, type and size and insert it under (*parentp). This is a full
2585 * insertion, based on the supplied key/keybits, and may involve creating
2586 * indirect blocks and moving other chains around via delete/duplicate.
2588 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2589 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2590 * FULL. This typically means that the caller is creating the chain after
2591 * doing a hammer2_chain_lookup().
2593 * (*parentp) must be exclusive locked and may be replaced on return
2594 * depending on how much work the function had to do.
2596 * (*parentp) must not be errored or this function will assert.
2598 * (*chainp) usually starts out NULL and returns the newly created chain,
2599 * but if the caller desires the caller may allocate a disconnected chain
2600 * and pass it in instead.
2602 * This function should NOT be used to insert INDIRECT blocks. It is
2603 * typically used to create/insert inodes and data blocks.
2605 * Caller must pass-in an exclusively locked parent the new chain is to
2606 * be inserted under, and optionally pass-in a disconnected, exclusively
2607 * locked chain to insert (else we create a new chain). The function will
2608 * adjust (*parentp) as necessary, create or connect the chain, and
2609 * return an exclusively locked chain in *chainp.
2611 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2612 * and will be reassigned.
2615 hammer2_chain_create(hammer2_chain_t **parentp,
2616 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2617 hammer2_key_t key, int keybits, int type, size_t bytes,
2618 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2621 hammer2_chain_t *chain;
2622 hammer2_chain_t *parent;
2623 hammer2_blockref_t *base;
2624 hammer2_blockref_t dummy;
2628 int maxloops = 300000;
2631 * Topology may be crossing a PFS boundary.
2634 KKASSERT(hammer2_mtx_owned(&parent->lock));
2635 KKASSERT(parent->error == 0);
2639 if (chain == NULL) {
2641 * First allocate media space and construct the dummy bref,
2642 * then allocate the in-memory chain structure. Set the
2643 * INITIAL flag for fresh chains which do not have embedded
2646 * XXX for now set the check mode of the child based on
2647 * the parent or, if the parent is an inode, the
2648 * specification in the inode.
2650 bzero(&dummy, sizeof(dummy));
2653 dummy.keybits = keybits;
2654 dummy.data_off = hammer2_getradix(bytes);
2655 dummy.methods = parent->bref.methods;
2656 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2658 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2659 dummy.methods |= HAMMER2_ENC_CHECK(
2660 parent->data->ipdata.meta.check_algo);
2663 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2666 * Lock the chain manually, chain_lock will load the chain
2667 * which we do NOT want to do. (note: chain->refs is set
2668 * to 1 by chain_alloc() for us, but lockcnt is not).
2671 hammer2_mtx_ex(&chain->lock);
2673 ++curthread->td_tracker;
2676 * Set INITIAL to optimize I/O. The flag will generally be
2677 * processed when we call hammer2_chain_modify().
2679 * Recalculate bytes to reflect the actual media block
2682 bytes = (hammer2_off_t)1 <<
2683 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2684 chain->bytes = bytes;
2687 case HAMMER2_BREF_TYPE_VOLUME:
2688 case HAMMER2_BREF_TYPE_FREEMAP:
2689 panic("hammer2_chain_create: called with volume type");
2691 case HAMMER2_BREF_TYPE_INDIRECT:
2692 panic("hammer2_chain_create: cannot be used to"
2693 "create indirect block");
2695 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2696 panic("hammer2_chain_create: cannot be used to"
2697 "create freemap root or node");
2699 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2700 KKASSERT(bytes == sizeof(chain->data->bmdata));
2702 case HAMMER2_BREF_TYPE_INODE:
2703 case HAMMER2_BREF_TYPE_DATA:
2706 * leave chain->data NULL, set INITIAL
2708 KKASSERT(chain->data == NULL);
2709 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2714 * We are reattaching a previously deleted chain, possibly
2715 * under a new parent and possibly with a new key/keybits.
2716 * The chain does not have to be in a modified state. The
2717 * UPDATE flag will be set later on in this routine.
2719 * Do NOT mess with the current state of the INITIAL flag.
2721 chain->bref.key = key;
2722 chain->bref.keybits = keybits;
2723 if (chain->flags & HAMMER2_CHAIN_DELETED)
2724 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2725 KKASSERT(chain->parent == NULL);
2727 if (flags & HAMMER2_INSERT_PFSROOT)
2728 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2730 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2733 * Calculate how many entries we have in the blockref array and
2734 * determine if an indirect block is required.
2737 if (--maxloops == 0)
2738 panic("hammer2_chain_create: maxloops");
2740 switch(parent->bref.type) {
2741 case HAMMER2_BREF_TYPE_INODE:
2742 if ((parent->data->ipdata.meta.op_flags &
2743 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2744 kprintf("hammer2: parent set for direct-data! "
2745 "pkey=%016jx ckey=%016jx\n",
2749 KKASSERT((parent->data->ipdata.meta.op_flags &
2750 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2751 KKASSERT(parent->data != NULL);
2752 base = &parent->data->ipdata.u.blockset.blockref[0];
2753 count = HAMMER2_SET_COUNT;
2755 case HAMMER2_BREF_TYPE_INDIRECT:
2756 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2757 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2760 base = &parent->data->npdata[0];
2761 count = parent->bytes / sizeof(hammer2_blockref_t);
2763 case HAMMER2_BREF_TYPE_VOLUME:
2764 KKASSERT(parent->data != NULL);
2765 base = &parent->data->voldata.sroot_blockset.blockref[0];
2766 count = HAMMER2_SET_COUNT;
2768 case HAMMER2_BREF_TYPE_FREEMAP:
2769 KKASSERT(parent->data != NULL);
2770 base = &parent->data->blkset.blockref[0];
2771 count = HAMMER2_SET_COUNT;
2774 panic("hammer2_chain_create: unrecognized blockref type: %d",
2782 * Make sure we've counted the brefs
2784 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2785 hammer2_chain_countbrefs(parent, base, count);
2787 KKASSERT(parent->core.live_count >= 0 &&
2788 parent->core.live_count <= count);
2791 * If no free blockref could be found we must create an indirect
2792 * block and move a number of blockrefs into it. With the parent
2793 * locked we can safely lock each child in order to delete+duplicate
2794 * it without causing a deadlock.
2796 * This may return the new indirect block or the old parent depending
2797 * on where the key falls. NULL is returned on error.
2799 if (parent->core.live_count == count) {
2800 hammer2_chain_t *nparent;
2802 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2803 mtid, type, &error);
2804 if (nparent == NULL) {
2806 hammer2_chain_drop(chain);
2810 if (parent != nparent) {
2811 hammer2_chain_unlock(parent);
2812 hammer2_chain_drop(parent);
2813 parent = *parentp = nparent;
2819 * Link the chain into its parent.
2821 if (chain->parent != NULL)
2822 panic("hammer2: hammer2_chain_create: chain already connected");
2823 KKASSERT(chain->parent == NULL);
2824 hammer2_chain_insert(parent, chain,
2825 HAMMER2_CHAIN_INSERT_SPIN |
2826 HAMMER2_CHAIN_INSERT_LIVE,
2831 * Mark the newly created chain modified. This will cause
2832 * UPDATE to be set and process the INITIAL flag.
2834 * Device buffers are not instantiated for DATA elements
2835 * as these are handled by logical buffers.
2837 * Indirect and freemap node indirect blocks are handled
2838 * by hammer2_chain_create_indirect() and not by this
2841 * Data for all other bref types is expected to be
2842 * instantiated (INODE, LEAF).
2844 switch(chain->bref.type) {
2845 case HAMMER2_BREF_TYPE_DATA:
2846 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2847 case HAMMER2_BREF_TYPE_INODE:
2848 hammer2_chain_modify(chain, mtid, dedup_off,
2849 HAMMER2_MODIFY_OPTDATA);
2853 * Remaining types are not supported by this function.
2854 * In particular, INDIRECT and LEAF_NODE types are
2855 * handled by create_indirect().
2857 panic("hammer2_chain_create: bad type: %d",
2864 * When reconnecting a chain we must set UPDATE and
2865 * setflush so the flush recognizes that it must update
2866 * the bref in the parent.
2868 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
2869 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2873 * We must setflush(parent) to ensure that it recurses through to
2874 * chain. setflush(chain) might not work because ONFLUSH is possibly
2875 * already set in the chain (so it won't recurse up to set it in the
2878 hammer2_chain_setflush(parent);
2887 * Move the chain from its old parent to a new parent. The chain must have
2888 * already been deleted or already disconnected (or never associated) with
2889 * a parent. The chain is reassociated with the new parent and the deleted
2890 * flag will be cleared (no longer deleted). The chain's modification state
2893 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2894 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2895 * FULL. This typically means that the caller is creating the chain after
2896 * doing a hammer2_chain_lookup().
2898 * A non-NULL bref is typically passed when key and keybits must be overridden.
2899 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2900 * from a passed-in bref and uses the old chain's bref for everything else.
2902 * Neither (parent) or (chain) can be errored.
2904 * If (parent) is non-NULL then the new duplicated chain is inserted under
2907 * If (parent) is NULL then the newly duplicated chain is not inserted
2908 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2909 * passing into hammer2_chain_create() after this function returns).
2911 * WARNING! This function calls create which means it can insert indirect
2912 * blocks. This can cause other unrelated chains in the parent to
2913 * be moved to a newly inserted indirect block in addition to the
2917 hammer2_chain_rename(hammer2_blockref_t *bref,
2918 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2919 hammer2_tid_t mtid, int flags)
2922 hammer2_chain_t *parent;
2926 * WARNING! We should never resolve DATA to device buffers
2927 * (XXX allow it if the caller did?), and since
2928 * we currently do not have the logical buffer cache
2929 * buffer in-hand to fix its cached physical offset
2930 * we also force the modify code to not COW it. XXX
2933 KKASSERT(chain->parent == NULL);
2934 KKASSERT(chain->error == 0);
2937 * Now create a duplicate of the chain structure, associating
2938 * it with the same core, making it the same size, pointing it
2939 * to the same bref (the same media block).
2942 bref = &chain->bref;
2943 bytes = (hammer2_off_t)1 <<
2944 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2947 * If parent is not NULL the duplicated chain will be entered under
2948 * the parent and the UPDATE bit set to tell flush to update
2951 * We must setflush(parent) to ensure that it recurses through to
2952 * chain. setflush(chain) might not work because ONFLUSH is possibly
2953 * already set in the chain (so it won't recurse up to set it in the
2956 * Having both chains locked is extremely important for atomicy.
2958 if (parentp && (parent = *parentp) != NULL) {
2959 KKASSERT(hammer2_mtx_owned(&parent->lock));
2960 KKASSERT(parent->refs > 0);
2961 KKASSERT(parent->error == 0);
2963 hammer2_chain_create(parentp, &chain, chain->pmp,
2964 bref->key, bref->keybits, bref->type,
2965 chain->bytes, mtid, 0, flags);
2966 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2967 hammer2_chain_setflush(*parentp);
2972 * Helper function for deleting chains.
2974 * The chain is removed from the live view (the RBTREE) as well as the parent's
2975 * blockmap. Both chain and its parent must be locked.
2977 * parent may not be errored. chain can be errored.
2980 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2981 hammer2_tid_t mtid, int flags)
2985 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2986 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2987 KKASSERT(chain->parent == parent);
2990 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2992 * Chain is blockmapped, so there must be a parent.
2993 * Atomically remove the chain from the parent and remove
2994 * the blockmap entry. The parent must be set modified
2995 * to remove the blockmap entry.
2997 hammer2_blockref_t *base;
3000 KKASSERT(parent != NULL);
3001 KKASSERT(parent->error == 0);
3002 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3003 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3006 * Calculate blockmap pointer
3008 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3009 hammer2_spin_ex(&parent->core.spin);
3011 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3012 atomic_add_int(&parent->core.live_count, -1);
3013 ++parent->core.generation;
3014 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3015 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3016 --parent->core.chain_count;
3017 chain->parent = NULL;
3019 switch(parent->bref.type) {
3020 case HAMMER2_BREF_TYPE_INODE:
3022 * Access the inode's block array. However, there
3023 * is no block array if the inode is flagged
3024 * DIRECTDATA. The DIRECTDATA case typicaly only
3025 * occurs when a hardlink has been shifted up the
3026 * tree and the original inode gets replaced with
3027 * an OBJTYPE_HARDLINK placeholding inode.
3030 (parent->data->ipdata.meta.op_flags &
3031 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3033 &parent->data->ipdata.u.blockset.blockref[0];
3037 count = HAMMER2_SET_COUNT;
3039 case HAMMER2_BREF_TYPE_INDIRECT:
3040 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3042 base = &parent->data->npdata[0];
3045 count = parent->bytes / sizeof(hammer2_blockref_t);
3047 case HAMMER2_BREF_TYPE_VOLUME:
3048 base = &parent->data->voldata.
3049 sroot_blockset.blockref[0];
3050 count = HAMMER2_SET_COUNT;
3052 case HAMMER2_BREF_TYPE_FREEMAP:
3053 base = &parent->data->blkset.blockref[0];
3054 count = HAMMER2_SET_COUNT;
3059 panic("hammer2_flush_pass2: "
3060 "unrecognized blockref type: %d",
3065 * delete blockmapped chain from its parent.
3067 * The parent is not affected by any statistics in chain
3068 * which are pending synchronization. That is, there is
3069 * nothing to undo in the parent since they have not yet
3070 * been incorporated into the parent.
3072 * The parent is affected by statistics stored in inodes.
3073 * Those have already been synchronized, so they must be
3074 * undone. XXX split update possible w/delete in middle?
3077 int cache_index = -1;
3078 hammer2_base_delete(parent, base, count,
3079 &cache_index, chain);
3081 hammer2_spin_unex(&parent->core.spin);
3082 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3084 * Chain is not blockmapped but a parent is present.
3085 * Atomically remove the chain from the parent. There is
3086 * no blockmap entry to remove.
3088 * Because chain was associated with a parent but not
3089 * synchronized, the chain's *_count_up fields contain
3090 * inode adjustment statistics which must be undone.
3092 hammer2_spin_ex(&parent->core.spin);
3093 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3094 atomic_add_int(&parent->core.live_count, -1);
3095 ++parent->core.generation;
3096 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3097 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3098 --parent->core.chain_count;
3099 chain->parent = NULL;
3100 hammer2_spin_unex(&parent->core.spin);
3103 * Chain is not blockmapped and has no parent. This
3104 * is a degenerate case.
3106 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3111 * Create an indirect block that covers one or more of the elements in the
3112 * current parent. Either returns the existing parent with no locking or
3113 * ref changes or returns the new indirect block locked and referenced
3114 * and leaving the original parent lock/ref intact as well.
3116 * If an error occurs, NULL is returned and *errorp is set to the error.
3118 * The returned chain depends on where the specified key falls.
3120 * The key/keybits for the indirect mode only needs to follow three rules:
3122 * (1) That all elements underneath it fit within its key space and
3124 * (2) That all elements outside it are outside its key space.
3126 * (3) When creating the new indirect block any elements in the current
3127 * parent that fit within the new indirect block's keyspace must be
3128 * moved into the new indirect block.
3130 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3131 * keyspace the the current parent, but lookup/iteration rules will
3132 * ensure (and must ensure) that rule (2) for all parents leading up
3133 * to the nearest inode or the root volume header is adhered to. This
3134 * is accomplished by always recursing through matching keyspaces in
3135 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3137 * The current implementation calculates the current worst-case keyspace by
3138 * iterating the current parent and then divides it into two halves, choosing
3139 * whichever half has the most elements (not necessarily the half containing
3140 * the requested key).
3142 * We can also opt to use the half with the least number of elements. This
3143 * causes lower-numbered keys (aka logical file offsets) to recurse through
3144 * fewer indirect blocks and higher-numbered keys to recurse through more.
3145 * This also has the risk of not moving enough elements to the new indirect
3146 * block and being forced to create several indirect blocks before the element
3149 * Must be called with an exclusively locked parent.
3151 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3152 hammer2_key_t *keyp, int keybits,
3153 hammer2_blockref_t *base, int count);
3154 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3155 hammer2_key_t *keyp, int keybits,
3156 hammer2_blockref_t *base, int count);
3159 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3160 hammer2_key_t create_key, int create_bits,
3161 hammer2_tid_t mtid, int for_type, int *errorp)
3164 hammer2_blockref_t *base;
3165 hammer2_blockref_t *bref;
3166 hammer2_blockref_t bcopy;
3167 hammer2_chain_t *chain;
3168 hammer2_chain_t *ichain;
3169 hammer2_chain_t dummy;
3170 hammer2_key_t key = create_key;
3171 hammer2_key_t key_beg;
3172 hammer2_key_t key_end;
3173 hammer2_key_t key_next;
3174 int keybits = create_bits;
3181 int maxloops = 300000;
3184 * Calculate the base blockref pointer or NULL if the chain
3185 * is known to be empty. We need to calculate the array count
3186 * for RB lookups either way.
3190 KKASSERT(hammer2_mtx_owned(&parent->lock));
3192 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3193 base = hammer2_chain_base_and_count(parent, &count);
3196 * dummy used in later chain allocation (no longer used for lookups).
3198 bzero(&dummy, sizeof(dummy));
3201 * When creating an indirect block for a freemap node or leaf
3202 * the key/keybits must be fitted to static radix levels because
3203 * particular radix levels use particular reserved blocks in the
3206 * This routine calculates the key/radix of the indirect block
3207 * we need to create, and whether it is on the high-side or the
3210 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3211 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3212 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3215 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3220 * Normalize the key for the radix being represented, keeping the
3221 * high bits and throwing away the low bits.
3223 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3226 * How big should our new indirect block be? It has to be at least
3227 * as large as its parent.
3229 * The freemap uses a specific indirect block size.
3231 * The first indirect block level down from an inode typically
3232 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3234 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3235 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3236 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3237 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3238 nbytes = HAMMER2_IND_BYTES_MIN;
3240 nbytes = HAMMER2_IND_BYTES_MAX;
3242 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3243 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3244 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3245 nbytes = count * sizeof(hammer2_blockref_t);
3249 * Ok, create our new indirect block
3251 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3252 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3253 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3255 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3257 dummy.bref.key = key;
3258 dummy.bref.keybits = keybits;
3259 dummy.bref.data_off = hammer2_getradix(nbytes);
3260 dummy.bref.methods = parent->bref.methods;
3262 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3263 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3264 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3265 /* ichain has one ref at this point */
3268 * We have to mark it modified to allocate its block, but use
3269 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3270 * it won't be acted upon by the flush code.
3272 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3275 * Iterate the original parent and move the matching brefs into
3276 * the new indirect block.
3278 * XXX handle flushes.
3281 key_end = HAMMER2_KEY_MAX;
3283 hammer2_spin_ex(&parent->core.spin);
3289 * Parent may have been modified, relocating its block array.
3290 * Reload the base pointer.
3292 base = hammer2_chain_base_and_count(parent, &count);
3294 if (++loops > 100000) {
3295 hammer2_spin_unex(&parent->core.spin);
3296 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3297 reason, parent, base, count, key_next);
3301 * NOTE: spinlock stays intact, returned chain (if not NULL)
3302 * is not referenced or locked which means that we
3303 * cannot safely check its flagged / deletion status
3306 chain = hammer2_combined_find(parent, base, count,
3307 &cache_index, &key_next,
3310 generation = parent->core.generation;
3313 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3316 * Skip keys that are not within the key/radix of the new
3317 * indirect block. They stay in the parent.
3319 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3320 (key ^ bref->key)) != 0) {
3321 goto next_key_spinlocked;
3325 * Load the new indirect block by acquiring the related
3326 * chains (potentially from media as it might not be
3327 * in-memory). Then move it to the new parent (ichain)
3328 * via DELETE-DUPLICATE.
3330 * chain is referenced but not locked. We must lock the
3331 * chain to obtain definitive DUPLICATED/DELETED state
3335 * Use chain already present in the RBTREE
3337 hammer2_chain_ref(chain);
3338 hammer2_spin_unex(&parent->core.spin);
3339 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3342 * Get chain for blockref element. _get returns NULL
3343 * on insertion race.
3346 hammer2_spin_unex(&parent->core.spin);
3347 chain = hammer2_chain_get(parent, generation, &bcopy);
3348 if (chain == NULL) {
3350 hammer2_spin_ex(&parent->core.spin);
3353 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3354 kprintf("REASON 2\n");
3356 hammer2_chain_drop(chain);
3357 hammer2_spin_ex(&parent->core.spin);
3360 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3364 * This is always live so if the chain has been deleted
3365 * we raced someone and we have to retry.
3367 * NOTE: Lookups can race delete-duplicate because
3368 * delete-duplicate does not lock the parent's core
3369 * (they just use the spinlock on the core). We must
3370 * check for races by comparing the DUPLICATED flag before
3371 * releasing the spinlock with the flag after locking the
3374 * (note reversed logic for this one)
3376 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3377 hammer2_chain_unlock(chain);
3378 hammer2_chain_drop(chain);
3383 * Shift the chain to the indirect block.
3385 * WARNING! No reason for us to load chain data, pass NOSTATS
3386 * to prevent delete/insert from trying to access
3387 * inode stats (and thus asserting if there is no
3388 * chain->data loaded).
3390 * WARNING! The (parent, chain) deletion may modify the parent
3391 * and invalidate the base pointer.
3393 hammer2_chain_delete(parent, chain, mtid, 0);
3394 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3395 hammer2_chain_unlock(chain);
3396 hammer2_chain_drop(chain);
3397 KKASSERT(parent->refs > 0);
3399 base = NULL; /* safety */
3401 hammer2_spin_ex(&parent->core.spin);
3402 next_key_spinlocked:
3403 if (--maxloops == 0)
3404 panic("hammer2_chain_create_indirect: maxloops");
3406 if (key_next == 0 || key_next > key_end)
3411 hammer2_spin_unex(&parent->core.spin);
3414 * Insert the new indirect block into the parent now that we've
3415 * cleared out some entries in the parent. We calculated a good
3416 * insertion index in the loop above (ichain->index).
3418 * We don't have to set UPDATE here because we mark ichain
3419 * modified down below (so the normal modified -> flush -> set-moved
3420 * sequence applies).
3422 * The insertion shouldn't race as this is a completely new block
3423 * and the parent is locked.
3425 base = NULL; /* safety, parent modify may change address */
3426 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3427 hammer2_chain_insert(parent, ichain,
3428 HAMMER2_CHAIN_INSERT_SPIN |
3429 HAMMER2_CHAIN_INSERT_LIVE,
3433 * Make sure flushes propogate after our manual insertion.
3435 hammer2_chain_setflush(ichain);
3436 hammer2_chain_setflush(parent);
3439 * Figure out what to return.
3441 if (~(((hammer2_key_t)1 << keybits) - 1) &
3442 (create_key ^ key)) {
3444 * Key being created is outside the key range,
3445 * return the original parent.
3447 hammer2_chain_unlock(ichain);
3448 hammer2_chain_drop(ichain);
3451 * Otherwise its in the range, return the new parent.
3452 * (leave both the new and old parent locked).
3461 * Calculate the keybits and highside/lowside of the freemap node the
3462 * caller is creating.
3464 * This routine will specify the next higher-level freemap key/radix
3465 * representing the lowest-ordered set. By doing so, eventually all
3466 * low-ordered sets will be moved one level down.
3468 * We have to be careful here because the freemap reserves a limited
3469 * number of blocks for a limited number of levels. So we can't just
3470 * push indiscriminately.
3473 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3474 int keybits, hammer2_blockref_t *base, int count)
3476 hammer2_chain_t *chain;
3477 hammer2_blockref_t *bref;
3479 hammer2_key_t key_beg;
3480 hammer2_key_t key_end;
3481 hammer2_key_t key_next;
3485 int maxloops = 300000;
3493 * Calculate the range of keys in the array being careful to skip
3494 * slots which are overridden with a deletion.
3497 key_end = HAMMER2_KEY_MAX;
3499 hammer2_spin_ex(&parent->core.spin);
3502 if (--maxloops == 0) {
3503 panic("indkey_freemap shit %p %p:%d\n",
3504 parent, base, count);
3506 chain = hammer2_combined_find(parent, base, count,
3507 &cache_index, &key_next,
3518 * Skip deleted chains.
3520 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3521 if (key_next == 0 || key_next > key_end)
3528 * Use the full live (not deleted) element for the scan
3529 * iteration. HAMMER2 does not allow partial replacements.
3531 * XXX should be built into hammer2_combined_find().
3533 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3535 if (keybits > bref->keybits) {
3537 keybits = bref->keybits;
3538 } else if (keybits == bref->keybits && bref->key < key) {
3545 hammer2_spin_unex(&parent->core.spin);
3548 * Return the keybits for a higher-level FREEMAP_NODE covering
3552 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3553 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3555 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3556 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3558 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3559 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3561 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3562 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3564 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3565 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3567 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3568 panic("hammer2_chain_indkey_freemap: level too high");
3571 panic("hammer2_chain_indkey_freemap: bad radix");
3580 * Calculate the keybits and highside/lowside of the indirect block the
3581 * caller is creating.
3584 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3585 int keybits, hammer2_blockref_t *base, int count)
3587 hammer2_blockref_t *bref;
3588 hammer2_chain_t *chain;
3589 hammer2_key_t key_beg;
3590 hammer2_key_t key_end;
3591 hammer2_key_t key_next;
3597 int maxloops = 300000;
3604 * Calculate the range of keys in the array being careful to skip
3605 * slots which are overridden with a deletion. Once the scan
3606 * completes we will cut the key range in half and shift half the
3607 * range into the new indirect block.
3610 key_end = HAMMER2_KEY_MAX;
3612 hammer2_spin_ex(&parent->core.spin);
3615 if (--maxloops == 0) {
3616 panic("indkey_freemap shit %p %p:%d\n",
3617 parent, base, count);
3619 chain = hammer2_combined_find(parent, base, count,
3620 &cache_index, &key_next,
3631 * NOTE: No need to check DUPLICATED here because we do
3632 * not release the spinlock.
3634 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3635 if (key_next == 0 || key_next > key_end)
3642 * Use the full live (not deleted) element for the scan
3643 * iteration. HAMMER2 does not allow partial replacements.
3645 * XXX should be built into hammer2_combined_find().
3647 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3650 * Expand our calculated key range (key, keybits) to fit
3651 * the scanned key. nkeybits represents the full range
3652 * that we will later cut in half (two halves @ nkeybits - 1).
3655 if (nkeybits < bref->keybits) {
3656 if (bref->keybits > 64) {
3657 kprintf("bad bref chain %p bref %p\n",
3661 nkeybits = bref->keybits;
3663 while (nkeybits < 64 &&
3664 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3665 (key ^ bref->key)) != 0) {
3670 * If the new key range is larger we have to determine
3671 * which side of the new key range the existing keys fall
3672 * under by checking the high bit, then collapsing the
3673 * locount into the hicount or vise-versa.
3675 if (keybits != nkeybits) {
3676 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3687 * The newly scanned key will be in the lower half or the
3688 * upper half of the (new) key range.
3690 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3699 hammer2_spin_unex(&parent->core.spin);
3700 bref = NULL; /* now invalid (safety) */
3703 * Adjust keybits to represent half of the full range calculated
3704 * above (radix 63 max)
3709 * Select whichever half contains the most elements. Theoretically
3710 * we can select either side as long as it contains at least one
3711 * element (in order to ensure that a free slot is present to hold
3712 * the indirect block).
3714 if (hammer2_indirect_optimize) {
3716 * Insert node for least number of keys, this will arrange
3717 * the first few blocks of a large file or the first few
3718 * inodes in a directory with fewer indirect blocks when
3721 if (hicount < locount && hicount != 0)
3722 key |= (hammer2_key_t)1 << keybits;
3724 key &= ~(hammer2_key_t)1 << keybits;
3727 * Insert node for most number of keys, best for heavily
3730 if (hicount > locount)
3731 key |= (hammer2_key_t)1 << keybits;
3733 key &= ~(hammer2_key_t)1 << keybits;
3741 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3744 * Both parent and chain must be locked exclusively.
3746 * This function will modify the parent if the blockref requires removal
3747 * from the parent's block table.
3749 * This function is NOT recursive. Any entity already pushed into the
3750 * chain (such as an inode) may still need visibility into its contents,
3751 * as well as the ability to read and modify the contents. For example,
3752 * for an unlinked file which is still open.
3755 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3756 hammer2_tid_t mtid, int flags)
3758 KKASSERT(hammer2_mtx_owned(&chain->lock));
3761 * Nothing to do if already marked.
3763 * We need the spinlock on the core whos RBTREE contains chain
3764 * to protect against races.
3766 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3767 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3768 chain->parent == parent);
3769 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3773 * Permanent deletions mark the chain as destroyed.
3775 if (flags & HAMMER2_DELETE_PERMANENT) {
3776 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3778 /* XXX might not be needed */
3779 hammer2_chain_setflush(chain);
3784 * Returns the index of the nearest element in the blockref array >= elm.
3785 * Returns (count) if no element could be found.
3787 * Sets *key_nextp to the next key for loop purposes but does not modify
3788 * it if the next key would be higher than the current value of *key_nextp.
3789 * Note that *key_nexp can overflow to 0, which should be tested by the
3792 * (*cache_indexp) is a heuristic and can be any value without effecting
3795 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3796 * held through the operation.
3799 hammer2_base_find(hammer2_chain_t *parent,
3800 hammer2_blockref_t *base, int count,
3801 int *cache_indexp, hammer2_key_t *key_nextp,
3802 hammer2_key_t key_beg, hammer2_key_t key_end)
3804 hammer2_blockref_t *scan;
3805 hammer2_key_t scan_end;
3810 * Require the live chain's already have their core's counted
3811 * so we can optimize operations.
3813 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3818 if (count == 0 || base == NULL)
3822 * Sequential optimization using *cache_indexp. This is the most
3825 * We can avoid trailing empty entries on live chains, otherwise
3826 * we might have to check the whole block array.
3830 limit = parent->core.live_zero;
3835 KKASSERT(i < count);
3841 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3848 * Search forwards, stop when we find a scan element which
3849 * encloses the key or until we know that there are no further
3853 if (scan->type != 0) {
3854 scan_end = scan->key +
3855 ((hammer2_key_t)1 << scan->keybits) - 1;
3856 if (scan->key > key_beg || scan_end >= key_beg)
3869 scan_end = scan->key +
3870 ((hammer2_key_t)1 << scan->keybits);
3871 if (scan_end && (*key_nextp > scan_end ||
3873 *key_nextp = scan_end;
3881 * Do a combined search and return the next match either from the blockref
3882 * array or from the in-memory chain. Sets *bresp to the returned bref in
3883 * both cases, or sets it to NULL if the search exhausted. Only returns
3884 * a non-NULL chain if the search matched from the in-memory chain.
3886 * When no in-memory chain has been found and a non-NULL bref is returned
3890 * The returned chain is not locked or referenced. Use the returned bref
3891 * to determine if the search exhausted or not. Iterate if the base find
3892 * is chosen but matches a deleted chain.
3894 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3895 * held through the operation.
3897 static hammer2_chain_t *
3898 hammer2_combined_find(hammer2_chain_t *parent,
3899 hammer2_blockref_t *base, int count,
3900 int *cache_indexp, hammer2_key_t *key_nextp,
3901 hammer2_key_t key_beg, hammer2_key_t key_end,
3902 hammer2_blockref_t **bresp)
3904 hammer2_blockref_t *bref;
3905 hammer2_chain_t *chain;
3909 * Lookup in block array and in rbtree.
3911 *key_nextp = key_end + 1;
3912 i = hammer2_base_find(parent, base, count, cache_indexp,
3913 key_nextp, key_beg, key_end);
3914 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3919 if (i == count && chain == NULL) {
3925 * Only chain matched.
3928 bref = &chain->bref;
3933 * Only blockref matched.
3935 if (chain == NULL) {
3941 * Both in-memory and blockref matched, select the nearer element.
3943 * If both are flush with the left-hand side or both are the
3944 * same distance away, select the chain. In this situation the
3945 * chain must have been loaded from the matching blockmap.
3947 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3948 chain->bref.key == base[i].key) {
3949 KKASSERT(chain->bref.key == base[i].key);
3950 bref = &chain->bref;
3955 * Select the nearer key
3957 if (chain->bref.key < base[i].key) {
3958 bref = &chain->bref;
3965 * If the bref is out of bounds we've exhausted our search.
3968 if (bref->key > key_end) {
3978 * Locate the specified block array element and delete it. The element
3981 * The spin lock on the related chain must be held.
3983 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3984 * need to be adjusted when we commit the media change.
3987 hammer2_base_delete(hammer2_chain_t *parent,
3988 hammer2_blockref_t *base, int count,
3989 int *cache_indexp, hammer2_chain_t *chain)
3991 hammer2_blockref_t *elm = &chain->bref;
3992 hammer2_key_t key_next;
3996 * Delete element. Expect the element to exist.
3998 * XXX see caller, flush code not yet sophisticated enough to prevent
3999 * re-flushed in some cases.
4001 key_next = 0; /* max range */
4002 i = hammer2_base_find(parent, base, count, cache_indexp,
4003 &key_next, elm->key, elm->key);
4004 if (i == count || base[i].type == 0 ||
4005 base[i].key != elm->key ||
4006 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4007 base[i].keybits != elm->keybits)) {
4008 hammer2_spin_unex(&parent->core.spin);
4009 panic("delete base %p element not found at %d/%d elm %p\n",
4010 base, i, count, elm);
4015 * Update stats and zero the entry
4017 parent->bref.data_count -= base[i].data_count;
4018 parent->bref.data_count -= (hammer2_off_t)1 <<
4019 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
4020 parent->bref.inode_count -= base[i].inode_count;
4021 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
4022 parent->bref.inode_count -= 1;
4024 bzero(&base[i], sizeof(*base));
4027 * We can only optimize parent->core.live_zero for live chains.
4029 if (parent->core.live_zero == i + 1) {
4030 while (--i >= 0 && base[i].type == 0)
4032 parent->core.live_zero = i + 1;
4036 * Clear appropriate blockmap flags in chain.
4038 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4039 HAMMER2_CHAIN_BMAPUPD);
4043 * Insert the specified element. The block array must not already have the
4044 * element and must have space available for the insertion.
4046 * The spin lock on the related chain must be held.
4048 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4049 * need to be adjusted when we commit the media change.
4052 hammer2_base_insert(hammer2_chain_t *parent,
4053 hammer2_blockref_t *base, int count,
4054 int *cache_indexp, hammer2_chain_t *chain)
4056 hammer2_blockref_t *elm = &chain->bref;
4057 hammer2_key_t key_next;
4066 * Insert new element. Expect the element to not already exist
4067 * unless we are replacing it.
4069 * XXX see caller, flush code not yet sophisticated enough to prevent
4070 * re-flushed in some cases.
4072 key_next = 0; /* max range */
4073 i = hammer2_base_find(parent, base, count, cache_indexp,
4074 &key_next, elm->key, elm->key);
4077 * Shortcut fill optimization, typical ordered insertion(s) may not
4080 KKASSERT(i >= 0 && i <= count);
4083 * Set appropriate blockmap flags in chain.
4085 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4088 * Update stats and zero the entry
4090 parent->bref.data_count += elm->data_count;
4091 parent->bref.data_count += (hammer2_off_t)1 <<
4092 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4093 parent->bref.inode_count += elm->inode_count;
4094 if (elm->type == HAMMER2_BREF_TYPE_INODE)
4095 parent->bref.inode_count += 1;
4099 * We can only optimize parent->core.live_zero for live chains.
4101 if (i == count && parent->core.live_zero < count) {
4102 i = parent->core.live_zero++;
4107 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4108 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4109 hammer2_spin_unex(&parent->core.spin);
4110 panic("insert base %p overlapping elements at %d elm %p\n",
4115 * Try to find an empty slot before or after.
4119 while (j > 0 || k < count) {
4121 if (j >= 0 && base[j].type == 0) {
4125 bcopy(&base[j+1], &base[j],
4126 (i - j - 1) * sizeof(*base));
4132 if (k < count && base[k].type == 0) {
4133 bcopy(&base[i], &base[i+1],
4134 (k - i) * sizeof(hammer2_blockref_t));
4138 * We can only update parent->core.live_zero for live
4141 if (parent->core.live_zero <= k)
4142 parent->core.live_zero = k + 1;
4147 panic("hammer2_base_insert: no room!");
4154 for (l = 0; l < count; ++l) {
4156 key_next = base[l].key +
4157 ((hammer2_key_t)1 << base[l].keybits) - 1;
4161 while (++l < count) {
4163 if (base[l].key <= key_next)
4164 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4165 key_next = base[l].key +
4166 ((hammer2_key_t)1 << base[l].keybits) - 1;
4176 * Sort the blockref array for the chain. Used by the flush code to
4177 * sort the blockref[] array.
4179 * The chain must be exclusively locked AND spin-locked.
4181 typedef hammer2_blockref_t *hammer2_blockref_p;
4185 hammer2_base_sort_callback(const void *v1, const void *v2)
4187 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4188 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4191 * Make sure empty elements are placed at the end of the array
4193 if (bref1->type == 0) {
4194 if (bref2->type == 0)
4197 } else if (bref2->type == 0) {
4204 if (bref1->key < bref2->key)
4206 if (bref1->key > bref2->key)
4212 hammer2_base_sort(hammer2_chain_t *chain)
4214 hammer2_blockref_t *base;
4217 switch(chain->bref.type) {
4218 case HAMMER2_BREF_TYPE_INODE:
4220 * Special shortcut for embedded data returns the inode
4221 * itself. Callers must detect this condition and access
4222 * the embedded data (the strategy code does this for us).
4224 * This is only applicable to regular files and softlinks.
4226 if (chain->data->ipdata.meta.op_flags &
4227 HAMMER2_OPFLAG_DIRECTDATA) {
4230 base = &chain->data->ipdata.u.blockset.blockref[0];
4231 count = HAMMER2_SET_COUNT;
4233 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4234 case HAMMER2_BREF_TYPE_INDIRECT:
4236 * Optimize indirect blocks in the INITIAL state to avoid
4239 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4240 base = &chain->data->npdata[0];
4241 count = chain->bytes / sizeof(hammer2_blockref_t);
4243 case HAMMER2_BREF_TYPE_VOLUME:
4244 base = &chain->data->voldata.sroot_blockset.blockref[0];
4245 count = HAMMER2_SET_COUNT;
4247 case HAMMER2_BREF_TYPE_FREEMAP:
4248 base = &chain->data->blkset.blockref[0];
4249 count = HAMMER2_SET_COUNT;
4252 kprintf("hammer2_chain_lookup: unrecognized "
4253 "blockref(A) type: %d",
4256 tsleep(&base, 0, "dead", 0);
4257 panic("hammer2_chain_lookup: unrecognized "
4258 "blockref(A) type: %d",
4260 base = NULL; /* safety */
4261 count = 0; /* safety */
4263 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4269 * Chain memory management
4272 hammer2_chain_wait(hammer2_chain_t *chain)
4274 tsleep(chain, 0, "chnflw", 1);
4277 const hammer2_media_data_t *
4278 hammer2_chain_rdata(hammer2_chain_t *chain)
4280 KKASSERT(chain->data != NULL);
4281 return (chain->data);
4284 hammer2_media_data_t *
4285 hammer2_chain_wdata(hammer2_chain_t *chain)
4287 KKASSERT(chain->data != NULL);
4288 return (chain->data);
4292 * Set the check data for a chain. This can be a heavy-weight operation
4293 * and typically only runs on-flush. For file data check data is calculated
4294 * when the logical buffers are flushed.
4297 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4299 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4301 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4302 case HAMMER2_CHECK_NONE:
4304 case HAMMER2_CHECK_DISABLED:
4306 case HAMMER2_CHECK_ISCSI32:
4307 chain->bref.check.iscsi32.value =
4308 hammer2_icrc32(bdata, chain->bytes);
4310 case HAMMER2_CHECK_XXHASH64:
4311 chain->bref.check.xxhash64.value =
4312 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4314 case HAMMER2_CHECK_SHA192:
4316 SHA256_CTX hash_ctx;
4318 uint8_t digest[SHA256_DIGEST_LENGTH];
4319 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4322 SHA256_Init(&hash_ctx);
4323 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4324 SHA256_Final(u.digest, &hash_ctx);
4325 u.digest64[2] ^= u.digest64[3];
4327 chain->bref.check.sha192.data,
4328 sizeof(chain->bref.check.sha192.data));
4331 case HAMMER2_CHECK_FREEMAP:
4332 chain->bref.check.freemap.icrc32 =
4333 hammer2_icrc32(bdata, chain->bytes);
4336 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4337 chain->bref.methods);
4343 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4347 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4350 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4351 case HAMMER2_CHECK_NONE:
4354 case HAMMER2_CHECK_DISABLED:
4357 case HAMMER2_CHECK_ISCSI32:
4358 r = (chain->bref.check.iscsi32.value ==
4359 hammer2_icrc32(bdata, chain->bytes));
4360 hammer2_check_icrc32 += chain->bytes;
4362 case HAMMER2_CHECK_XXHASH64:
4363 r = (chain->bref.check.xxhash64.value ==
4364 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED));
4365 hammer2_check_xxhash64 += chain->bytes;
4367 case HAMMER2_CHECK_SHA192:
4369 SHA256_CTX hash_ctx;
4371 uint8_t digest[SHA256_DIGEST_LENGTH];
4372 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4375 SHA256_Init(&hash_ctx);
4376 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4377 SHA256_Final(u.digest, &hash_ctx);
4378 u.digest64[2] ^= u.digest64[3];
4380 chain->bref.check.sha192.data,
4381 sizeof(chain->bref.check.sha192.data)) == 0) {
4388 case HAMMER2_CHECK_FREEMAP:
4389 r = (chain->bref.check.freemap.icrc32 ==
4390 hammer2_icrc32(bdata, chain->bytes));
4392 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4393 chain->bref.check.freemap.icrc32,
4394 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4396 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4397 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4402 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4403 chain->bref.methods);
4411 * The caller presents a shared-locked (parent, chain) where the chain
4412 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4413 * structure representing the inode locked to prevent
4414 * consolidation/deconsolidation races.
4416 * The flags passed in are LOOKUP flags, not RESOLVE flags. Only
4417 * HAMMER2_LOOKUP_SHARED is supported.
4419 * We locate the hardlink in the current or a common parent directory.
4421 * If we are unable to locate the hardlink, EIO is returned and
4422 * (*chainp) is unlocked and dropped.
4425 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4426 hammer2_chain_t **parentp,
4427 hammer2_chain_t **chainp,
4430 hammer2_chain_t *parent;
4431 hammer2_chain_t *rchain;
4432 hammer2_key_t key_dummy;
4434 int cache_index = -1;
4437 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
4438 HAMMER2_RESOLVE_SHARED : 0;
4441 * Obtain the key for the hardlink from *chainp.
4444 lhc = rchain->data->ipdata.meta.inum;
4445 hammer2_chain_unlock(rchain);
4446 hammer2_chain_drop(rchain);
4452 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4454 &cache_index, flags);
4459 * Iterate parents, handle parent rename races by retrying
4465 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4470 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4473 if (parent->parent == NULL)
4475 parent = parent->parent;
4476 hammer2_chain_ref(parent);
4477 hammer2_chain_unlock(*parentp);
4478 hammer2_chain_lock(parent,
4479 HAMMER2_RESOLVE_ALWAYS |
4481 if ((*parentp)->parent == parent) {
4482 hammer2_chain_drop(*parentp);
4486 hammer2_chain_unlock(parent);
4487 hammer2_chain_drop(parent);
4488 hammer2_chain_lock(*parentp,
4489 HAMMER2_RESOLVE_ALWAYS |
4498 return (rchain ? 0 : EINVAL);
4502 * Used by the bulkscan code to snapshot the synchronized storage for
4503 * a volume, allowing it to be scanned concurrently against normal
4507 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4509 hammer2_chain_t *copy;
4511 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4512 switch(chain->bref.type) {
4513 case HAMMER2_BREF_TYPE_VOLUME:
4514 copy->data = kmalloc(sizeof(copy->data->voldata),
4517 hammer2_spin_ex(&chain->core.spin);
4518 copy->data->voldata = chain->data->voldata;
4519 hammer2_spin_unex(&chain->core.spin);
4521 case HAMMER2_BREF_TYPE_FREEMAP:
4522 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4525 hammer2_spin_ex(&chain->core.spin);
4526 copy->data->blkset = chain->data->blkset;
4527 hammer2_spin_unex(&chain->core.spin);
4536 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4538 switch(copy->bref.type) {
4539 case HAMMER2_BREF_TYPE_VOLUME:
4540 case HAMMER2_BREF_TYPE_FREEMAP:
4541 KKASSERT(copy->data);
4542 kfree(copy->data, copy->hmp->mchain);
4544 atomic_add_long(&hammer2_chain_allocs, -1);
4549 hammer2_chain_drop(copy);
4553 * Create a snapshot of the specified {parent, ochain} with the specified
4554 * label. The originating hammer2_inode must be exclusively locked for
4557 * The ioctl code has already synced the filesystem.
4560 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4564 const hammer2_inode_data_t *ripdata;
4565 hammer2_inode_data_t *wipdata;
4566 hammer2_chain_t *nchain;
4567 hammer2_inode_t *nip;
4576 kprintf("snapshot %s\n", pmp->name);
4578 name_len = strlen(pmp->name);
4579 lhc = hammer2_dirhash(pmp->name, name_len);
4584 ripdata = &chain->data->ipdata;
4586 opfs_clid = ripdata->meta.pfs_clid;
4591 * Create the snapshot directory under the super-root
4593 * Set PFS type, generate a unique filesystem id, and generate
4594 * a cluster id. Use the same clid when snapshotting a PFS root,
4595 * which theoretically allows the snapshot to be used as part of
4596 * the same cluster (perhaps as a cache).
4598 * Copy the (flushed) blockref array. Theoretically we could use
4599 * chain_duplicate() but it becomes difficult to disentangle
4600 * the shared core so for now just brute-force it.
4605 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4606 pmp->name, name_len, 0,
4608 HAMMER2_INSERT_PFSROOT, &error);
4611 hammer2_inode_modify(nip);
4612 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4613 hammer2_chain_modify(nchain, mtid, 0, 0);
4614 wipdata = &nchain->data->ipdata;
4616 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4617 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4618 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4619 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4622 * Give the snapshot its own private cluster id. As a
4623 * snapshot no further synchronization with the original
4624 * cluster will be done.
4627 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4628 nip->meta.pfs_clid = opfs_clid;
4630 kern_uuidgen(&nip->meta.pfs_clid, 1);
4632 kern_uuidgen(&nip->meta.pfs_clid, 1);
4633 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4635 /* XXX hack blockset copy */
4636 /* XXX doesn't work with real cluster */
4637 wipdata->meta = nip->meta;
4638 wipdata->u.blockset = ripdata->u.blockset;
4639 hammer2_flush(nchain, 1);
4640 hammer2_chain_unlock(nchain);
4641 hammer2_chain_drop(nchain);
4642 hammer2_inode_unlock(nip);