2 * Copyright (c) 2011-2015 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * and Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This subsystem implements most of the core support functions for
37 * the hammer2_chain structure.
39 * Chains are the in-memory version on media objects (volume header, inodes,
40 * indirect blocks, data blocks, etc). Chains represent a portion of the
43 * Chains are no-longer delete-duplicated. Instead, the original in-memory
44 * chain will be moved along with its block reference (e.g. for things like
45 * renames, hardlink operations, modifications, etc), and will be indexed
46 * on a secondary list for flush handling instead of propagating a flag
49 * Concurrent front-end operations can still run against backend flushes
50 * as long as they do not cross the current flush boundary. An operation
51 * running above the current flush (in areas not yet flushed) can become
52 * part of the current flush while ano peration running below the current
53 * flush can become part of the next flush.
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
60 #include <sys/kern_syscall.h>
63 #include <crypto/sha2/sha2.h>
67 static hammer2_chain_t *hammer2_chain_create_indirect(
68 hammer2_chain_t *parent,
69 hammer2_key_t key, int keybits,
70 hammer2_tid_t mtid, int for_type, int *errorp);
71 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain,
73 static hammer2_chain_t *hammer2_combined_find(
74 hammer2_chain_t *parent,
75 hammer2_blockref_t *base, int count,
76 int *cache_indexp, hammer2_key_t *key_nextp,
77 hammer2_key_t key_beg, hammer2_key_t key_end,
78 hammer2_blockref_t **bresp);
81 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
82 * overlap in the RB trees. Deleted chains are moved from rbtree to either
85 * Chains in delete-duplicate sequences can always iterate through core_entry
86 * to locate the live version of the chain.
88 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
90 extern int h2timer[32];
94 #define TIMER(which) do { \
96 h2timer[h2lid] += (int)(ticks - h2last);\
102 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
104 hammer2_key_t c1_beg;
105 hammer2_key_t c1_end;
106 hammer2_key_t c2_beg;
107 hammer2_key_t c2_end;
110 * Compare chains. Overlaps are not supposed to happen and catch
111 * any software issues early we count overlaps as a match.
113 c1_beg = chain1->bref.key;
114 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
115 c2_beg = chain2->bref.key;
116 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
118 if (c1_end < c2_beg) /* fully to the left */
120 if (c1_beg > c2_end) /* fully to the right */
122 return(0); /* overlap (must not cross edge boundary) */
126 * Make a chain visible to the flusher. The flusher needs to be able to
127 * do flushes of subdirectory chains or single files so it does a top-down
128 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
129 * or UPDATE chains and flushes back up the chain to the volume root.
131 * This routine sets ONFLUSH upward until it hits the volume root. For
132 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
133 * Extra ONFLUSH flagging doesn't hurt the filesystem.
136 hammer2_chain_setflush(hammer2_chain_t *chain)
138 hammer2_chain_t *parent;
140 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
141 hammer2_spin_sh(&chain->core.spin);
142 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
143 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
144 if ((parent = chain->parent) == NULL)
146 hammer2_spin_sh(&parent->core.spin);
147 hammer2_spin_unsh(&chain->core.spin);
150 hammer2_spin_unsh(&chain->core.spin);
155 * Allocate a new disconnected chain element representing the specified
156 * bref. chain->refs is set to 1 and the passed bref is copied to
157 * chain->bref. chain->bytes is derived from the bref.
159 * chain->pmp inherits pmp unless the chain is an inode (other than the
162 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
165 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
166 hammer2_blockref_t *bref)
168 hammer2_chain_t *chain;
172 * Special case - radix of 0 indicates a chain that does not
173 * need a data reference (context is completely embedded in the
176 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
177 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
181 atomic_add_long(&hammer2_chain_allocs, 1);
184 * Construct the appropriate system structure.
187 case HAMMER2_BREF_TYPE_DIRENT:
188 case HAMMER2_BREF_TYPE_INODE:
189 case HAMMER2_BREF_TYPE_INDIRECT:
190 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
191 case HAMMER2_BREF_TYPE_DATA:
192 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
194 * Chain's are really only associated with the hmp but we
195 * maintain a pmp association for per-mount memory tracking
196 * purposes. The pmp can be NULL.
198 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
200 case HAMMER2_BREF_TYPE_VOLUME:
201 case HAMMER2_BREF_TYPE_FREEMAP:
203 * Only hammer2_chain_bulksnap() calls this function with these
206 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
210 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
215 * Initialize the new chain structure. pmp must be set to NULL for
216 * chains belonging to the super-root topology of a device mount.
218 if (pmp == hmp->spmp)
224 chain->bytes = bytes;
226 chain->flags = HAMMER2_CHAIN_ALLOCATED;
229 * Set the PFS boundary flag if this chain represents a PFS root.
231 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
232 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
233 hammer2_chain_core_init(chain);
239 * Initialize a chain's core structure. This structure used to be allocated
240 * but is now embedded.
242 * The core is not locked. No additional refs on the chain are made.
243 * (trans) must not be NULL if (core) is not NULL.
246 hammer2_chain_core_init(hammer2_chain_t *chain)
249 * Fresh core under nchain (no multi-homing of ochain's
252 RB_INIT(&chain->core.rbtree); /* live chains */
253 hammer2_mtx_init(&chain->lock, "h2chain");
257 * Add a reference to a chain element, preventing its destruction.
259 * (can be called with spinlock held)
262 hammer2_chain_ref(hammer2_chain_t *chain)
264 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
266 * 0->non-zero transition must ensure that chain is removed
269 * NOTE: Already holding lru_spin here so we cannot call
270 * hammer2_chain_ref() to get it off lru_list, do
273 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
274 hammer2_pfs_t *pmp = chain->pmp;
275 hammer2_spin_ex(&pmp->lru_spin);
276 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
277 atomic_add_int(&pmp->lru_count, -1);
278 atomic_clear_int(&chain->flags,
279 HAMMER2_CHAIN_ONLRU);
280 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
282 hammer2_spin_unex(&pmp->lru_spin);
286 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
292 * Ref a locked chain and force the data to be held across an unlock.
293 * Chain must be currently locked. The user of the chain who desires
294 * to release the hold must call hammer2_chain_lock_unhold() to lock
295 * and unhold the chain, then unlock normally, or may simply call
296 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
299 hammer2_chain_ref_hold(hammer2_chain_t *chain)
301 atomic_add_int(&chain->persist_refs, 1);
302 hammer2_chain_ref(chain);
306 * Insert the chain in the core rbtree.
308 * Normal insertions are placed in the live rbtree. Insertion of a deleted
309 * chain is a special case used by the flush code that is placed on the
310 * unstaged deleted list to avoid confusing the live view.
312 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
313 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
314 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
318 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
319 int flags, int generation)
321 hammer2_chain_t *xchain;
324 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
325 hammer2_spin_ex(&parent->core.spin);
328 * Interlocked by spinlock, check for race
330 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
331 parent->core.generation != generation) {
339 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
340 KASSERT(xchain == NULL,
341 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
342 chain, xchain, chain->bref.key));
343 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
344 chain->parent = parent;
345 ++parent->core.chain_count;
346 ++parent->core.generation; /* XXX incs for _get() too, XXX */
349 * We have to keep track of the effective live-view blockref count
350 * so the create code knows when to push an indirect block.
352 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
353 atomic_add_int(&parent->core.live_count, 1);
355 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
356 hammer2_spin_unex(&parent->core.spin);
361 * Drop the caller's reference to the chain. When the ref count drops to
362 * zero this function will try to disassociate the chain from its parent and
363 * deallocate it, then recursely drop the parent using the implied ref
364 * from the chain's chain->parent.
366 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
369 hammer2_chain_drop(hammer2_chain_t *chain)
373 if (hammer2_debug & 0x200000)
376 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
380 KKASSERT(chain->refs > 0);
388 chain = hammer2_chain_lastdrop(chain);
390 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
392 /* retry the same chain */
398 * Unhold a held and probably not-locked chain. To ensure that the data
399 * is properly dropped we check lockcnt. If lockcnt is 0 we unconditionally
400 * interlock the chain to release its data. We must obtain the lock
401 * unconditionally becuase it is possible for the chain to still be
402 * temporarily locked by a hammer2_chain_unlock() call in a race.
405 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
409 atomic_add_int(&chain->persist_refs, -1);
411 if (chain->lockcnt == 0) {
412 hammer2_mtx_ex(&chain->lock);
413 if (chain->lockcnt == 0 && chain->persist_refs == 0) {
414 dio = hammer2_chain_drop_data(chain, 0);
416 hammer2_io_bqrelse(&dio);
418 hammer2_mtx_unlock(&chain->lock);
420 hammer2_chain_drop(chain);
424 * Safe handling of the 1->0 transition on chain. Returns a chain for
425 * recursive drop or NULL, possibly returning the same chain if the atomic
428 * When two chains need to be recursively dropped we use the chain we
429 * would otherwise free to placehold the additional chain. It's a bit
430 * convoluted but we can't just recurse without potentially blowing out
433 * The chain cannot be freed if it has any children.
434 * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
435 * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
437 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
441 hammer2_chain_lastdrop(hammer2_chain_t *chain)
445 hammer2_chain_t *parent;
446 hammer2_chain_t *rdrop;
450 * Critical field access.
452 hammer2_spin_ex(&chain->core.spin);
454 if ((parent = chain->parent) != NULL) {
456 * If the chain has a parent the UPDATE bit prevents scrapping
457 * as the chain is needed to properly flush the parent. Try
458 * to complete the 1->0 transition and return NULL. Retry
459 * (return chain) if we are unable to complete the 1->0
460 * transition, else return NULL (nothing more to do).
462 * If the chain has a parent the MODIFIED bit prevents
465 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
467 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
468 HAMMER2_CHAIN_MODIFIED)) {
469 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
470 dio = hammer2_chain_drop_data(chain, 0);
471 hammer2_spin_unex(&chain->core.spin);
473 hammer2_io_bqrelse(&dio);
476 hammer2_spin_unex(&chain->core.spin);
480 /* spinlock still held */
483 * The chain has no parent and can be flagged for destruction.
484 * Since it has no parent, UPDATE can also be cleared.
486 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
487 if (chain->flags & HAMMER2_CHAIN_UPDATE)
488 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
491 * If the chain has children we must still flush the chain.
492 * Any dedup is already handled by the underlying DIO, so
493 * we do not have to specifically flush it here.
495 * In the case where it has children, the DESTROY flag test
496 * in the flush code will prevent unnecessary flushes of
497 * MODIFIED chains that are not flagged DEDUP so don't worry
500 if (chain->core.chain_count) {
502 * Put on flushq (should ensure refs > 1), retry
505 hammer2_spin_unex(&chain->core.spin);
506 hammer2_delayed_flush(chain);
507 return(chain); /* retry drop */
511 * Otherwise we can scrap the MODIFIED bit if it is set,
512 * and continue along the freeing path.
514 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
515 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
516 atomic_add_long(&hammer2_count_modified_chains, -1);
518 hammer2_pfs_memory_wakeup(chain->pmp);
520 /* spinlock still held */
523 /* spinlock still held */
527 * If any children exist we must leave the chain intact with refs == 0.
528 * They exist because chains are retained below us which have refs or
529 * may require flushing. This case can occur when parent != NULL.
531 * Retry (return chain) if we fail to transition the refs to 0, else
532 * return NULL indication nothing more to do.
534 * Chains with children are NOT put on the LRU list.
536 if (chain->core.chain_count) {
538 hammer2_spin_ex(&parent->core.spin);
539 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
540 dio = hammer2_chain_drop_data(chain, 1);
541 hammer2_spin_unex(&chain->core.spin);
543 hammer2_spin_unex(&parent->core.spin);
546 hammer2_io_bqrelse(&dio);
548 hammer2_spin_unex(&chain->core.spin);
550 hammer2_spin_unex(&parent->core.spin);
554 /* spinlock still held */
555 /* no chains left under us */
558 * chain->core has no children left so no accessors can get to our
559 * chain from there. Now we have to lock the parent core to interlock
560 * remaining possible accessors that might bump chain's refs before
561 * we can safely drop chain's refs with intent to free the chain.
564 pmp = chain->pmp; /* can be NULL */
567 parent = chain->parent;
570 * WARNING! chain's spin lock is still held here, and other spinlocks
571 * will be acquired and released in the code below. We
572 * cannot be making fancy procedure calls!
576 * We can cache the chain if it is associated with a pmp
577 * and not flagged as being destroyed or requesting a full
578 * release. In this situation the chain is not removed
579 * from its parent, i.e. it can still be looked up.
581 * We intentionally do not cache DATA chains because these
582 * were likely used to load data into the logical buffer cache
583 * and will not be accessed again for some time.
586 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
588 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
590 hammer2_spin_ex(&parent->core.spin);
591 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
593 * 1->0 transition failed, retry. Do not drop
594 * the chain's data yet!
597 hammer2_spin_unex(&parent->core.spin);
598 hammer2_spin_unex(&chain->core.spin);
604 * Success, be sure to clean out the chain's data
605 * before putting it on a queue that it might be
608 dio = hammer2_chain_drop_data(chain, 1);
610 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
611 hammer2_spin_ex(&pmp->lru_spin);
612 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
613 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
616 * If we are over the LRU limit we need to drop something.
618 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
619 rdrop = TAILQ_FIRST(&pmp->lru_list);
620 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
621 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
622 atomic_add_int(&rdrop->refs, 1);
623 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
625 atomic_add_int(&pmp->lru_count, 1);
627 hammer2_spin_unex(&pmp->lru_spin);
629 hammer2_spin_unex(&parent->core.spin);
630 parent = NULL; /* safety */
632 hammer2_spin_unex(&chain->core.spin);
634 hammer2_io_bqrelse(&dio);
641 * Spinlock the parent and try to drop the last ref on chain.
642 * On success determine if we should dispose of the chain
643 * (remove the chain from its parent, etc).
645 * (normal core locks are top-down recursive but we define
646 * core spinlocks as bottom-up recursive, so this is safe).
649 hammer2_spin_ex(&parent->core.spin);
650 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
652 /* XXX remove, don't try to drop data on fail */
653 hammer2_spin_unex(&parent->core.spin);
654 dio = hammer2_chain_drop_data(chain, 0);
655 hammer2_spin_unex(&chain->core.spin);
657 hammer2_io_bqrelse(&dio);
660 * 1->0 transition failed, retry.
662 hammer2_spin_unex(&parent->core.spin);
663 hammer2_spin_unex(&chain->core.spin);
669 * 1->0 transition successful, remove chain from the
672 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
673 RB_REMOVE(hammer2_chain_tree,
674 &parent->core.rbtree, chain);
675 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
676 --parent->core.chain_count;
677 chain->parent = NULL;
681 * If our chain was the last chain in the parent's core the
682 * core is now empty and its parent might have to be
683 * re-dropped if it has 0 refs.
685 if (parent->core.chain_count == 0) {
687 atomic_add_int(&rdrop->refs, 1);
689 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
693 hammer2_spin_unex(&parent->core.spin);
694 parent = NULL; /* safety */
699 * Successful 1->0 transition and the chain can be destroyed now.
701 * We still have the core spinlock, and core's chain_count is 0.
702 * Any parent spinlock is gone.
704 hammer2_spin_unex(&chain->core.spin);
705 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
706 chain->core.chain_count == 0);
709 * All spin locks are gone, no pointers remain to the chain, finish
712 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
713 HAMMER2_CHAIN_MODIFIED)) == 0);
714 dio = hammer2_chain_drop_data(chain, 1);
716 hammer2_io_bqrelse(&dio);
719 * Once chain resources are gone we can use the now dead chain
720 * structure to placehold what might otherwise require a recursive
721 * drop, because we have potentially two things to drop and can only
722 * return one directly.
724 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
725 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
727 kfree(chain, hmp->mchain);
731 * Possible chaining loop when parent re-drop needed.
737 * On either last lock release or last drop
739 static hammer2_io_t *
740 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
744 if ((dio = chain->dio) != NULL) {
748 switch(chain->bref.type) {
749 case HAMMER2_BREF_TYPE_VOLUME:
750 case HAMMER2_BREF_TYPE_FREEMAP:
755 if (chain->data != NULL) {
756 hammer2_spin_unex(&chain->core.spin);
757 panic("chain data not null");
759 KKASSERT(chain->data == NULL);
767 * Lock a referenced chain element, acquiring its data with I/O if necessary,
768 * and specify how you would like the data to be resolved.
770 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
772 * The lock is allowed to recurse, multiple locking ops will aggregate
773 * the requested resolve types. Once data is assigned it will not be
774 * removed until the last unlock.
776 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
777 * (typically used to avoid device/logical buffer
780 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
781 * the INITIAL-create state (indirect blocks only).
783 * Do not resolve data elements for DATA chains.
784 * (typically used to avoid device/logical buffer
787 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
789 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
790 * it will be locked exclusive.
792 * NOTE: Embedded elements (volume header, inodes) are always resolved
795 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
796 * element will instantiate and zero its buffer, and flush it on
799 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
800 * so as not to instantiate a device buffer, which could alias against
801 * a logical file buffer. However, if ALWAYS is specified the
802 * device buffer will be instantiated anyway.
804 * WARNING! This function blocks on I/O if data needs to be fetched. This
805 * blocking can run concurrent with other compatible lock holders
806 * who do not need data returning. The lock is not upgraded to
807 * exclusive during a data fetch, a separate bit is used to
808 * interlock I/O. However, an exclusive lock holder can still count
809 * on being interlocked against an I/O fetch managed by a shared
813 hammer2_chain_lock(hammer2_chain_t *chain, int how)
816 * Ref and lock the element. Recursive locks are allowed.
818 KKASSERT(chain->refs > 0);
819 atomic_add_int(&chain->lockcnt, 1);
824 * Get the appropriate lock. If LOCKAGAIN is flagged with SHARED
825 * the caller expects a shared lock to already be present and we
826 * are giving it another ref. This case must importantly not block
827 * if there is a pending exclusive lock request.
829 if (how & HAMMER2_RESOLVE_SHARED) {
830 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
831 hammer2_mtx_sh_again(&chain->lock);
833 hammer2_mtx_sh(&chain->lock);
836 hammer2_mtx_ex(&chain->lock);
838 ++curthread->td_tracker;
842 * If we already have a valid data pointer no further action is
850 * Do we have to resolve the data? This is generally only
851 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
852 * Other BREF types expects the data to be there.
854 switch(how & HAMMER2_RESOLVE_MASK) {
855 case HAMMER2_RESOLVE_NEVER:
857 case HAMMER2_RESOLVE_MAYBE:
858 if (chain->flags & HAMMER2_CHAIN_INITIAL)
860 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
863 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
865 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
869 case HAMMER2_RESOLVE_ALWAYS:
875 * Caller requires data
877 hammer2_chain_load_data(chain);
881 * Lock the chain and remove the data hold (matches against
882 * hammer2_chain_unlock_hold()). The data remains valid because
883 * the chain is now locked, but will be dropped as per-normal when
884 * the caller does a normal unlock.
887 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
889 atomic_add_int(&chain->persist_refs, -1);
890 hammer2_chain_lock(chain, how);
895 * Downgrade an exclusive chain lock to a shared chain lock.
897 * NOTE: There is no upgrade equivalent due to the ease of
898 * deadlocks in that direction.
901 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
903 hammer2_mtx_downgrade(&chain->lock);
909 * Obtains a second shared lock on the chain, does not account the second
910 * shared lock as being owned by the current thread.
912 * Caller must already own a shared lock on this chain.
914 * The lock function is required to obtain the second shared lock without
915 * blocking on pending exclusive requests.
918 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
920 hammer2_mtx_sh_again(&chain->lock);
921 atomic_add_int(&chain->lockcnt, 1);
922 /* do not count in td_tracker for this thread */
926 * Accounts for a shared lock that was pushed to us as being owned by our
930 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
932 ++curthread->td_tracker;
937 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
938 * may be of any type.
940 * Once chain->data is set it cannot be disposed of until all locks are
944 hammer2_chain_load_data(hammer2_chain_t *chain)
946 hammer2_blockref_t *bref;
953 * Degenerate case, data already present, or chain is not expected
958 if ((chain->bref.data_off & HAMMER2_OFF_MASK_RADIX) == 0)
963 KKASSERT(hmp != NULL);
966 * Gain the IOINPROG bit, interlocked block.
972 oflags = chain->flags;
974 if (oflags & HAMMER2_CHAIN_IOINPROG) {
975 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
976 tsleep_interlock(&chain->flags, 0);
977 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
978 tsleep(&chain->flags, PINTERLOCKED,
983 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
984 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
993 * We own CHAIN_IOINPROG
995 * Degenerate case if we raced another load.
1001 * We must resolve to a device buffer, either by issuing I/O or
1002 * by creating a zero-fill element. We do not mark the buffer
1003 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1004 * API must still be used to do that).
1006 * The device buffer is variable-sized in powers of 2 down
1007 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1008 * chunk always contains buffers of the same size. (XXX)
1010 * The minimum physical IO size may be larger than the variable
1013 bref = &chain->bref;
1016 * The getblk() optimization can only be used on newly created
1017 * elements if the physical block size matches the request.
1019 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1020 error = hammer2_io_new(hmp, bref->type,
1021 bref->data_off, chain->bytes,
1024 error = hammer2_io_bread(hmp, bref->type,
1025 bref->data_off, chain->bytes,
1027 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1031 chain->error = HAMMER2_ERROR_IO;
1032 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1033 (intmax_t)bref->data_off, error);
1034 hammer2_io_bqrelse(&chain->dio);
1040 * This isn't perfect and can be ignored on OSs which do not have
1041 * an indication as to whether a buffer is coming from cache or
1042 * if I/O was actually issued for the read. TESTEDGOOD will work
1043 * pretty well without the B_IOISSUED logic because chains are
1046 * If the underlying kernel buffer covers the entire chain we can
1047 * use the B_IOISSUED indication to determine if we have to re-run
1048 * the CRC on chain data for chains that managed to stay cached
1049 * across the kernel disposal of the original buffer.
1051 if ((dio = chain->dio) != NULL && dio->bp) {
1052 struct buf *bp = dio->bp;
1054 if (dio->psize == chain->bytes &&
1055 (bp->b_flags & B_IOISSUED)) {
1056 atomic_clear_int(&chain->flags,
1057 HAMMER2_CHAIN_TESTEDGOOD);
1058 bp->b_flags &= ~B_IOISSUED;
1063 * NOTE: A locked chain's data cannot be modified without first
1064 * calling hammer2_chain_modify().
1068 * Clear INITIAL. In this case we used io_new() and the buffer has
1069 * been zero'd and marked dirty.
1071 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1073 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1074 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1075 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1076 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1078 * check data not currently synchronized due to
1079 * modification. XXX assumes data stays in the buffer
1080 * cache, which might not be true (need biodep on flush
1081 * to calculate crc? or simple crc?).
1083 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1085 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1086 chain->error = HAMMER2_ERROR_CHECK;
1088 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1094 * Setup the data pointer, either pointing it to an embedded data
1095 * structure and copying the data from the buffer, or pointing it
1098 * The buffer is not retained when copying to an embedded data
1099 * structure in order to avoid potential deadlocks or recursions
1100 * on the same physical buffer.
1102 * WARNING! Other threads can start using the data the instant we
1103 * set chain->data non-NULL.
1105 switch (bref->type) {
1106 case HAMMER2_BREF_TYPE_VOLUME:
1107 case HAMMER2_BREF_TYPE_FREEMAP:
1109 * Copy data from bp to embedded buffer
1111 panic("hammer2_chain_load_data: unresolved volume header");
1113 case HAMMER2_BREF_TYPE_DIRENT:
1114 KKASSERT(chain->bytes != 0);
1116 case HAMMER2_BREF_TYPE_INODE:
1117 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1118 case HAMMER2_BREF_TYPE_INDIRECT:
1119 case HAMMER2_BREF_TYPE_DATA:
1120 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1123 * Point data at the device buffer and leave dio intact.
1125 chain->data = (void *)bdata;
1130 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1137 oflags = chain->flags;
1138 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1139 HAMMER2_CHAIN_IOSIGNAL);
1140 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1141 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1142 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1143 wakeup(&chain->flags);
1151 * Unlock and deref a chain element.
1153 * Remember that the presence of children under chain prevent the chain's
1154 * destruction but do not add additional references, so the dio will still
1158 hammer2_chain_unlock(hammer2_chain_t *chain)
1162 --curthread->td_tracker;
1164 * If multiple locks are present (or being attempted) on this
1165 * particular chain we can just unlock, drop refs, and return.
1167 * Otherwise fall-through on the 1->0 transition.
1170 lockcnt = chain->lockcnt;
1171 KKASSERT(lockcnt > 0);
1174 if (atomic_cmpset_int(&chain->lockcnt,
1175 lockcnt, lockcnt - 1)) {
1176 hammer2_mtx_unlock(&chain->lock);
1180 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1187 * Normally we want to disassociate the data on the last unlock,
1188 * but leave it intact if persist_refs is non-zero. The persist-data
1189 * user modifies persist_refs only while holding the chain locked
1190 * so there should be no race on the last unlock here.
1192 * NOTE: If this was a shared lock we have to temporarily upgrade it
1193 * to prevent data load races. We can only do this non-blocking,
1194 * and unlock/relock-excl can deadlock. If the try fails it
1195 * means someone else got a shared or exclusive lock while we
1196 * we bandying about.
1198 if (chain->persist_refs == 0) {
1201 if (hammer2_mtx_upgrade_try(&chain->lock) == 0 &&
1202 chain->lockcnt == 0 && chain->persist_refs == 0) {
1203 dio = hammer2_chain_drop_data(chain, 0);
1205 hammer2_io_bqrelse(&dio);
1208 hammer2_mtx_unlock(&chain->lock);
1212 * Unlock and hold chain data intact
1215 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1217 atomic_add_int(&chain->persist_refs, 1);
1218 hammer2_chain_unlock(chain);
1222 * Helper to obtain the blockref[] array base and count for a chain.
1224 * XXX Not widely used yet, various use cases need to be validated and
1225 * converted to use this function.
1228 hammer2_blockref_t *
1229 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1231 hammer2_blockref_t *base;
1234 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1237 switch(parent->bref.type) {
1238 case HAMMER2_BREF_TYPE_INODE:
1239 count = HAMMER2_SET_COUNT;
1241 case HAMMER2_BREF_TYPE_INDIRECT:
1242 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1243 count = parent->bytes / sizeof(hammer2_blockref_t);
1245 case HAMMER2_BREF_TYPE_VOLUME:
1246 count = HAMMER2_SET_COUNT;
1248 case HAMMER2_BREF_TYPE_FREEMAP:
1249 count = HAMMER2_SET_COUNT;
1252 panic("hammer2_chain_create_indirect: "
1253 "unrecognized blockref type: %d",
1259 switch(parent->bref.type) {
1260 case HAMMER2_BREF_TYPE_INODE:
1261 base = &parent->data->ipdata.u.blockset.blockref[0];
1262 count = HAMMER2_SET_COUNT;
1264 case HAMMER2_BREF_TYPE_INDIRECT:
1265 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1266 base = &parent->data->npdata[0];
1267 count = parent->bytes / sizeof(hammer2_blockref_t);
1269 case HAMMER2_BREF_TYPE_VOLUME:
1270 base = &parent->data->voldata.
1271 sroot_blockset.blockref[0];
1272 count = HAMMER2_SET_COUNT;
1274 case HAMMER2_BREF_TYPE_FREEMAP:
1275 base = &parent->data->blkset.blockref[0];
1276 count = HAMMER2_SET_COUNT;
1279 panic("hammer2_chain_create_indirect: "
1280 "unrecognized blockref type: %d",
1292 * This counts the number of live blockrefs in a block array and
1293 * also calculates the point at which all remaining blockrefs are empty.
1294 * This routine can only be called on a live chain.
1296 * NOTE: Flag is not set until after the count is complete, allowing
1297 * callers to test the flag without holding the spinlock.
1299 * NOTE: If base is NULL the related chain is still in the INITIAL
1300 * state and there are no blockrefs to count.
1302 * NOTE: live_count may already have some counts accumulated due to
1303 * creation and deletion and could even be initially negative.
1306 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1307 hammer2_blockref_t *base, int count)
1309 hammer2_spin_ex(&chain->core.spin);
1310 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1312 while (--count >= 0) {
1313 if (base[count].type)
1316 chain->core.live_zero = count + 1;
1317 while (count >= 0) {
1318 if (base[count].type)
1319 atomic_add_int(&chain->core.live_count,
1324 chain->core.live_zero = 0;
1326 /* else do not modify live_count */
1327 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1329 hammer2_spin_unex(&chain->core.spin);
1333 * Resize the chain's physical storage allocation in-place. This function does
1334 * not usually adjust the data pointer and must be followed by (typically) a
1335 * hammer2_chain_modify() call to copy any old data over and adjust the
1338 * Chains can be resized smaller without reallocating the storage. Resizing
1339 * larger will reallocate the storage. Excess or prior storage is reclaimed
1340 * asynchronously at a later time.
1342 * An nradix value of 0 is special-cased to mean that the storage should
1343 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1346 * Must be passed an exclusively locked parent and chain.
1348 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1349 * to avoid instantiating a device buffer that conflicts with the vnode data
1350 * buffer. However, because H2 can compress or encrypt data, the chain may
1351 * have a dio assigned to it in those situations, and they do not conflict.
1353 * XXX return error if cannot resize.
1356 hammer2_chain_resize(hammer2_chain_t *chain,
1357 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1358 int nradix, int flags)
1367 * Only data and indirect blocks can be resized for now.
1368 * (The volu root, inodes, and freemap elements use a fixed size).
1370 KKASSERT(chain != &hmp->vchain);
1371 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1372 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1373 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1376 * Nothing to do if the element is already the proper size
1378 obytes = chain->bytes;
1379 nbytes = (nradix) ? (1U << nradix) : 0;
1380 if (obytes == nbytes)
1384 * Make sure the old data is instantiated so we can copy it. If this
1385 * is a data block, the device data may be superfluous since the data
1386 * might be in a logical block, but compressed or encrypted data is
1389 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1391 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1394 * Relocate the block, even if making it smaller (because different
1395 * block sizes may be in different regions).
1397 * NOTE: Operation does not copy the data and may only be used
1398 * to resize data blocks in-place, or directory entry blocks
1399 * which are about to be modified in some manner.
1401 hammer2_freemap_alloc(chain, nbytes);
1402 chain->bytes = nbytes;
1405 * We don't want the followup chain_modify() to try to copy data
1406 * from the old (wrong-sized) buffer. It won't know how much to
1407 * copy. This case should only occur during writes when the
1408 * originator already has the data to write in-hand.
1411 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1412 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1413 hammer2_io_brelse(&chain->dio);
1419 * Helper for chains already flagged as MODIFIED. A new allocation may
1420 * still be required if the existing one has already been used in a de-dup.
1424 modified_needs_new_allocation(hammer2_chain_t *chain)
1427 * We only live-dedup data, we do not live-dedup meta-data.
1429 if (chain->bref.type != HAMMER2_BREF_TYPE_DATA &&
1430 chain->bref.type != HAMMER2_BREF_TYPE_DIRENT) {
1435 * If chain has no data, then there is nothing to live-dedup.
1437 if (chain->bytes == 0)
1445 * If this flag is not set the current modification has not been
1446 * recorded for dedup so a new allocation is not needed. The
1447 * recording occurs when dirty file data is flushed from the frontend
1450 if (chain->flags & HAMMER2_CHAIN_DEDUP)
1454 * If the DEDUP flag is set we have one final line of defense to
1455 * allow re-use of a modified buffer, and that is if the DIO_INVALOK
1456 * flag is still set on the underlying DIO. This flag is only set
1457 * for hammer2_io_new() buffers which cover the whole buffer (64KB),
1458 * and is cleared when a dedup operation actually decides to use
1462 if ((dio = chain->dio) != NULL) {
1463 if (dio->refs & HAMMER2_DIO_INVALOK)
1466 dio = hammer2_io_getquick(chain->hmp, chain->bref.data_off,
1469 if (dio->refs & HAMMER2_DIO_INVALOK) {
1470 hammer2_io_putblk(&dio);
1473 hammer2_io_putblk(&dio);
1481 * Set the chain modified so its data can be changed by the caller.
1483 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1484 * is a CLC (cluster level change) field and is not updated by parent
1485 * propagation during a flush.
1487 * If the caller passes a non-zero dedup_off we assign data_off to that
1488 * instead of allocating a ne block. Caller must not modify the data already
1489 * present at the target offset.
1492 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1493 hammer2_off_t dedup_off, int flags)
1495 hammer2_blockref_t obref;
1504 obref = chain->bref;
1505 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1508 * Data is not optional for freemap chains (we must always be sure
1509 * to copy the data on COW storage allocations).
1511 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1512 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1513 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1514 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1518 * Data must be resolved if already assigned, unless explicitly
1519 * flagged otherwise.
1521 if (chain->data == NULL && chain->bytes != 0 &&
1522 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1523 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1524 hammer2_chain_load_data(chain);
1528 * Set MODIFIED to indicate that the chain has been modified.
1529 * Set UPDATE to ensure that the blockref is updated in the parent.
1531 * If MODIFIED is already set determine if we can reuse the assigned
1532 * data block or if we need a new data block. The assigned data block
1533 * can be reused if HAMMER2_DIO_INVALOK is set on the dio.
1535 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
1536 modified_needs_new_allocation(chain)) {
1538 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1540 * Must set modified bit.
1542 atomic_add_long(&hammer2_count_modified_chains, 1);
1543 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1544 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1547 * We may be able to avoid a copy-on-write if the chain's
1548 * check mode is set to NONE and the chain's current
1549 * modify_tid is beyond the last explicit snapshot tid.
1551 * This implements HAMMER2's overwrite-in-place feature.
1553 * NOTE! This data-block cannot be used as a de-duplication
1554 * source when the check mode is set to NONE.
1556 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1557 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1558 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1559 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1560 HAMMER2_CHECK_NONE &&
1562 chain->bref.modify_tid >
1563 chain->pmp->iroot->meta.pfs_lsnap_tid &&
1564 modified_needs_new_allocation(chain) == 0) {
1566 * Sector overwrite allowed.
1571 * Sector overwrite not allowed, must copy-on-write.
1577 * Already flagged modified, no new allocation is needed.
1583 * Flag parent update required.
1585 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1586 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1589 * The modification or re-modification requires an allocation and
1592 * If dedup_off is non-zero, caller already has a data offset
1593 * containing the caller's desired data. The dedup offset is
1594 * allowed to be in a partially free state and we must be sure
1595 * to reset it to a fully allocated state to force two bulkfree
1596 * passes to free it again. The chain will not be marked MODIFIED
1597 * in the dedup case, as the dedup data cannot be changed without
1600 * NOTE: Only applicable when chain->bytes != 0.
1602 * XXX can a chain already be marked MODIFIED without a data
1603 * assignment? If not, assert here instead of testing the case.
1605 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1607 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1611 chain->bref.data_off = dedup_off;
1612 chain->bytes = 1 << (dedup_off &
1613 HAMMER2_OFF_MASK_RADIX);
1614 atomic_clear_int(&chain->flags,
1615 HAMMER2_CHAIN_MODIFIED);
1616 atomic_add_long(&hammer2_count_modified_chains,
1619 hammer2_pfs_memory_wakeup(chain->pmp);
1620 hammer2_freemap_adjust(hmp, &chain->bref,
1621 HAMMER2_FREEMAP_DORECOVER);
1623 hammer2_freemap_alloc(chain, chain->bytes);
1625 /* XXX failed allocation */
1630 * Update mirror_tid and modify_tid. modify_tid is only updated
1631 * if not passed as zero (during flushes, parent propagation passes
1634 * NOTE: chain->pmp could be the device spmp.
1636 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1638 chain->bref.modify_tid = mtid;
1641 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1642 * requires updating as well as to tell the delete code that the
1643 * chain's blockref might not exactly match (in terms of physical size
1644 * or block offset) the one in the parent's blocktable. The base key
1645 * of course will still match.
1647 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1648 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1651 * Short-cut data blocks which the caller does not need an actual
1652 * data reference to (aka OPTDATA), as long as the chain does not
1653 * already have a data pointer to the data. This generally means
1654 * that the modifications are being done via the logical buffer cache.
1655 * The INITIAL flag relates only to the device data buffer and thus
1656 * remains unchange in this situation.
1658 * This code also handles bytes == 0 (most dirents).
1660 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1661 (flags & HAMMER2_MODIFY_OPTDATA) &&
1662 chain->data == NULL) {
1663 KKASSERT(chain->dio == NULL);
1668 * Clearing the INITIAL flag (for indirect blocks) indicates that
1669 * we've processed the uninitialized storage allocation.
1671 * If this flag is already clear we are likely in a copy-on-write
1672 * situation but we have to be sure NOT to bzero the storage if
1673 * no data is present.
1675 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1676 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1683 * Instantiate data buffer and possibly execute COW operation
1685 switch(chain->bref.type) {
1686 case HAMMER2_BREF_TYPE_VOLUME:
1687 case HAMMER2_BREF_TYPE_FREEMAP:
1689 * The data is embedded, no copy-on-write operation is
1692 KKASSERT(chain->dio == NULL);
1694 case HAMMER2_BREF_TYPE_DIRENT:
1696 * The data might be fully embedded.
1698 if (chain->bytes == 0) {
1699 KKASSERT(chain->dio == NULL);
1703 case HAMMER2_BREF_TYPE_INODE:
1704 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1705 case HAMMER2_BREF_TYPE_DATA:
1706 case HAMMER2_BREF_TYPE_INDIRECT:
1707 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1709 * Perform the copy-on-write operation
1711 * zero-fill or copy-on-write depending on whether
1712 * chain->data exists or not and set the dirty state for
1713 * the new buffer. hammer2_io_new() will handle the
1716 * If a dedup_off was supplied this is an existing block
1717 * and no COW, copy, or further modification is required.
1719 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1721 if (wasinitial && dedup_off == 0) {
1722 error = hammer2_io_new(hmp, chain->bref.type,
1723 chain->bref.data_off,
1724 chain->bytes, &dio);
1726 error = hammer2_io_bread(hmp, chain->bref.type,
1727 chain->bref.data_off,
1728 chain->bytes, &dio);
1730 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1733 * If an I/O error occurs make sure callers cannot accidently
1734 * modify the old buffer's contents and corrupt the filesystem.
1737 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1739 chain->error = HAMMER2_ERROR_IO;
1740 hammer2_io_brelse(&dio);
1741 hammer2_io_brelse(&chain->dio);
1746 bdata = hammer2_io_data(dio, chain->bref.data_off);
1750 * COW (unless a dedup).
1752 KKASSERT(chain->dio != NULL);
1753 if (chain->data != (void *)bdata && dedup_off == 0) {
1754 bcopy(chain->data, bdata, chain->bytes);
1756 } else if (wasinitial == 0) {
1758 * We have a problem. We were asked to COW but
1759 * we don't have any data to COW with!
1761 panic("hammer2_chain_modify: having a COW %p\n",
1766 * Retire the old buffer, replace with the new. Dirty or
1767 * redirty the new buffer.
1769 * WARNING! The system buffer cache may have already flushed
1770 * the buffer, so we must be sure to [re]dirty it
1771 * for further modification.
1773 * If dedup_off was supplied, the caller is not
1774 * expected to make any further modification to the
1778 hammer2_io_bqrelse(&chain->dio);
1779 chain->data = (void *)bdata;
1782 hammer2_io_setdirty(dio);
1785 panic("hammer2_chain_modify: illegal non-embedded type %d",
1792 * setflush on parent indicating that the parent must recurse down
1793 * to us. Do not call on chain itself which might already have it
1797 hammer2_chain_setflush(chain->parent);
1801 * Modify the chain associated with an inode.
1804 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1805 hammer2_tid_t mtid, int flags)
1807 hammer2_inode_modify(ip);
1808 hammer2_chain_modify(chain, mtid, 0, flags);
1812 * Volume header data locks
1815 hammer2_voldata_lock(hammer2_dev_t *hmp)
1817 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1821 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1823 lockmgr(&hmp->vollk, LK_RELEASE);
1827 hammer2_voldata_modify(hammer2_dev_t *hmp)
1829 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1830 atomic_add_long(&hammer2_count_modified_chains, 1);
1831 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1832 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1837 * This function returns the chain at the nearest key within the specified
1838 * range. The returned chain will be referenced but not locked.
1840 * This function will recurse through chain->rbtree as necessary and will
1841 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1842 * the iteration value is less than the current value of *key_nextp.
1844 * The caller should use (*key_nextp) to calculate the actual range of
1845 * the returned element, which will be (key_beg to *key_nextp - 1), because
1846 * there might be another element which is superior to the returned element
1849 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1850 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1851 * it will wind up being (key_end + 1).
1853 * WARNING! Must be called with child's spinlock held. Spinlock remains
1854 * held through the operation.
1856 struct hammer2_chain_find_info {
1857 hammer2_chain_t *best;
1858 hammer2_key_t key_beg;
1859 hammer2_key_t key_end;
1860 hammer2_key_t key_next;
1863 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1864 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1868 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1869 hammer2_key_t key_beg, hammer2_key_t key_end)
1871 struct hammer2_chain_find_info info;
1874 info.key_beg = key_beg;
1875 info.key_end = key_end;
1876 info.key_next = *key_nextp;
1878 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1879 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1881 *key_nextp = info.key_next;
1883 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1884 parent, key_beg, key_end, *key_nextp);
1892 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1894 struct hammer2_chain_find_info *info = data;
1895 hammer2_key_t child_beg;
1896 hammer2_key_t child_end;
1898 child_beg = child->bref.key;
1899 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1901 if (child_end < info->key_beg)
1903 if (child_beg > info->key_end)
1910 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1912 struct hammer2_chain_find_info *info = data;
1913 hammer2_chain_t *best;
1914 hammer2_key_t child_end;
1917 * WARNING! Layerq is scanned forwards, exact matches should keep
1918 * the existing info->best.
1920 if ((best = info->best) == NULL) {
1922 * No previous best. Assign best
1925 } else if (best->bref.key <= info->key_beg &&
1926 child->bref.key <= info->key_beg) {
1931 /*info->best = child;*/
1932 } else if (child->bref.key < best->bref.key) {
1934 * Child has a nearer key and best is not flush with key_beg.
1935 * Set best to child. Truncate key_next to the old best key.
1938 if (info->key_next > best->bref.key || info->key_next == 0)
1939 info->key_next = best->bref.key;
1940 } else if (child->bref.key == best->bref.key) {
1942 * If our current best is flush with the child then this
1943 * is an illegal overlap.
1945 * key_next will automatically be limited to the smaller of
1946 * the two end-points.
1952 * Keep the current best but truncate key_next to the child's
1955 * key_next will also automatically be limited to the smaller
1956 * of the two end-points (probably not necessary for this case
1957 * but we do it anyway).
1959 if (info->key_next > child->bref.key || info->key_next == 0)
1960 info->key_next = child->bref.key;
1964 * Always truncate key_next based on child's end-of-range.
1966 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1967 if (child_end && (info->key_next > child_end || info->key_next == 0))
1968 info->key_next = child_end;
1974 * Retrieve the specified chain from a media blockref, creating the
1975 * in-memory chain structure which reflects it.
1977 * To handle insertion races pass the INSERT_RACE flag along with the
1978 * generation number of the core. NULL will be returned if the generation
1979 * number changes before we have a chance to insert the chain. Insert
1980 * races can occur because the parent might be held shared.
1982 * Caller must hold the parent locked shared or exclusive since we may
1983 * need the parent's bref array to find our block.
1985 * WARNING! chain->pmp is always set to NULL for any chain representing
1986 * part of the super-root topology.
1989 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1990 hammer2_blockref_t *bref)
1992 hammer2_dev_t *hmp = parent->hmp;
1993 hammer2_chain_t *chain;
1997 * Allocate a chain structure representing the existing media
1998 * entry. Resulting chain has one ref and is not locked.
2000 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2001 chain = hammer2_chain_alloc(hmp, NULL, bref);
2003 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2004 /* ref'd chain returned */
2007 * Flag that the chain is in the parent's blockmap so delete/flush
2008 * knows what to do with it.
2010 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2013 * Link the chain into its parent. A spinlock is required to safely
2014 * access the RBTREE, and it is possible to collide with another
2015 * hammer2_chain_get() operation because the caller might only hold
2016 * a shared lock on the parent.
2018 * NOTE: Get races can occur quite often when we distribute
2019 * asynchronous read-aheads across multiple threads.
2021 KKASSERT(parent->refs > 0);
2022 error = hammer2_chain_insert(parent, chain,
2023 HAMMER2_CHAIN_INSERT_SPIN |
2024 HAMMER2_CHAIN_INSERT_RACE,
2027 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2028 /*kprintf("chain %p get race\n", chain);*/
2029 hammer2_chain_drop(chain);
2032 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2036 * Return our new chain referenced but not locked, or NULL if
2043 * Lookup initialization/completion API
2046 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2048 hammer2_chain_ref(parent);
2049 if (flags & HAMMER2_LOOKUP_SHARED) {
2050 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2051 HAMMER2_RESOLVE_SHARED);
2053 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2059 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2062 hammer2_chain_unlock(parent);
2063 hammer2_chain_drop(parent);
2068 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
2070 hammer2_chain_t *oparent;
2071 hammer2_chain_t *nparent;
2074 * Be careful of order, oparent must be unlocked before nparent
2075 * is locked below to avoid a deadlock.
2078 hammer2_spin_ex(&oparent->core.spin);
2079 nparent = oparent->parent;
2080 if (nparent == NULL) {
2081 hammer2_spin_unex(&oparent->core.spin);
2082 panic("hammer2_chain_getparent: no parent");
2084 hammer2_chain_ref(nparent);
2085 hammer2_spin_unex(&oparent->core.spin);
2087 hammer2_chain_unlock(oparent);
2088 hammer2_chain_drop(oparent);
2092 hammer2_chain_lock(nparent, how);
2099 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2100 * (*parentp) typically points to an inode but can also point to a related
2101 * indirect block and this function will recurse upwards and find the inode
2104 * (*parentp) must be exclusively locked and referenced and can be an inode
2105 * or an existing indirect block within the inode.
2107 * On return (*parentp) will be modified to point at the deepest parent chain
2108 * element encountered during the search, as a helper for an insertion or
2109 * deletion. The new (*parentp) will be locked and referenced and the old
2110 * will be unlocked and dereferenced (no change if they are both the same).
2112 * The matching chain will be returned exclusively locked. If NOLOCK is
2113 * requested the chain will be returned only referenced. Note that the
2114 * parent chain must always be locked shared or exclusive, matching the
2115 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2116 * when NOLOCK is specified but that complicates matters if *parentp must
2117 * inherit the chain.
2119 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2120 * data pointer or can otherwise be in flux.
2122 * NULL is returned if no match was found, but (*parentp) will still
2123 * potentially be adjusted.
2125 * If a fatal error occurs (typically an I/O error), a dummy chain is
2126 * returned with chain->error and error-identifying information set. This
2127 * chain will assert if you try to do anything fancy with it.
2129 * XXX Depending on where the error occurs we should allow continued iteration.
2131 * On return (*key_nextp) will point to an iterative value for key_beg.
2132 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2134 * This function will also recurse up the chain if the key is not within the
2135 * current parent's range. (*parentp) can never be set to NULL. An iteration
2136 * can simply allow (*parentp) to float inside the loop.
2138 * NOTE! chain->data is not always resolved. By default it will not be
2139 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2140 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2141 * BREF_TYPE_DATA as the device buffer can alias the logical file
2146 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2147 hammer2_key_t key_beg, hammer2_key_t key_end,
2148 int *cache_indexp, int flags)
2151 hammer2_chain_t *parent;
2152 hammer2_chain_t *chain;
2153 hammer2_blockref_t *base;
2154 hammer2_blockref_t *bref;
2155 hammer2_blockref_t bcopy;
2156 hammer2_key_t scan_beg;
2157 hammer2_key_t scan_end;
2159 int how_always = HAMMER2_RESOLVE_ALWAYS;
2160 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2163 int maxloops = 300000;
2167 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2168 how_maybe = how_always;
2169 how = HAMMER2_RESOLVE_ALWAYS;
2170 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2171 how = HAMMER2_RESOLVE_NEVER;
2173 how = HAMMER2_RESOLVE_MAYBE;
2175 if (flags & HAMMER2_LOOKUP_SHARED) {
2176 how_maybe |= HAMMER2_RESOLVE_SHARED;
2177 how_always |= HAMMER2_RESOLVE_SHARED;
2178 how |= HAMMER2_RESOLVE_SHARED;
2182 * Recurse (*parentp) upward if necessary until the parent completely
2183 * encloses the key range or we hit the inode.
2185 * Handle races against the flusher deleting indirect nodes on its
2186 * way back up by continuing to recurse upward past the deletion.
2191 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2192 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2193 scan_beg = parent->bref.key;
2194 scan_end = scan_beg +
2195 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2196 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT ||
2197 (parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2198 if (key_beg >= scan_beg && key_end <= scan_end)
2201 parent = hammer2_chain_getparent(parentp, how_maybe);
2206 if (--maxloops == 0)
2207 panic("hammer2_chain_lookup: maxloops");
2209 * Locate the blockref array. Currently we do a fully associative
2210 * search through the array.
2212 switch(parent->bref.type) {
2213 case HAMMER2_BREF_TYPE_INODE:
2215 * Special shortcut for embedded data returns the inode
2216 * itself. Callers must detect this condition and access
2217 * the embedded data (the strategy code does this for us).
2219 * This is only applicable to regular files and softlinks.
2221 * We need a second lock on parent. Since we already have
2222 * a lock we must pass LOCKAGAIN to prevent unexpected
2223 * blocking (we don't want to block on a second shared
2224 * ref if an exclusive lock is pending)
2226 if (parent->data->ipdata.meta.op_flags &
2227 HAMMER2_OPFLAG_DIRECTDATA) {
2228 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2230 *key_nextp = key_end + 1;
2233 hammer2_chain_ref(parent);
2234 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2235 hammer2_chain_lock(parent,
2237 HAMMER2_RESOLVE_LOCKAGAIN);
2238 *key_nextp = key_end + 1;
2241 base = &parent->data->ipdata.u.blockset.blockref[0];
2242 count = HAMMER2_SET_COUNT;
2244 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2245 case HAMMER2_BREF_TYPE_INDIRECT:
2247 * Handle MATCHIND on the parent
2249 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2250 scan_beg = parent->bref.key;
2251 scan_end = scan_beg +
2252 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2253 if (key_beg == scan_beg && key_end == scan_end) {
2255 hammer2_chain_ref(chain);
2256 hammer2_chain_lock(chain, how_maybe);
2257 *key_nextp = scan_end + 1;
2263 * Optimize indirect blocks in the INITIAL state to avoid
2266 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2269 if (parent->data == NULL) {
2270 kprintf("parent->data is NULL %p\n", parent);
2272 tsleep(parent, 0, "xxx", 0);
2274 base = &parent->data->npdata[0];
2276 count = parent->bytes / sizeof(hammer2_blockref_t);
2278 case HAMMER2_BREF_TYPE_VOLUME:
2279 base = &parent->data->voldata.sroot_blockset.blockref[0];
2280 count = HAMMER2_SET_COUNT;
2282 case HAMMER2_BREF_TYPE_FREEMAP:
2283 base = &parent->data->blkset.blockref[0];
2284 count = HAMMER2_SET_COUNT;
2287 kprintf("hammer2_chain_lookup: unrecognized "
2288 "blockref(B) type: %d",
2291 tsleep(&base, 0, "dead", 0);
2292 panic("hammer2_chain_lookup: unrecognized "
2293 "blockref(B) type: %d",
2295 base = NULL; /* safety */
2296 count = 0; /* safety */
2301 * Merged scan to find next candidate.
2303 * hammer2_base_*() functions require the parent->core.live_* fields
2304 * to be synchronized.
2306 * We need to hold the spinlock to access the block array and RB tree
2307 * and to interlock chain creation.
2309 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2310 hammer2_chain_countbrefs(parent, base, count);
2317 hammer2_spin_ex(&parent->core.spin);
2318 chain = hammer2_combined_find(parent, base, count,
2319 cache_indexp, key_nextp,
2322 generation = parent->core.generation;
2327 * Exhausted parent chain, iterate.
2331 hammer2_spin_unex(&parent->core.spin);
2332 if (key_beg == key_end) /* short cut single-key case */
2336 * Stop if we reached the end of the iteration.
2338 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2339 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2344 * Calculate next key, stop if we reached the end of the
2345 * iteration, otherwise go up one level and loop.
2347 key_beg = parent->bref.key +
2348 ((hammer2_key_t)1 << parent->bref.keybits);
2349 if (key_beg == 0 || key_beg > key_end)
2351 parent = hammer2_chain_getparent(parentp, how_maybe);
2356 * Selected from blockref or in-memory chain.
2358 if (chain == NULL) {
2361 hammer2_spin_unex(&parent->core.spin);
2362 chain = hammer2_chain_get(parent, generation,
2364 if (chain == NULL) {
2366 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2367 parent, key_beg, key_end);
2371 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2372 hammer2_chain_drop(chain);
2377 hammer2_chain_ref(chain);
2378 hammer2_spin_unex(&parent->core.spin);
2383 * chain is referenced but not locked. We must lock the chain
2384 * to obtain definitive state.
2386 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2387 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2388 hammer2_chain_lock(chain, how_maybe);
2390 hammer2_chain_lock(chain, how);
2392 KKASSERT(chain->parent == parent);
2396 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2398 * NOTE: Chain's key range is not relevant as there might be
2399 * one-offs within the range that are not deleted.
2401 * NOTE: Lookups can race delete-duplicate because
2402 * delete-duplicate does not lock the parent's core
2403 * (they just use the spinlock on the core).
2405 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2406 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2407 chain->bref.data_off, chain->bref.type,
2409 hammer2_chain_unlock(chain);
2410 hammer2_chain_drop(chain);
2411 key_beg = *key_nextp;
2412 if (key_beg == 0 || key_beg > key_end)
2419 * If the chain element is an indirect block it becomes the new
2420 * parent and we loop on it. We must maintain our top-down locks
2421 * to prevent the flusher from interfering (i.e. doing a
2422 * delete-duplicate and leaving us recursing down a deleted chain).
2424 * The parent always has to be locked with at least RESOLVE_MAYBE
2425 * so we can access its data. It might need a fixup if the caller
2426 * passed incompatible flags. Be careful not to cause a deadlock
2427 * as a data-load requires an exclusive lock.
2429 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2430 * range is within the requested key range we return the indirect
2431 * block and do NOT loop. This is usually only used to acquire
2434 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2435 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2436 hammer2_chain_unlock(parent);
2437 hammer2_chain_drop(parent);
2438 *parentp = parent = chain;
2444 * All done, return the chain.
2446 * If the caller does not want a locked chain, replace the lock with
2447 * a ref. Perhaps this can eventually be optimized to not obtain the
2448 * lock in the first place for situations where the data does not
2449 * need to be resolved.
2452 if (flags & HAMMER2_LOOKUP_NOLOCK)
2453 hammer2_chain_unlock(chain);
2461 * After having issued a lookup we can iterate all matching keys.
2463 * If chain is non-NULL we continue the iteration from just after it's index.
2465 * If chain is NULL we assume the parent was exhausted and continue the
2466 * iteration at the next parent.
2468 * If a fatal error occurs (typically an I/O error), a dummy chain is
2469 * returned with chain->error and error-identifying information set. This
2470 * chain will assert if you try to do anything fancy with it.
2472 * XXX Depending on where the error occurs we should allow continued iteration.
2474 * parent must be locked on entry and remains locked throughout. chain's
2475 * lock status must match flags. Chain is always at least referenced.
2477 * WARNING! The MATCHIND flag does not apply to this function.
2480 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2481 hammer2_key_t *key_nextp,
2482 hammer2_key_t key_beg, hammer2_key_t key_end,
2483 int *cache_indexp, int flags)
2485 hammer2_chain_t *parent;
2489 * Calculate locking flags for upward recursion.
2491 how_maybe = HAMMER2_RESOLVE_MAYBE;
2492 if (flags & HAMMER2_LOOKUP_SHARED)
2493 how_maybe |= HAMMER2_RESOLVE_SHARED;
2498 * Calculate the next index and recalculate the parent if necessary.
2501 key_beg = chain->bref.key +
2502 ((hammer2_key_t)1 << chain->bref.keybits);
2503 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2504 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2505 hammer2_chain_unlock(chain);
2507 hammer2_chain_drop(chain);
2510 * chain invalid past this point, but we can still do a
2511 * pointer comparison w/parent.
2513 * Any scan where the lookup returned degenerate data embedded
2514 * in the inode has an invalid index and must terminate.
2516 if (chain == parent)
2518 if (key_beg == 0 || key_beg > key_end)
2521 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2522 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2524 * We reached the end of the iteration.
2529 * Continue iteration with next parent unless the current
2530 * parent covers the range.
2532 * (This also handles the case of a deleted, empty indirect
2535 key_beg = parent->bref.key +
2536 ((hammer2_key_t)1 << parent->bref.keybits);
2537 if (key_beg == 0 || key_beg > key_end)
2539 parent = hammer2_chain_getparent(parentp, how_maybe);
2545 return (hammer2_chain_lookup(parentp, key_nextp,
2547 cache_indexp, flags));
2551 * The raw scan function is similar to lookup/next but does not seek to a key.
2552 * Blockrefs are iterated via first_bref = (parent, NULL) and
2553 * next_chain = (parent, bref).
2555 * The passed-in parent must be locked and its data resolved. The function
2556 * nominally returns a locked and referenced *chainp != NULL for chains
2557 * the caller might need to recurse on (and will dipose of any *chainp passed
2558 * in). The caller must check the chain->bref.type either way.
2560 * *chainp is not set for leaf elements.
2562 * This function takes a pointer to a stack-based bref structure whos
2563 * contents is updated for each iteration. The same pointer is returned,
2564 * or NULL when the iteration is complete. *firstp must be set to 1 for
2565 * the first ieration. This function will set it to 0.
2567 hammer2_blockref_t *
2568 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2569 hammer2_blockref_t *bref, int *firstp,
2570 int *cache_indexp, int flags)
2573 hammer2_blockref_t *base;
2574 hammer2_blockref_t *bref_ptr;
2576 hammer2_key_t next_key;
2577 hammer2_chain_t *chain = NULL;
2579 int how_always = HAMMER2_RESOLVE_ALWAYS;
2580 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2583 int maxloops = 300000;
2588 * Scan flags borrowed from lookup.
2590 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2591 how_maybe = how_always;
2592 how = HAMMER2_RESOLVE_ALWAYS;
2593 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2594 how = HAMMER2_RESOLVE_NEVER;
2596 how = HAMMER2_RESOLVE_MAYBE;
2598 if (flags & HAMMER2_LOOKUP_SHARED) {
2599 how_maybe |= HAMMER2_RESOLVE_SHARED;
2600 how_always |= HAMMER2_RESOLVE_SHARED;
2601 how |= HAMMER2_RESOLVE_SHARED;
2605 * Calculate key to locate first/next element, unlocking the previous
2606 * element as we go. Be careful, the key calculation can overflow.
2608 * (also reset bref to NULL)
2614 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2615 if ((chain = *chainp) != NULL) {
2617 hammer2_chain_unlock(chain);
2618 hammer2_chain_drop(chain);
2628 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2629 if (--maxloops == 0)
2630 panic("hammer2_chain_scan: maxloops");
2632 * Locate the blockref array. Currently we do a fully associative
2633 * search through the array.
2635 switch(parent->bref.type) {
2636 case HAMMER2_BREF_TYPE_INODE:
2638 * An inode with embedded data has no sub-chains.
2640 * WARNING! Bulk scan code may pass a static chain marked
2641 * as BREF_TYPE_INODE with a copy of the volume
2642 * root blockset to snapshot the volume.
2644 if (parent->data->ipdata.meta.op_flags &
2645 HAMMER2_OPFLAG_DIRECTDATA) {
2649 base = &parent->data->ipdata.u.blockset.blockref[0];
2650 count = HAMMER2_SET_COUNT;
2652 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2653 case HAMMER2_BREF_TYPE_INDIRECT:
2655 * Optimize indirect blocks in the INITIAL state to avoid
2658 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2661 if (parent->data == NULL)
2662 panic("parent->data is NULL");
2663 base = &parent->data->npdata[0];
2665 count = parent->bytes / sizeof(hammer2_blockref_t);
2667 case HAMMER2_BREF_TYPE_VOLUME:
2668 base = &parent->data->voldata.sroot_blockset.blockref[0];
2669 count = HAMMER2_SET_COUNT;
2671 case HAMMER2_BREF_TYPE_FREEMAP:
2672 base = &parent->data->blkset.blockref[0];
2673 count = HAMMER2_SET_COUNT;
2676 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2678 base = NULL; /* safety */
2679 count = 0; /* safety */
2683 * Merged scan to find next candidate.
2685 * hammer2_base_*() functions require the parent->core.live_* fields
2686 * to be synchronized.
2688 * We need to hold the spinlock to access the block array and RB tree
2689 * and to interlock chain creation.
2691 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2692 hammer2_chain_countbrefs(parent, base, count);
2696 hammer2_spin_ex(&parent->core.spin);
2697 chain = hammer2_combined_find(parent, base, count,
2698 cache_indexp, &next_key,
2699 key, HAMMER2_KEY_MAX,
2701 generation = parent->core.generation;
2704 * Exhausted parent chain, we're done.
2706 if (bref_ptr == NULL) {
2707 hammer2_spin_unex(&parent->core.spin);
2708 KKASSERT(chain == NULL);
2714 * Copy into the supplied stack-based blockref.
2719 * Selected from blockref or in-memory chain.
2721 if (chain == NULL) {
2722 switch(bref->type) {
2723 case HAMMER2_BREF_TYPE_INODE:
2724 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2725 case HAMMER2_BREF_TYPE_INDIRECT:
2726 case HAMMER2_BREF_TYPE_VOLUME:
2727 case HAMMER2_BREF_TYPE_FREEMAP:
2729 * Recursion, always get the chain
2731 hammer2_spin_unex(&parent->core.spin);
2732 chain = hammer2_chain_get(parent, generation, bref);
2733 if (chain == NULL) {
2734 kprintf("retry scan parent %p keys %016jx\n",
2738 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2739 hammer2_chain_drop(chain);
2746 * No recursion, do not waste time instantiating
2747 * a chain, just iterate using the bref.
2749 hammer2_spin_unex(&parent->core.spin);
2754 * Recursion or not we need the chain in order to supply
2757 hammer2_chain_ref(chain);
2758 hammer2_spin_unex(&parent->core.spin);
2762 * chain is referenced but not locked. We must lock the chain
2763 * to obtain definitive state.
2766 hammer2_chain_lock(chain, how);
2769 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2771 * NOTE: chain's key range is not relevant as there might be
2772 * one-offs within the range that are not deleted.
2774 * NOTE: XXX this could create problems with scans used in
2775 * situations other than mount-time recovery.
2777 * NOTE: Lookups can race delete-duplicate because
2778 * delete-duplicate does not lock the parent's core
2779 * (they just use the spinlock on the core).
2781 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2782 hammer2_chain_unlock(chain);
2783 hammer2_chain_drop(chain);
2796 * All done, return the bref or NULL, supply chain if necessary.
2804 * Create and return a new hammer2 system memory structure of the specified
2805 * key, type and size and insert it under (*parentp). This is a full
2806 * insertion, based on the supplied key/keybits, and may involve creating
2807 * indirect blocks and moving other chains around via delete/duplicate.
2809 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2810 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2811 * FULL. This typically means that the caller is creating the chain after
2812 * doing a hammer2_chain_lookup().
2814 * (*parentp) must be exclusive locked and may be replaced on return
2815 * depending on how much work the function had to do.
2817 * (*parentp) must not be errored or this function will assert.
2819 * (*chainp) usually starts out NULL and returns the newly created chain,
2820 * but if the caller desires the caller may allocate a disconnected chain
2821 * and pass it in instead.
2823 * This function should NOT be used to insert INDIRECT blocks. It is
2824 * typically used to create/insert inodes and data blocks.
2826 * Caller must pass-in an exclusively locked parent the new chain is to
2827 * be inserted under, and optionally pass-in a disconnected, exclusively
2828 * locked chain to insert (else we create a new chain). The function will
2829 * adjust (*parentp) as necessary, create or connect the chain, and
2830 * return an exclusively locked chain in *chainp.
2832 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2833 * and will be reassigned.
2836 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2837 hammer2_pfs_t *pmp, int methods,
2838 hammer2_key_t key, int keybits, int type, size_t bytes,
2839 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2842 hammer2_chain_t *chain;
2843 hammer2_chain_t *parent;
2844 hammer2_blockref_t *base;
2845 hammer2_blockref_t dummy;
2849 int maxloops = 300000;
2852 * Topology may be crossing a PFS boundary.
2855 KKASSERT(hammer2_mtx_owned(&parent->lock));
2856 KKASSERT(parent->error == 0);
2860 if (chain == NULL) {
2862 * First allocate media space and construct the dummy bref,
2863 * then allocate the in-memory chain structure. Set the
2864 * INITIAL flag for fresh chains which do not have embedded
2867 * XXX for now set the check mode of the child based on
2868 * the parent or, if the parent is an inode, the
2869 * specification in the inode.
2871 bzero(&dummy, sizeof(dummy));
2874 dummy.keybits = keybits;
2875 dummy.data_off = hammer2_getradix(bytes);
2878 * Inherit methods from parent by default. Primarily used
2879 * for BREF_TYPE_DATA. Non-data types *must* be set to
2880 * a non-NONE check algorithm.
2883 dummy.methods = parent->bref.methods;
2885 dummy.methods = (uint8_t)methods;
2887 if (type != HAMMER2_BREF_TYPE_DATA &&
2888 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
2890 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
2893 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2896 * Lock the chain manually, chain_lock will load the chain
2897 * which we do NOT want to do. (note: chain->refs is set
2898 * to 1 by chain_alloc() for us, but lockcnt is not).
2901 hammer2_mtx_ex(&chain->lock);
2903 ++curthread->td_tracker;
2906 * Set INITIAL to optimize I/O. The flag will generally be
2907 * processed when we call hammer2_chain_modify().
2909 * Recalculate bytes to reflect the actual media block
2910 * allocation. Handle special case radix 0 == 0 bytes.
2912 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2914 bytes = (hammer2_off_t)1 << bytes;
2915 chain->bytes = bytes;
2918 case HAMMER2_BREF_TYPE_VOLUME:
2919 case HAMMER2_BREF_TYPE_FREEMAP:
2920 panic("hammer2_chain_create: called with volume type");
2922 case HAMMER2_BREF_TYPE_INDIRECT:
2923 panic("hammer2_chain_create: cannot be used to"
2924 "create indirect block");
2926 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2927 panic("hammer2_chain_create: cannot be used to"
2928 "create freemap root or node");
2930 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2931 KKASSERT(bytes == sizeof(chain->data->bmdata));
2933 case HAMMER2_BREF_TYPE_DIRENT:
2934 case HAMMER2_BREF_TYPE_INODE:
2935 case HAMMER2_BREF_TYPE_DATA:
2938 * leave chain->data NULL, set INITIAL
2940 KKASSERT(chain->data == NULL);
2941 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2946 * We are reattaching a previously deleted chain, possibly
2947 * under a new parent and possibly with a new key/keybits.
2948 * The chain does not have to be in a modified state. The
2949 * UPDATE flag will be set later on in this routine.
2951 * Do NOT mess with the current state of the INITIAL flag.
2953 chain->bref.key = key;
2954 chain->bref.keybits = keybits;
2955 if (chain->flags & HAMMER2_CHAIN_DELETED)
2956 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2957 KKASSERT(chain->parent == NULL);
2959 if (flags & HAMMER2_INSERT_PFSROOT)
2960 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2962 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2965 * Calculate how many entries we have in the blockref array and
2966 * determine if an indirect block is required.
2969 if (--maxloops == 0)
2970 panic("hammer2_chain_create: maxloops");
2972 switch(parent->bref.type) {
2973 case HAMMER2_BREF_TYPE_INODE:
2974 if ((parent->data->ipdata.meta.op_flags &
2975 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2976 kprintf("hammer2: parent set for direct-data! "
2977 "pkey=%016jx ckey=%016jx\n",
2981 KKASSERT((parent->data->ipdata.meta.op_flags &
2982 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2983 KKASSERT(parent->data != NULL);
2984 base = &parent->data->ipdata.u.blockset.blockref[0];
2985 count = HAMMER2_SET_COUNT;
2987 case HAMMER2_BREF_TYPE_INDIRECT:
2988 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2989 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2992 base = &parent->data->npdata[0];
2993 count = parent->bytes / sizeof(hammer2_blockref_t);
2995 case HAMMER2_BREF_TYPE_VOLUME:
2996 KKASSERT(parent->data != NULL);
2997 base = &parent->data->voldata.sroot_blockset.blockref[0];
2998 count = HAMMER2_SET_COUNT;
3000 case HAMMER2_BREF_TYPE_FREEMAP:
3001 KKASSERT(parent->data != NULL);
3002 base = &parent->data->blkset.blockref[0];
3003 count = HAMMER2_SET_COUNT;
3006 panic("hammer2_chain_create: unrecognized blockref type: %d",
3014 * Make sure we've counted the brefs
3016 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3017 hammer2_chain_countbrefs(parent, base, count);
3019 KASSERT(parent->core.live_count >= 0 &&
3020 parent->core.live_count <= count,
3021 ("bad live_count %d/%d (%02x, %d)",
3022 parent->core.live_count, count,
3023 parent->bref.type, parent->bytes));
3026 * If no free blockref could be found we must create an indirect
3027 * block and move a number of blockrefs into it. With the parent
3028 * locked we can safely lock each child in order to delete+duplicate
3029 * it without causing a deadlock.
3031 * This may return the new indirect block or the old parent depending
3032 * on where the key falls. NULL is returned on error.
3034 if (parent->core.live_count == count) {
3035 hammer2_chain_t *nparent;
3037 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3038 mtid, type, &error);
3039 if (nparent == NULL) {
3041 hammer2_chain_drop(chain);
3045 if (parent != nparent) {
3046 hammer2_chain_unlock(parent);
3047 hammer2_chain_drop(parent);
3048 parent = *parentp = nparent;
3053 if (chain->flags & HAMMER2_CHAIN_DELETED)
3054 kprintf("Inserting deleted chain @%016jx\n",
3058 * Link the chain into its parent.
3060 if (chain->parent != NULL)
3061 panic("hammer2: hammer2_chain_create: chain already connected");
3062 KKASSERT(chain->parent == NULL);
3063 hammer2_chain_insert(parent, chain,
3064 HAMMER2_CHAIN_INSERT_SPIN |
3065 HAMMER2_CHAIN_INSERT_LIVE,
3070 * Mark the newly created chain modified. This will cause
3071 * UPDATE to be set and process the INITIAL flag.
3073 * Device buffers are not instantiated for DATA elements
3074 * as these are handled by logical buffers.
3076 * Indirect and freemap node indirect blocks are handled
3077 * by hammer2_chain_create_indirect() and not by this
3080 * Data for all other bref types is expected to be
3081 * instantiated (INODE, LEAF).
3083 switch(chain->bref.type) {
3084 case HAMMER2_BREF_TYPE_DATA:
3085 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3086 case HAMMER2_BREF_TYPE_DIRENT:
3087 case HAMMER2_BREF_TYPE_INODE:
3088 hammer2_chain_modify(chain, mtid, dedup_off,
3089 HAMMER2_MODIFY_OPTDATA);
3093 * Remaining types are not supported by this function.
3094 * In particular, INDIRECT and LEAF_NODE types are
3095 * handled by create_indirect().
3097 panic("hammer2_chain_create: bad type: %d",
3104 * When reconnecting a chain we must set UPDATE and
3105 * setflush so the flush recognizes that it must update
3106 * the bref in the parent.
3108 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3109 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3113 * We must setflush(parent) to ensure that it recurses through to
3114 * chain. setflush(chain) might not work because ONFLUSH is possibly
3115 * already set in the chain (so it won't recurse up to set it in the
3118 hammer2_chain_setflush(parent);
3127 * Move the chain from its old parent to a new parent. The chain must have
3128 * already been deleted or already disconnected (or never associated) with
3129 * a parent. The chain is reassociated with the new parent and the deleted
3130 * flag will be cleared (no longer deleted). The chain's modification state
3133 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3134 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3135 * FULL. This typically means that the caller is creating the chain after
3136 * doing a hammer2_chain_lookup().
3138 * A non-NULL bref is typically passed when key and keybits must be overridden.
3139 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3140 * from a passed-in bref and uses the old chain's bref for everything else.
3142 * Neither (parent) or (chain) can be errored.
3144 * If (parent) is non-NULL then the chain is inserted under the parent.
3146 * If (parent) is NULL then the newly duplicated chain is not inserted
3147 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3148 * passing into hammer2_chain_create() after this function returns).
3150 * WARNING! This function calls create which means it can insert indirect
3151 * blocks. This can cause other unrelated chains in the parent to
3152 * be moved to a newly inserted indirect block in addition to the
3156 hammer2_chain_rename(hammer2_blockref_t *bref,
3157 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3158 hammer2_tid_t mtid, int flags)
3161 hammer2_chain_t *parent;
3165 * WARNING! We should never resolve DATA to device buffers
3166 * (XXX allow it if the caller did?), and since
3167 * we currently do not have the logical buffer cache
3168 * buffer in-hand to fix its cached physical offset
3169 * we also force the modify code to not COW it. XXX
3172 KKASSERT(chain->parent == NULL);
3173 KKASSERT(chain->error == 0);
3176 * Now create a duplicate of the chain structure, associating
3177 * it with the same core, making it the same size, pointing it
3178 * to the same bref (the same media block).
3180 * NOTE: Handle special radix == 0 case (means 0 bytes).
3183 bref = &chain->bref;
3184 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3186 bytes = (hammer2_off_t)1 << bytes;
3189 * If parent is not NULL the duplicated chain will be entered under
3190 * the parent and the UPDATE bit set to tell flush to update
3193 * We must setflush(parent) to ensure that it recurses through to
3194 * chain. setflush(chain) might not work because ONFLUSH is possibly
3195 * already set in the chain (so it won't recurse up to set it in the
3198 * Having both chains locked is extremely important for atomicy.
3200 if (parentp && (parent = *parentp) != NULL) {
3201 KKASSERT(hammer2_mtx_owned(&parent->lock));
3202 KKASSERT(parent->refs > 0);
3203 KKASSERT(parent->error == 0);
3205 hammer2_chain_create(parentp, &chain,
3206 chain->pmp, HAMMER2_METH_DEFAULT,
3207 bref->key, bref->keybits, bref->type,
3208 chain->bytes, mtid, 0, flags);
3209 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3210 hammer2_chain_setflush(*parentp);
3215 * Helper function for deleting chains.
3217 * The chain is removed from the live view (the RBTREE) as well as the parent's
3218 * blockmap. Both chain and its parent must be locked.
3220 * parent may not be errored. chain can be errored.
3223 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3224 hammer2_tid_t mtid, int flags)
3228 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3229 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3230 KKASSERT(chain->parent == parent);
3233 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3235 * Chain is blockmapped, so there must be a parent.
3236 * Atomically remove the chain from the parent and remove
3237 * the blockmap entry. The parent must be set modified
3238 * to remove the blockmap entry.
3240 hammer2_blockref_t *base;
3243 KKASSERT(parent != NULL);
3244 KKASSERT(parent->error == 0);
3245 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3246 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3249 * Calculate blockmap pointer
3251 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3252 hammer2_spin_ex(&parent->core.spin);
3254 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3255 atomic_add_int(&parent->core.live_count, -1);
3256 ++parent->core.generation;
3257 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3258 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3259 --parent->core.chain_count;
3260 chain->parent = NULL;
3262 switch(parent->bref.type) {
3263 case HAMMER2_BREF_TYPE_INODE:
3265 * Access the inode's block array. However, there
3266 * is no block array if the inode is flagged
3270 (parent->data->ipdata.meta.op_flags &
3271 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3273 &parent->data->ipdata.u.blockset.blockref[0];
3277 count = HAMMER2_SET_COUNT;
3279 case HAMMER2_BREF_TYPE_INDIRECT:
3280 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3282 base = &parent->data->npdata[0];
3285 count = parent->bytes / sizeof(hammer2_blockref_t);
3287 case HAMMER2_BREF_TYPE_VOLUME:
3288 base = &parent->data->voldata.
3289 sroot_blockset.blockref[0];
3290 count = HAMMER2_SET_COUNT;
3292 case HAMMER2_BREF_TYPE_FREEMAP:
3293 base = &parent->data->blkset.blockref[0];
3294 count = HAMMER2_SET_COUNT;
3299 panic("hammer2_flush_pass2: "
3300 "unrecognized blockref type: %d",
3305 * delete blockmapped chain from its parent.
3307 * The parent is not affected by any statistics in chain
3308 * which are pending synchronization. That is, there is
3309 * nothing to undo in the parent since they have not yet
3310 * been incorporated into the parent.
3312 * The parent is affected by statistics stored in inodes.
3313 * Those have already been synchronized, so they must be
3314 * undone. XXX split update possible w/delete in middle?
3317 int cache_index = -1;
3318 hammer2_base_delete(parent, base, count,
3319 &cache_index, chain);
3321 hammer2_spin_unex(&parent->core.spin);
3322 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3324 * Chain is not blockmapped but a parent is present.
3325 * Atomically remove the chain from the parent. There is
3326 * no blockmap entry to remove.
3328 * Because chain was associated with a parent but not
3329 * synchronized, the chain's *_count_up fields contain
3330 * inode adjustment statistics which must be undone.
3332 hammer2_spin_ex(&parent->core.spin);
3333 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3334 atomic_add_int(&parent->core.live_count, -1);
3335 ++parent->core.generation;
3336 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3337 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3338 --parent->core.chain_count;
3339 chain->parent = NULL;
3340 hammer2_spin_unex(&parent->core.spin);
3343 * Chain is not blockmapped and has no parent. This
3344 * is a degenerate case.
3346 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3351 * Create an indirect block that covers one or more of the elements in the
3352 * current parent. Either returns the existing parent with no locking or
3353 * ref changes or returns the new indirect block locked and referenced
3354 * and leaving the original parent lock/ref intact as well.
3356 * If an error occurs, NULL is returned and *errorp is set to the error.
3358 * The returned chain depends on where the specified key falls.
3360 * The key/keybits for the indirect mode only needs to follow three rules:
3362 * (1) That all elements underneath it fit within its key space and
3364 * (2) That all elements outside it are outside its key space.
3366 * (3) When creating the new indirect block any elements in the current
3367 * parent that fit within the new indirect block's keyspace must be
3368 * moved into the new indirect block.
3370 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3371 * keyspace the the current parent, but lookup/iteration rules will
3372 * ensure (and must ensure) that rule (2) for all parents leading up
3373 * to the nearest inode or the root volume header is adhered to. This
3374 * is accomplished by always recursing through matching keyspaces in
3375 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3377 * The current implementation calculates the current worst-case keyspace by
3378 * iterating the current parent and then divides it into two halves, choosing
3379 * whichever half has the most elements (not necessarily the half containing
3380 * the requested key).
3382 * We can also opt to use the half with the least number of elements. This
3383 * causes lower-numbered keys (aka logical file offsets) to recurse through
3384 * fewer indirect blocks and higher-numbered keys to recurse through more.
3385 * This also has the risk of not moving enough elements to the new indirect
3386 * block and being forced to create several indirect blocks before the element
3389 * Must be called with an exclusively locked parent.
3391 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3392 hammer2_key_t *keyp, int keybits,
3393 hammer2_blockref_t *base, int count);
3394 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3395 hammer2_key_t *keyp, int keybits,
3396 hammer2_blockref_t *base, int count,
3398 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3399 hammer2_key_t *keyp, int keybits,
3400 hammer2_blockref_t *base, int count,
3404 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3405 hammer2_key_t create_key, int create_bits,
3406 hammer2_tid_t mtid, int for_type, int *errorp)
3409 hammer2_blockref_t *base;
3410 hammer2_blockref_t *bref;
3411 hammer2_blockref_t bcopy;
3412 hammer2_chain_t *chain;
3413 hammer2_chain_t *ichain;
3414 hammer2_chain_t dummy;
3415 hammer2_key_t key = create_key;
3416 hammer2_key_t key_beg;
3417 hammer2_key_t key_end;
3418 hammer2_key_t key_next;
3419 int keybits = create_bits;
3427 int maxloops = 300000;
3430 * Calculate the base blockref pointer or NULL if the chain
3431 * is known to be empty. We need to calculate the array count
3432 * for RB lookups either way.
3436 KKASSERT(hammer2_mtx_owned(&parent->lock));
3438 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3439 base = hammer2_chain_base_and_count(parent, &count);
3442 * dummy used in later chain allocation (no longer used for lookups).
3444 bzero(&dummy, sizeof(dummy));
3447 * How big should our new indirect block be? It has to be at least
3448 * as large as its parent for splits to work properly.
3450 * The freemap uses a specific indirect block size. The number of
3451 * levels are built dynamically and ultimately depend on the size
3452 * volume. Because freemap blocks are taken from the reserved areas
3453 * of the volume our goal is efficiency (fewer levels) and not so
3454 * much to save disk space.
3456 * The first indirect block level for a directory usually uses
3457 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3458 * the hash mechanism, this typically gives us a nominal
3459 * 32 * 4 entries with one level of indirection.
3461 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3462 * indirect blocks. The initial 4 entries in the inode gives us
3463 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3464 * of indirection gives us 137GB, and so forth. H2 can support
3465 * huge file sizes but they are not typical, so we try to stick
3466 * with compactness and do not use a larger indirect block size.
3468 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3469 * due to the way indirect blocks are created this usually winds
3470 * up being extremely inefficient for small files. Even though
3471 * 16KB requires more levels of indirection for very large files,
3472 * the 16KB records can be ganged together into 64KB DIOs.
3474 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3475 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3476 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3477 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3478 if (parent->data->ipdata.meta.type ==
3479 HAMMER2_OBJTYPE_DIRECTORY)
3480 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3482 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3485 nbytes = HAMMER2_IND_BYTES_NOM;
3487 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3488 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3489 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3490 nbytes = count * sizeof(hammer2_blockref_t);
3492 ncount = nbytes / sizeof(hammer2_blockref_t);
3495 * When creating an indirect block for a freemap node or leaf
3496 * the key/keybits must be fitted to static radix levels because
3497 * particular radix levels use particular reserved blocks in the
3500 * This routine calculates the key/radix of the indirect block
3501 * we need to create, and whether it is on the high-side or the
3505 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3506 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3507 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3510 case HAMMER2_BREF_TYPE_DATA:
3511 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3512 base, count, ncount);
3514 case HAMMER2_BREF_TYPE_DIRENT:
3515 case HAMMER2_BREF_TYPE_INODE:
3516 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3517 base, count, ncount);
3520 panic("illegal indirect block for bref type %d", for_type);
3525 * Normalize the key for the radix being represented, keeping the
3526 * high bits and throwing away the low bits.
3528 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3531 * Ok, create our new indirect block
3533 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3534 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3535 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3537 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3539 dummy.bref.key = key;
3540 dummy.bref.keybits = keybits;
3541 dummy.bref.data_off = hammer2_getradix(nbytes);
3542 dummy.bref.methods =
3543 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3544 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3546 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3547 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3548 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3549 /* ichain has one ref at this point */
3552 * We have to mark it modified to allocate its block, but use
3553 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3554 * it won't be acted upon by the flush code.
3556 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3559 * Iterate the original parent and move the matching brefs into
3560 * the new indirect block.
3562 * XXX handle flushes.
3565 key_end = HAMMER2_KEY_MAX;
3566 key_next = 0; /* avoid gcc warnings */
3568 hammer2_spin_ex(&parent->core.spin);
3574 * Parent may have been modified, relocating its block array.
3575 * Reload the base pointer.
3577 base = hammer2_chain_base_and_count(parent, &count);
3579 if (++loops > 100000) {
3580 hammer2_spin_unex(&parent->core.spin);
3581 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3582 reason, parent, base, count, key_next);
3586 * NOTE: spinlock stays intact, returned chain (if not NULL)
3587 * is not referenced or locked which means that we
3588 * cannot safely check its flagged / deletion status
3591 chain = hammer2_combined_find(parent, base, count,
3592 &cache_index, &key_next,
3595 generation = parent->core.generation;
3598 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3601 * Skip keys that are not within the key/radix of the new
3602 * indirect block. They stay in the parent.
3604 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3605 (key ^ bref->key)) != 0) {
3606 goto next_key_spinlocked;
3610 * Load the new indirect block by acquiring the related
3611 * chains (potentially from media as it might not be
3612 * in-memory). Then move it to the new parent (ichain).
3614 * chain is referenced but not locked. We must lock the
3615 * chain to obtain definitive state.
3619 * Use chain already present in the RBTREE
3621 hammer2_chain_ref(chain);
3622 hammer2_spin_unex(&parent->core.spin);
3623 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3626 * Get chain for blockref element. _get returns NULL
3627 * on insertion race.
3630 hammer2_spin_unex(&parent->core.spin);
3631 chain = hammer2_chain_get(parent, generation, &bcopy);
3632 if (chain == NULL) {
3634 hammer2_spin_ex(&parent->core.spin);
3637 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3638 kprintf("REASON 2\n");
3640 hammer2_chain_drop(chain);
3641 hammer2_spin_ex(&parent->core.spin);
3644 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3648 * This is always live so if the chain has been deleted
3649 * we raced someone and we have to retry.
3651 * NOTE: Lookups can race delete-duplicate because
3652 * delete-duplicate does not lock the parent's core
3653 * (they just use the spinlock on the core).
3655 * (note reversed logic for this one)
3657 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3658 hammer2_chain_unlock(chain);
3659 hammer2_chain_drop(chain);
3664 * Shift the chain to the indirect block.
3666 * WARNING! No reason for us to load chain data, pass NOSTATS
3667 * to prevent delete/insert from trying to access
3668 * inode stats (and thus asserting if there is no
3669 * chain->data loaded).
3671 * WARNING! The (parent, chain) deletion may modify the parent
3672 * and invalidate the base pointer.
3674 hammer2_chain_delete(parent, chain, mtid, 0);
3675 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3676 hammer2_chain_unlock(chain);
3677 hammer2_chain_drop(chain);
3678 KKASSERT(parent->refs > 0);
3680 base = NULL; /* safety */
3682 hammer2_spin_ex(&parent->core.spin);
3683 next_key_spinlocked:
3684 if (--maxloops == 0)
3685 panic("hammer2_chain_create_indirect: maxloops");
3687 if (key_next == 0 || key_next > key_end)
3692 hammer2_spin_unex(&parent->core.spin);
3695 * Insert the new indirect block into the parent now that we've
3696 * cleared out some entries in the parent. We calculated a good
3697 * insertion index in the loop above (ichain->index).
3699 * We don't have to set UPDATE here because we mark ichain
3700 * modified down below (so the normal modified -> flush -> set-moved
3701 * sequence applies).
3703 * The insertion shouldn't race as this is a completely new block
3704 * and the parent is locked.
3706 base = NULL; /* safety, parent modify may change address */
3707 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3708 hammer2_chain_insert(parent, ichain,
3709 HAMMER2_CHAIN_INSERT_SPIN |
3710 HAMMER2_CHAIN_INSERT_LIVE,
3714 * Make sure flushes propogate after our manual insertion.
3716 hammer2_chain_setflush(ichain);
3717 hammer2_chain_setflush(parent);
3720 * Figure out what to return.
3722 if (~(((hammer2_key_t)1 << keybits) - 1) &
3723 (create_key ^ key)) {
3725 * Key being created is outside the key range,
3726 * return the original parent.
3728 hammer2_chain_unlock(ichain);
3729 hammer2_chain_drop(ichain);
3732 * Otherwise its in the range, return the new parent.
3733 * (leave both the new and old parent locked).
3742 * Freemap indirect blocks
3744 * Calculate the keybits and highside/lowside of the freemap node the
3745 * caller is creating.
3747 * This routine will specify the next higher-level freemap key/radix
3748 * representing the lowest-ordered set. By doing so, eventually all
3749 * low-ordered sets will be moved one level down.
3751 * We have to be careful here because the freemap reserves a limited
3752 * number of blocks for a limited number of levels. So we can't just
3753 * push indiscriminately.
3756 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3757 int keybits, hammer2_blockref_t *base, int count)
3759 hammer2_chain_t *chain;
3760 hammer2_blockref_t *bref;
3762 hammer2_key_t key_beg;
3763 hammer2_key_t key_end;
3764 hammer2_key_t key_next;
3768 int maxloops = 300000;
3776 * Calculate the range of keys in the array being careful to skip
3777 * slots which are overridden with a deletion.
3780 key_end = HAMMER2_KEY_MAX;
3782 hammer2_spin_ex(&parent->core.spin);
3785 if (--maxloops == 0) {
3786 panic("indkey_freemap shit %p %p:%d\n",
3787 parent, base, count);
3789 chain = hammer2_combined_find(parent, base, count,
3790 &cache_index, &key_next,
3801 * Skip deleted chains.
3803 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3804 if (key_next == 0 || key_next > key_end)
3811 * Use the full live (not deleted) element for the scan
3812 * iteration. HAMMER2 does not allow partial replacements.
3814 * XXX should be built into hammer2_combined_find().
3816 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3818 if (keybits > bref->keybits) {
3820 keybits = bref->keybits;
3821 } else if (keybits == bref->keybits && bref->key < key) {
3828 hammer2_spin_unex(&parent->core.spin);
3831 * Return the keybits for a higher-level FREEMAP_NODE covering
3835 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3836 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3838 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3839 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3841 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3842 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3844 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3845 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3847 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3848 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3850 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3851 panic("hammer2_chain_indkey_freemap: level too high");
3854 panic("hammer2_chain_indkey_freemap: bad radix");
3863 * File indirect blocks
3865 * Calculate the key/keybits for the indirect block to create by scanning
3866 * existing keys. The key being created is also passed in *keyp and can be
3867 * inside or outside the indirect block. Regardless, the indirect block
3868 * must hold at least two keys in order to guarantee sufficient space.
3870 * We use a modified version of the freemap's fixed radix tree, but taylored
3871 * for file data. Basically we configure an indirect block encompassing the
3875 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
3876 int keybits, hammer2_blockref_t *base, int count,
3879 hammer2_chain_t *chain;
3880 hammer2_blockref_t *bref;
3882 hammer2_key_t key_beg;
3883 hammer2_key_t key_end;
3884 hammer2_key_t key_next;
3889 int maxloops = 300000;
3897 * Calculate the range of keys in the array being careful to skip
3898 * slots which are overridden with a deletion.
3900 * Locate the smallest key.
3903 key_end = HAMMER2_KEY_MAX;
3905 hammer2_spin_ex(&parent->core.spin);
3908 if (--maxloops == 0) {
3909 panic("indkey_freemap shit %p %p:%d\n",
3910 parent, base, count);
3912 chain = hammer2_combined_find(parent, base, count,
3913 &cache_index, &key_next,
3924 * Skip deleted chains.
3926 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3927 if (key_next == 0 || key_next > key_end)
3934 * Use the full live (not deleted) element for the scan
3935 * iteration. HAMMER2 does not allow partial replacements.
3937 * XXX should be built into hammer2_combined_find().
3939 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3941 if (keybits > bref->keybits) {
3943 keybits = bref->keybits;
3944 } else if (keybits == bref->keybits && bref->key < key) {
3951 hammer2_spin_unex(&parent->core.spin);
3954 * Calculate the static keybits for a higher-level indirect block
3955 * that contains the key.
3960 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
3961 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
3963 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
3964 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
3966 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
3967 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
3970 panic("bad ncount %d\n", ncount);
3976 * The largest radix that can be returned for an indirect block is
3977 * 63 bits. (The largest practical indirect block radix is actually
3978 * 62 bits because the top-level inode or volume root contains four
3979 * entries, but allow 63 to be returned).
3984 return keybits + nradix;
3990 * Directory indirect blocks.
3992 * Covers both the inode index (directory of inodes), and directory contents
3993 * (filenames hardlinked to inodes).
3995 * Because directory keys are hashed we generally try to cut the space in
3996 * half. We accomodate the inode index (which tends to have linearly
3997 * increasing inode numbers) by ensuring that the keyspace is at least large
3998 * enough to fill up the indirect block being created.
4001 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4002 int keybits, hammer2_blockref_t *base, int count,
4005 hammer2_blockref_t *bref;
4006 hammer2_chain_t *chain;
4007 hammer2_key_t key_beg;
4008 hammer2_key_t key_end;
4009 hammer2_key_t key_next;
4015 int maxloops = 300000;
4018 * Shortcut if the parent is the inode. In this situation the
4019 * parent has 4+1 directory entries and we are creating an indirect
4020 * block capable of holding many more.
4022 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4031 * Calculate the range of keys in the array being careful to skip
4032 * slots which are overridden with a deletion.
4035 key_end = HAMMER2_KEY_MAX;
4037 hammer2_spin_ex(&parent->core.spin);
4040 if (--maxloops == 0) {
4041 panic("indkey_freemap shit %p %p:%d\n",
4042 parent, base, count);
4044 chain = hammer2_combined_find(parent, base, count,
4045 &cache_index, &key_next,
4058 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4059 if (key_next == 0 || key_next > key_end)
4066 * Use the full live (not deleted) element for the scan
4067 * iteration. HAMMER2 does not allow partial replacements.
4069 * XXX should be built into hammer2_combined_find().
4071 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4074 * Expand our calculated key range (key, keybits) to fit
4075 * the scanned key. nkeybits represents the full range
4076 * that we will later cut in half (two halves @ nkeybits - 1).
4079 if (nkeybits < bref->keybits) {
4080 if (bref->keybits > 64) {
4081 kprintf("bad bref chain %p bref %p\n",
4085 nkeybits = bref->keybits;
4087 while (nkeybits < 64 &&
4088 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4089 (key ^ bref->key)) != 0) {
4094 * If the new key range is larger we have to determine
4095 * which side of the new key range the existing keys fall
4096 * under by checking the high bit, then collapsing the
4097 * locount into the hicount or vise-versa.
4099 if (keybits != nkeybits) {
4100 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4111 * The newly scanned key will be in the lower half or the
4112 * upper half of the (new) key range.
4114 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4123 hammer2_spin_unex(&parent->core.spin);
4124 bref = NULL; /* now invalid (safety) */
4127 * Adjust keybits to represent half of the full range calculated
4128 * above (radix 63 max) for our new indirect block.
4133 * Expand keybits to hold at least ncount elements. ncount will be
4134 * a power of 2. This is to try to completely fill leaf nodes (at
4135 * least for keys which are not hashes).
4137 * We aren't counting 'in' or 'out', we are counting 'high side'
4138 * and 'low side' based on the bit at (1LL << keybits). We want
4139 * everything to be inside in these cases so shift it all to
4140 * the low or high side depending on the new high bit.
4142 while (((hammer2_key_t)1 << keybits) < ncount) {
4144 if (key & ((hammer2_key_t)1 << keybits)) {
4153 if (hicount > locount)
4154 key |= (hammer2_key_t)1 << keybits;
4156 key &= ~(hammer2_key_t)1 << keybits;
4166 * Directory indirect blocks.
4168 * Covers both the inode index (directory of inodes), and directory contents
4169 * (filenames hardlinked to inodes).
4171 * Because directory keys are hashed we generally try to cut the space in
4172 * half. We accomodate the inode index (which tends to have linearly
4173 * increasing inode numbers) by ensuring that the keyspace is at least large
4174 * enough to fill up the indirect block being created.
4177 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4178 int keybits, hammer2_blockref_t *base, int count,
4181 hammer2_blockref_t *bref;
4182 hammer2_chain_t *chain;
4183 hammer2_key_t key_beg;
4184 hammer2_key_t key_end;
4185 hammer2_key_t key_next;
4191 int maxloops = 300000;
4194 * Shortcut if the parent is the inode. In this situation the
4195 * parent has 4+1 directory entries and we are creating an indirect
4196 * block capable of holding many more.
4198 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4207 * Calculate the range of keys in the array being careful to skip
4208 * slots which are overridden with a deletion.
4211 key_end = HAMMER2_KEY_MAX;
4213 hammer2_spin_ex(&parent->core.spin);
4216 if (--maxloops == 0) {
4217 panic("indkey_freemap shit %p %p:%d\n",
4218 parent, base, count);
4220 chain = hammer2_combined_find(parent, base, count,
4221 &cache_index, &key_next,
4234 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4235 if (key_next == 0 || key_next > key_end)
4242 * Use the full live (not deleted) element for the scan
4243 * iteration. HAMMER2 does not allow partial replacements.
4245 * XXX should be built into hammer2_combined_find().
4247 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4250 * Expand our calculated key range (key, keybits) to fit
4251 * the scanned key. nkeybits represents the full range
4252 * that we will later cut in half (two halves @ nkeybits - 1).
4255 if (nkeybits < bref->keybits) {
4256 if (bref->keybits > 64) {
4257 kprintf("bad bref chain %p bref %p\n",
4261 nkeybits = bref->keybits;
4263 while (nkeybits < 64 &&
4264 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4265 (key ^ bref->key)) != 0) {
4270 * If the new key range is larger we have to determine
4271 * which side of the new key range the existing keys fall
4272 * under by checking the high bit, then collapsing the
4273 * locount into the hicount or vise-versa.
4275 if (keybits != nkeybits) {
4276 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4287 * The newly scanned key will be in the lower half or the
4288 * upper half of the (new) key range.
4290 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4299 hammer2_spin_unex(&parent->core.spin);
4300 bref = NULL; /* now invalid (safety) */
4303 * Adjust keybits to represent half of the full range calculated
4304 * above (radix 63 max) for our new indirect block.
4309 * Expand keybits to hold at least ncount elements. ncount will be
4310 * a power of 2. This is to try to completely fill leaf nodes (at
4311 * least for keys which are not hashes).
4313 * We aren't counting 'in' or 'out', we are counting 'high side'
4314 * and 'low side' based on the bit at (1LL << keybits). We want
4315 * everything to be inside in these cases so shift it all to
4316 * the low or high side depending on the new high bit.
4318 while (((hammer2_key_t)1 << keybits) < ncount) {
4320 if (key & ((hammer2_key_t)1 << keybits)) {
4329 if (hicount > locount)
4330 key |= (hammer2_key_t)1 << keybits;
4332 key &= ~(hammer2_key_t)1 << keybits;
4342 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4345 * Both parent and chain must be locked exclusively.
4347 * This function will modify the parent if the blockref requires removal
4348 * from the parent's block table.
4350 * This function is NOT recursive. Any entity already pushed into the
4351 * chain (such as an inode) may still need visibility into its contents,
4352 * as well as the ability to read and modify the contents. For example,
4353 * for an unlinked file which is still open.
4355 * Also note that the flusher is responsible for cleaning up empty
4359 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4360 hammer2_tid_t mtid, int flags)
4362 KKASSERT(hammer2_mtx_owned(&chain->lock));
4365 * Nothing to do if already marked.
4367 * We need the spinlock on the core whos RBTREE contains chain
4368 * to protect against races.
4370 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4371 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4372 chain->parent == parent);
4373 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4377 * Permanent deletions mark the chain as destroyed.
4379 if (flags & HAMMER2_DELETE_PERMANENT) {
4380 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4382 /* XXX might not be needed */
4383 hammer2_chain_setflush(chain);
4388 * Returns the index of the nearest element in the blockref array >= elm.
4389 * Returns (count) if no element could be found.
4391 * Sets *key_nextp to the next key for loop purposes but does not modify
4392 * it if the next key would be higher than the current value of *key_nextp.
4393 * Note that *key_nexp can overflow to 0, which should be tested by the
4396 * (*cache_indexp) is a heuristic and can be any value without effecting
4399 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4400 * held through the operation.
4403 hammer2_base_find(hammer2_chain_t *parent,
4404 hammer2_blockref_t *base, int count,
4405 int *cache_indexp, hammer2_key_t *key_nextp,
4406 hammer2_key_t key_beg, hammer2_key_t key_end)
4408 hammer2_blockref_t *scan;
4409 hammer2_key_t scan_end;
4414 * Require the live chain's already have their core's counted
4415 * so we can optimize operations.
4417 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4422 if (count == 0 || base == NULL)
4426 * Sequential optimization using *cache_indexp. This is the most
4429 * We can avoid trailing empty entries on live chains, otherwise
4430 * we might have to check the whole block array.
4434 limit = parent->core.live_zero;
4439 KKASSERT(i < count);
4445 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4452 * Search forwards, stop when we find a scan element which
4453 * encloses the key or until we know that there are no further
4457 if (scan->type != 0) {
4458 scan_end = scan->key +
4459 ((hammer2_key_t)1 << scan->keybits) - 1;
4460 if (scan->key > key_beg || scan_end >= key_beg)
4473 scan_end = scan->key +
4474 ((hammer2_key_t)1 << scan->keybits);
4475 if (scan_end && (*key_nextp > scan_end ||
4477 *key_nextp = scan_end;
4485 * Do a combined search and return the next match either from the blockref
4486 * array or from the in-memory chain. Sets *bresp to the returned bref in
4487 * both cases, or sets it to NULL if the search exhausted. Only returns
4488 * a non-NULL chain if the search matched from the in-memory chain.
4490 * When no in-memory chain has been found and a non-NULL bref is returned
4494 * The returned chain is not locked or referenced. Use the returned bref
4495 * to determine if the search exhausted or not. Iterate if the base find
4496 * is chosen but matches a deleted chain.
4498 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4499 * held through the operation.
4501 static hammer2_chain_t *
4502 hammer2_combined_find(hammer2_chain_t *parent,
4503 hammer2_blockref_t *base, int count,
4504 int *cache_indexp, hammer2_key_t *key_nextp,
4505 hammer2_key_t key_beg, hammer2_key_t key_end,
4506 hammer2_blockref_t **bresp)
4508 hammer2_blockref_t *bref;
4509 hammer2_chain_t *chain;
4513 * Lookup in block array and in rbtree.
4515 *key_nextp = key_end + 1;
4516 i = hammer2_base_find(parent, base, count, cache_indexp,
4517 key_nextp, key_beg, key_end);
4518 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4523 if (i == count && chain == NULL) {
4529 * Only chain matched.
4532 bref = &chain->bref;
4537 * Only blockref matched.
4539 if (chain == NULL) {
4545 * Both in-memory and blockref matched, select the nearer element.
4547 * If both are flush with the left-hand side or both are the
4548 * same distance away, select the chain. In this situation the
4549 * chain must have been loaded from the matching blockmap.
4551 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4552 chain->bref.key == base[i].key) {
4553 KKASSERT(chain->bref.key == base[i].key);
4554 bref = &chain->bref;
4559 * Select the nearer key
4561 if (chain->bref.key < base[i].key) {
4562 bref = &chain->bref;
4569 * If the bref is out of bounds we've exhausted our search.
4572 if (bref->key > key_end) {
4582 * Locate the specified block array element and delete it. The element
4585 * The spin lock on the related chain must be held.
4587 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4588 * need to be adjusted when we commit the media change.
4591 hammer2_base_delete(hammer2_chain_t *parent,
4592 hammer2_blockref_t *base, int count,
4593 int *cache_indexp, hammer2_chain_t *chain)
4595 hammer2_blockref_t *elm = &chain->bref;
4596 hammer2_blockref_t *scan;
4597 hammer2_key_t key_next;
4601 * Delete element. Expect the element to exist.
4603 * XXX see caller, flush code not yet sophisticated enough to prevent
4604 * re-flushed in some cases.
4606 key_next = 0; /* max range */
4607 i = hammer2_base_find(parent, base, count, cache_indexp,
4608 &key_next, elm->key, elm->key);
4610 if (i == count || scan->type == 0 ||
4611 scan->key != elm->key ||
4612 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4613 scan->keybits != elm->keybits)) {
4614 hammer2_spin_unex(&parent->core.spin);
4615 panic("delete base %p element not found at %d/%d elm %p\n",
4616 base, i, count, elm);
4621 * Update stats and zero the entry.
4623 * NOTE: Handle radix == 0 (0 bytes) case.
4625 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4626 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4627 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4629 switch(scan->type) {
4630 case HAMMER2_BREF_TYPE_INODE:
4631 parent->bref.embed.stats.inode_count -= 1;
4633 case HAMMER2_BREF_TYPE_DATA:
4634 case HAMMER2_BREF_TYPE_INDIRECT:
4635 parent->bref.embed.stats.data_count -=
4636 scan->embed.stats.data_count;
4637 parent->bref.embed.stats.inode_count -=
4638 scan->embed.stats.inode_count;
4644 bzero(scan, sizeof(*scan));
4647 * We can only optimize parent->core.live_zero for live chains.
4649 if (parent->core.live_zero == i + 1) {
4650 while (--i >= 0 && base[i].type == 0)
4652 parent->core.live_zero = i + 1;
4656 * Clear appropriate blockmap flags in chain.
4658 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4659 HAMMER2_CHAIN_BMAPUPD);
4663 * Insert the specified element. The block array must not already have the
4664 * element and must have space available for the insertion.
4666 * The spin lock on the related chain must be held.
4668 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4669 * need to be adjusted when we commit the media change.
4672 hammer2_base_insert(hammer2_chain_t *parent,
4673 hammer2_blockref_t *base, int count,
4674 int *cache_indexp, hammer2_chain_t *chain)
4676 hammer2_blockref_t *elm = &chain->bref;
4677 hammer2_key_t key_next;
4686 * Insert new element. Expect the element to not already exist
4687 * unless we are replacing it.
4689 * XXX see caller, flush code not yet sophisticated enough to prevent
4690 * re-flushed in some cases.
4692 key_next = 0; /* max range */
4693 i = hammer2_base_find(parent, base, count, cache_indexp,
4694 &key_next, elm->key, elm->key);
4697 * Shortcut fill optimization, typical ordered insertion(s) may not
4700 KKASSERT(i >= 0 && i <= count);
4703 * Set appropriate blockmap flags in chain.
4705 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4708 * Update stats and zero the entry
4710 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4711 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4712 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4715 case HAMMER2_BREF_TYPE_INODE:
4716 parent->bref.embed.stats.inode_count += 1;
4718 case HAMMER2_BREF_TYPE_DATA:
4719 case HAMMER2_BREF_TYPE_INDIRECT:
4720 parent->bref.embed.stats.data_count +=
4721 elm->embed.stats.data_count;
4722 parent->bref.embed.stats.inode_count +=
4723 elm->embed.stats.inode_count;
4731 * We can only optimize parent->core.live_zero for live chains.
4733 if (i == count && parent->core.live_zero < count) {
4734 i = parent->core.live_zero++;
4739 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4740 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4741 hammer2_spin_unex(&parent->core.spin);
4742 panic("insert base %p overlapping elements at %d elm %p\n",
4747 * Try to find an empty slot before or after.
4751 while (j > 0 || k < count) {
4753 if (j >= 0 && base[j].type == 0) {
4757 bcopy(&base[j+1], &base[j],
4758 (i - j - 1) * sizeof(*base));
4764 if (k < count && base[k].type == 0) {
4765 bcopy(&base[i], &base[i+1],
4766 (k - i) * sizeof(hammer2_blockref_t));
4770 * We can only update parent->core.live_zero for live
4773 if (parent->core.live_zero <= k)
4774 parent->core.live_zero = k + 1;
4779 panic("hammer2_base_insert: no room!");
4786 for (l = 0; l < count; ++l) {
4788 key_next = base[l].key +
4789 ((hammer2_key_t)1 << base[l].keybits) - 1;
4793 while (++l < count) {
4795 if (base[l].key <= key_next)
4796 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4797 key_next = base[l].key +
4798 ((hammer2_key_t)1 << base[l].keybits) - 1;
4808 * Sort the blockref array for the chain. Used by the flush code to
4809 * sort the blockref[] array.
4811 * The chain must be exclusively locked AND spin-locked.
4813 typedef hammer2_blockref_t *hammer2_blockref_p;
4817 hammer2_base_sort_callback(const void *v1, const void *v2)
4819 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4820 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4823 * Make sure empty elements are placed at the end of the array
4825 if (bref1->type == 0) {
4826 if (bref2->type == 0)
4829 } else if (bref2->type == 0) {
4836 if (bref1->key < bref2->key)
4838 if (bref1->key > bref2->key)
4844 hammer2_base_sort(hammer2_chain_t *chain)
4846 hammer2_blockref_t *base;
4849 switch(chain->bref.type) {
4850 case HAMMER2_BREF_TYPE_INODE:
4852 * Special shortcut for embedded data returns the inode
4853 * itself. Callers must detect this condition and access
4854 * the embedded data (the strategy code does this for us).
4856 * This is only applicable to regular files and softlinks.
4858 if (chain->data->ipdata.meta.op_flags &
4859 HAMMER2_OPFLAG_DIRECTDATA) {
4862 base = &chain->data->ipdata.u.blockset.blockref[0];
4863 count = HAMMER2_SET_COUNT;
4865 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4866 case HAMMER2_BREF_TYPE_INDIRECT:
4868 * Optimize indirect blocks in the INITIAL state to avoid
4871 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4872 base = &chain->data->npdata[0];
4873 count = chain->bytes / sizeof(hammer2_blockref_t);
4875 case HAMMER2_BREF_TYPE_VOLUME:
4876 base = &chain->data->voldata.sroot_blockset.blockref[0];
4877 count = HAMMER2_SET_COUNT;
4879 case HAMMER2_BREF_TYPE_FREEMAP:
4880 base = &chain->data->blkset.blockref[0];
4881 count = HAMMER2_SET_COUNT;
4884 kprintf("hammer2_chain_lookup: unrecognized "
4885 "blockref(A) type: %d",
4888 tsleep(&base, 0, "dead", 0);
4889 panic("hammer2_chain_lookup: unrecognized "
4890 "blockref(A) type: %d",
4892 base = NULL; /* safety */
4893 count = 0; /* safety */
4895 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4901 * Chain memory management
4904 hammer2_chain_wait(hammer2_chain_t *chain)
4906 tsleep(chain, 0, "chnflw", 1);
4909 const hammer2_media_data_t *
4910 hammer2_chain_rdata(hammer2_chain_t *chain)
4912 KKASSERT(chain->data != NULL);
4913 return (chain->data);
4916 hammer2_media_data_t *
4917 hammer2_chain_wdata(hammer2_chain_t *chain)
4919 KKASSERT(chain->data != NULL);
4920 return (chain->data);
4924 * Set the check data for a chain. This can be a heavy-weight operation
4925 * and typically only runs on-flush. For file data check data is calculated
4926 * when the logical buffers are flushed.
4929 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4931 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4933 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4934 case HAMMER2_CHECK_NONE:
4936 case HAMMER2_CHECK_DISABLED:
4938 case HAMMER2_CHECK_ISCSI32:
4939 chain->bref.check.iscsi32.value =
4940 hammer2_icrc32(bdata, chain->bytes);
4942 case HAMMER2_CHECK_XXHASH64:
4943 chain->bref.check.xxhash64.value =
4944 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4946 case HAMMER2_CHECK_SHA192:
4948 SHA256_CTX hash_ctx;
4950 uint8_t digest[SHA256_DIGEST_LENGTH];
4951 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4954 SHA256_Init(&hash_ctx);
4955 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4956 SHA256_Final(u.digest, &hash_ctx);
4957 u.digest64[2] ^= u.digest64[3];
4959 chain->bref.check.sha192.data,
4960 sizeof(chain->bref.check.sha192.data));
4963 case HAMMER2_CHECK_FREEMAP:
4964 chain->bref.check.freemap.icrc32 =
4965 hammer2_icrc32(bdata, chain->bytes);
4968 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4969 chain->bref.methods);
4975 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4981 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4984 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4985 case HAMMER2_CHECK_NONE:
4988 case HAMMER2_CHECK_DISABLED:
4991 case HAMMER2_CHECK_ISCSI32:
4992 check32 = hammer2_icrc32(bdata, chain->bytes);
4993 r = (chain->bref.check.iscsi32.value == check32);
4995 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
4996 "(flags=%08x, bref/data %08x/%08x)\n",
4997 chain->bref.data_off,
4999 chain->bref.methods,
5001 chain->bref.check.iscsi32.value,
5004 hammer2_check_icrc32 += chain->bytes;
5006 case HAMMER2_CHECK_XXHASH64:
5007 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5008 r = (chain->bref.check.xxhash64.value == check64);
5010 kprintf("chain %016jx.%02x key=%016jx "
5011 "meth=%02x CHECK FAIL "
5012 "(flags=%08x, bref/data %016jx/%016jx)\n",
5013 chain->bref.data_off,
5016 chain->bref.methods,
5018 chain->bref.check.xxhash64.value,
5021 hammer2_check_xxhash64 += chain->bytes;
5023 case HAMMER2_CHECK_SHA192:
5025 SHA256_CTX hash_ctx;
5027 uint8_t digest[SHA256_DIGEST_LENGTH];
5028 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5031 SHA256_Init(&hash_ctx);
5032 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5033 SHA256_Final(u.digest, &hash_ctx);
5034 u.digest64[2] ^= u.digest64[3];
5036 chain->bref.check.sha192.data,
5037 sizeof(chain->bref.check.sha192.data)) == 0) {
5041 kprintf("chain %016jx.%02x meth=%02x "
5043 chain->bref.data_off,
5045 chain->bref.methods);
5049 case HAMMER2_CHECK_FREEMAP:
5050 r = (chain->bref.check.freemap.icrc32 ==
5051 hammer2_icrc32(bdata, chain->bytes));
5053 kprintf("chain %016jx.%02x meth=%02x "
5055 chain->bref.data_off,
5057 chain->bref.methods);
5058 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5059 chain->bref.check.freemap.icrc32,
5060 hammer2_icrc32(bdata, chain->bytes),
5063 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5064 chain->dio, chain->dio->bp->b_loffset,
5065 chain->dio->bp->b_bufsize, bdata,
5066 chain->dio->bp->b_data);
5071 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5072 chain->bref.methods);
5080 * Acquire the chain and parent representing the specified inode for the
5081 * device at the specified cluster index.
5083 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5085 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5086 * will be NULL. *parentp may still be set error or not, or NULL if the
5087 * parent itself could not be resolved.
5089 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5090 * *parentp and *chainp will be unlocked if not NULL.
5093 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5094 int clindex, int flags,
5095 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5097 hammer2_chain_t *parent;
5098 hammer2_chain_t *rchain;
5099 hammer2_key_t key_dummy;
5100 int cache_index = -1;
5103 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5104 HAMMER2_RESOLVE_SHARED : 0;
5107 * Caller expects us to replace these.
5110 hammer2_chain_unlock(*chainp);
5111 hammer2_chain_drop(*chainp);
5115 hammer2_chain_unlock(*parentp);
5116 hammer2_chain_drop(*parentp);
5121 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5122 * inodes from root directory entries in the key lookup).
5124 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5127 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5129 &cache_index, flags);
5134 return (rchain ? 0 : EINVAL);
5138 * Used by the bulkscan code to snapshot the synchronized storage for
5139 * a volume, allowing it to be scanned concurrently against normal
5143 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5145 hammer2_chain_t *copy;
5147 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5148 copy->data = kmalloc(sizeof(copy->data->voldata),
5151 hammer2_voldata_lock(hmp);
5152 copy->data->voldata = hmp->volsync;
5153 hammer2_voldata_unlock(hmp);
5159 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5161 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5162 KKASSERT(copy->data);
5163 kfree(copy->data, copy->hmp->mchain);
5165 atomic_add_long(&hammer2_chain_allocs, -1);
5166 hammer2_chain_drop(copy);
5170 * Create a snapshot of the specified (chain) with the specified label.
5171 * The originating hammer2_inode must be exclusively locked for
5172 * safety. The device's bulklk should be held by the caller. The caller
5173 * is responsible for synchronizing the filesystem to storage before
5174 * taking the snapshot.
5177 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5181 const hammer2_inode_data_t *ripdata;
5182 hammer2_inode_data_t *wipdata;
5183 hammer2_chain_t *nchain;
5184 hammer2_inode_t *nip;
5193 kprintf("snapshot %s\n", pmp->name);
5195 name_len = strlen(pmp->name);
5196 lhc = hammer2_dirhash(pmp->name, name_len);
5201 ripdata = &chain->data->ipdata;
5203 opfs_clid = ripdata->meta.pfs_clid;
5208 * Create the snapshot directory under the super-root
5210 * Set PFS type, generate a unique filesystem id, and generate
5211 * a cluster id. Use the same clid when snapshotting a PFS root,
5212 * which theoretically allows the snapshot to be used as part of
5213 * the same cluster (perhaps as a cache).
5215 * Copy the (flushed) blockref array. Theoretically we could use
5216 * chain_duplicate() but it becomes difficult to disentangle
5217 * the shared core so for now just brute-force it.
5222 hammer2_chain_unlock(chain);
5223 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5224 &vat, proc0.p_ucred,
5225 pmp->name, name_len, 0,
5227 HAMMER2_INSERT_PFSROOT, &error);
5228 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5231 hammer2_inode_modify(nip);
5232 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5233 hammer2_chain_modify(nchain, mtid, 0, 0);
5234 wipdata = &nchain->data->ipdata;
5236 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5237 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5238 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5239 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5242 * Give the snapshot its own private cluster id. As a
5243 * snapshot no further synchronization with the original
5244 * cluster will be done.
5247 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5248 nip->meta.pfs_clid = opfs_clid;
5250 kern_uuidgen(&nip->meta.pfs_clid, 1);
5252 kern_uuidgen(&nip->meta.pfs_clid, 1);
5253 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5255 /* XXX hack blockset copy */
5256 /* XXX doesn't work with real cluster */
5257 wipdata->meta = nip->meta;
5258 wipdata->u.blockset = ripdata->u.blockset;
5260 hammer2_flush(nchain, 1);
5261 KKASSERT(wipdata == &nchain->data->ipdata);
5262 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5264 hammer2_chain_unlock(nchain);
5265 hammer2_chain_drop(nchain);
5266 hammer2_inode_chain_sync(nip);
5267 hammer2_inode_unlock(nip);
5268 hammer2_inode_run_sideq(hmp->spmp);
5274 * Returns non-zero if the chain (INODE or DIRENT) matches the
5278 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5281 const hammer2_inode_data_t *ripdata;
5282 const hammer2_dirent_head_t *den;
5284 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5285 ripdata = &chain->data->ipdata;
5286 if (ripdata->meta.name_len == name_len &&
5287 bcmp(ripdata->filename, name, name_len) == 0) {
5291 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5292 chain->bref.embed.dirent.namlen == name_len) {
5293 den = &chain->bref.embed.dirent;
5294 if (name_len > sizeof(chain->bref.check.buf) &&
5295 bcmp(chain->data->buf, name, name_len) == 0) {
5298 if (name_len <= sizeof(chain->bref.check.buf) &&
5299 bcmp(chain->bref.check.buf, name, name_len) == 0) {