2 * Copyright (c) 2011-2014 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>
65 static int hammer2_indirect_optimize; /* XXX SYSCTL */
67 static hammer2_chain_t *hammer2_chain_create_indirect(
68 hammer2_trans_t *trans, hammer2_chain_t *parent,
69 hammer2_key_t key, int keybits, int for_type, int *errorp);
70 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
71 static hammer2_chain_t *hammer2_combined_find(
72 hammer2_chain_t *parent,
73 hammer2_blockref_t *base, int count,
74 int *cache_indexp, hammer2_key_t *key_nextp,
75 hammer2_key_t key_beg, hammer2_key_t key_end,
76 hammer2_blockref_t **bresp);
79 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
80 * overlap in the RB trees. Deleted chains are moved from rbtree to either
83 * Chains in delete-duplicate sequences can always iterate through core_entry
84 * to locate the live version of the chain.
86 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
89 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
97 * Compare chains. Overlaps are not supposed to happen and catch
98 * any software issues early we count overlaps as a match.
100 c1_beg = chain1->bref.key;
101 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
102 c2_beg = chain2->bref.key;
103 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
105 if (c1_end < c2_beg) /* fully to the left */
107 if (c1_beg > c2_end) /* fully to the right */
109 return(0); /* overlap (must not cross edge boundary) */
114 hammer2_isclusterable(hammer2_chain_t *chain)
116 if (hammer2_cluster_enable) {
117 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
118 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
119 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
127 * Make a chain visible to the flusher. The flusher needs to be able to
128 * do flushes of a subdirectory chains or single files so it does a top-down
129 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
130 * or UPDATE chains and flushes back up the chain to the root.
133 hammer2_chain_setflush(hammer2_trans_t *trans, hammer2_chain_t *chain)
135 hammer2_chain_t *parent;
137 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
138 spin_lock(&chain->core.cst.spin);
139 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
140 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
141 if ((parent = chain->parent) == NULL)
143 spin_lock(&parent->core.cst.spin);
144 spin_unlock(&chain->core.cst.spin);
147 spin_unlock(&chain->core.cst.spin);
152 * Allocate a new disconnected chain element representing the specified
153 * bref. chain->refs is set to 1 and the passed bref is copied to
154 * chain->bref. chain->bytes is derived from the bref.
156 * chain->core is NOT allocated and the media data and bp pointers are left
157 * NULL. The caller must call chain_core_alloc() to allocate or associate
158 * a core with the chain.
160 * chain->pmp inherits pmp unless the chain is an inode (other than the
163 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
166 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
167 hammer2_trans_t *trans, hammer2_blockref_t *bref)
169 hammer2_chain_t *chain;
170 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
173 * Construct the appropriate system structure.
176 case HAMMER2_BREF_TYPE_INODE:
177 case HAMMER2_BREF_TYPE_INDIRECT:
178 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
179 case HAMMER2_BREF_TYPE_DATA:
180 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
182 * Chain's are really only associated with the hmp but we
183 * maintain a pmp association for per-mount memory tracking
184 * purposes. The pmp can be NULL.
186 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
188 case HAMMER2_BREF_TYPE_VOLUME:
189 case HAMMER2_BREF_TYPE_FREEMAP:
191 panic("hammer2_chain_alloc volume type illegal for op");
194 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
199 * Initialize the new chain structure.
204 chain->bytes = bytes;
206 chain->flags = HAMMER2_CHAIN_ALLOCATED;
209 * Set the PFS boundary flag if this chain represents a PFS root.
211 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
212 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
218 * Associate an existing core with the chain or allocate a new core.
220 * The core is not locked. No additional refs on the chain are made.
221 * (trans) must not be NULL if (core) is not NULL.
223 * When chains are delete-duplicated during flushes we insert nchain on
224 * the ownerq after ochain instead of at the end in order to give the
225 * drop code visibility in the correct order, otherwise drops can be missed.
228 hammer2_chain_core_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain)
230 hammer2_chain_core_t *core = &chain->core;
233 * Fresh core under nchain (no multi-homing of ochain's
236 RB_INIT(&core->rbtree); /* live chains */
237 ccms_cst_init(&core->cst, chain);
241 * Add a reference to a chain element, preventing its destruction.
244 hammer2_chain_ref(hammer2_chain_t *chain)
246 atomic_add_int(&chain->refs, 1);
250 * Insert the chain in the core rbtree.
252 * Normal insertions are placed in the live rbtree. Insertion of a deleted
253 * chain is a special case used by the flush code that is placed on the
254 * unstaged deleted list to avoid confusing the live view.
256 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
257 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
258 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
262 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
263 int flags, int generation)
265 hammer2_chain_t *xchain;
268 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
269 spin_lock(&parent->core.cst.spin);
272 * Interlocked by spinlock, check for race
274 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
275 parent->core.generation != generation) {
283 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
284 KASSERT(xchain == NULL,
285 ("hammer2_chain_insert: collision %p %p", chain, xchain));
286 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
287 chain->parent = parent;
288 ++parent->core.chain_count;
289 ++parent->core.generation; /* XXX incs for _get() too, XXX */
292 * We have to keep track of the effective live-view blockref count
293 * so the create code knows when to push an indirect block.
295 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
296 atomic_add_int(&parent->core.live_count, 1);
298 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
299 spin_unlock(&parent->core.cst.spin);
304 * Drop the caller's reference to the chain. When the ref count drops to
305 * zero this function will try to disassociate the chain from its parent and
306 * deallocate it, then recursely drop the parent using the implied ref
307 * from the chain's chain->parent.
309 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
312 hammer2_chain_drop(hammer2_chain_t *chain)
317 if (hammer2_debug & 0x200000)
320 if (chain->flags & HAMMER2_CHAIN_UPDATE)
322 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
324 KKASSERT(chain->refs > need);
332 chain = hammer2_chain_lastdrop(chain);
334 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
336 /* retry the same chain */
342 * Safe handling of the 1->0 transition on chain. Returns a chain for
343 * recursive drop or NULL, possibly returning the same chain if the atomic
346 * Whem two chains need to be recursively dropped we use the chain
347 * we would otherwise free to placehold the additional chain. It's a bit
348 * convoluted but we can't just recurse without potentially blowing out
351 * The chain cannot be freed if it has a non-empty core (children) or
352 * it is not at the head of ownerq.
354 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
358 hammer2_chain_lastdrop(hammer2_chain_t *chain)
360 hammer2_pfsmount_t *pmp;
361 hammer2_mount_t *hmp;
362 hammer2_chain_t *parent;
363 hammer2_chain_t *rdrop;
366 * Spinlock the core and check to see if it is empty. If it is
367 * not empty we leave chain intact with refs == 0. The elements
368 * in core->rbtree are associated with other chains contemporary
369 * with ours but not with our chain directly.
371 spin_lock(&chain->core.cst.spin);
374 * We can't free non-stale chains with children until we are
375 * able to free the children because there might be a flush
376 * dependency. Flushes of stale children (which should also
377 * have their deleted flag set) short-cut recursive flush
378 * dependencies and can be freed here. Any flushes which run
379 * through stale children due to the flush synchronization
380 * point should have a FLUSH_* bit set in the chain and not
381 * reach lastdrop at this time.
383 * NOTE: We return (chain) on failure to retry.
385 if (chain->core.chain_count) {
386 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
387 spin_unlock(&chain->core.cst.spin);
388 chain = NULL; /* success */
390 spin_unlock(&chain->core.cst.spin);
394 /* no chains left under us */
397 * chain->core has no children left so no accessors can get to our
398 * chain from there. Now we have to lock the parent core to interlock
399 * remaining possible accessors that might bump chain's refs before
400 * we can safely drop chain's refs with intent to free the chain.
403 pmp = chain->pmp; /* can be NULL */
407 * Spinlock the parent and try to drop the last ref on chain.
408 * On success remove chain from its parent, otherwise return NULL.
410 * (normal core locks are top-down recursive but we define core
411 * spinlocks as bottom-up recursive, so this is safe).
413 if ((parent = chain->parent) != NULL) {
414 spin_lock(&parent->core.cst.spin);
415 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
416 /* 1->0 transition failed */
417 spin_unlock(&parent->core.cst.spin);
418 spin_unlock(&chain->core.cst.spin);
419 return(chain); /* retry */
423 * 1->0 transition successful, remove chain from its
426 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
427 RB_REMOVE(hammer2_chain_tree,
428 &parent->core.rbtree, chain);
429 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
430 --parent->core.chain_count;
431 chain->parent = NULL;
435 * If our chain was the last chain in the parent's core the
436 * core is now empty and its parent might have to be
437 * re-dropped if it has 0 refs.
439 if (parent->core.chain_count == 0) {
441 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
445 spin_unlock(&parent->core.cst.spin);
446 parent = NULL; /* safety */
450 * Successful 1->0 transition and the chain can be destroyed now.
452 * We still have the core spinlock, and core's chain_count is 0.
453 * Any parent spinlock is gone.
455 spin_unlock(&chain->core.cst.spin);
456 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
457 chain->core.chain_count == 0);
458 KKASSERT(chain->core.cst.count == 0);
459 KKASSERT(chain->core.cst.upgrade == 0);
462 * All spin locks are gone, finish freeing stuff.
464 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
465 HAMMER2_CHAIN_MODIFIED)) == 0);
466 hammer2_chain_drop_data(chain, 1);
468 KKASSERT(chain->dio == NULL);
471 * Once chain resources are gone we can use the now dead chain
472 * structure to placehold what might otherwise require a recursive
473 * drop, because we have potentially two things to drop and can only
474 * return one directly.
476 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
477 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
479 kfree(chain, hmp->mchain);
483 * Possible chaining loop when parent re-drop needed.
489 * On either last lock release or last drop
492 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
494 /*hammer2_mount_t *hmp = chain->hmp;*/
496 switch(chain->bref.type) {
497 case HAMMER2_BREF_TYPE_VOLUME:
498 case HAMMER2_BREF_TYPE_FREEMAP:
503 KKASSERT(chain->data == NULL);
509 * Ref and lock a chain element, acquiring its data with I/O if necessary,
510 * and specify how you would like the data to be resolved.
512 * Returns 0 on success or an error code if the data could not be acquired.
513 * The chain element is locked on return regardless of whether an error
516 * The lock is allowed to recurse, multiple locking ops will aggregate
517 * the requested resolve types. Once data is assigned it will not be
518 * removed until the last unlock.
520 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
521 * (typically used to avoid device/logical buffer
524 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
525 * the INITIAL-create state (indirect blocks only).
527 * Do not resolve data elements for DATA chains.
528 * (typically used to avoid device/logical buffer
531 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
533 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
534 * it will be locked exclusive.
536 * NOTE: Embedded elements (volume header, inodes) are always resolved
539 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
540 * element will instantiate and zero its buffer, and flush it on
543 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
544 * so as not to instantiate a device buffer, which could alias against
545 * a logical file buffer. However, if ALWAYS is specified the
546 * device buffer will be instantiated anyway.
548 * WARNING! If data must be fetched a shared lock will temporarily be
549 * upgraded to exclusive. However, a deadlock can occur if
550 * the caller owns more than one shared lock.
553 hammer2_chain_lock(hammer2_chain_t *chain, int how)
555 hammer2_mount_t *hmp;
556 hammer2_blockref_t *bref;
562 * Ref and lock the element. Recursive locks are allowed.
564 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
565 hammer2_chain_ref(chain);
566 atomic_add_int(&chain->lockcnt, 1);
569 KKASSERT(hmp != NULL);
572 * Get the appropriate lock.
574 if (how & HAMMER2_RESOLVE_SHARED)
575 ccms_thread_lock(&chain->core.cst, CCMS_STATE_SHARED);
577 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
580 * If we already have a valid data pointer no further action is
587 * Do we have to resolve the data?
589 switch(how & HAMMER2_RESOLVE_MASK) {
590 case HAMMER2_RESOLVE_NEVER:
592 case HAMMER2_RESOLVE_MAYBE:
593 if (chain->flags & HAMMER2_CHAIN_INITIAL)
595 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
598 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
601 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
604 case HAMMER2_RESOLVE_ALWAYS:
609 * Upgrade to an exclusive lock so we can safely manipulate the
610 * buffer cache. If another thread got to it before us we
613 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
615 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
620 * We must resolve to a device buffer, either by issuing I/O or
621 * by creating a zero-fill element. We do not mark the buffer
622 * dirty when creating a zero-fill element (the hammer2_chain_modify()
623 * API must still be used to do that).
625 * The device buffer is variable-sized in powers of 2 down
626 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
627 * chunk always contains buffers of the same size. (XXX)
629 * The minimum physical IO size may be larger than the variable
635 * The getblk() optimization can only be used on newly created
636 * elements if the physical block size matches the request.
638 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
639 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
642 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
644 hammer2_adjreadcounter(&chain->bref, chain->bytes);
648 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
649 (intmax_t)bref->data_off, error);
650 hammer2_io_bqrelse(&chain->dio);
651 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
657 * No need for this, always require that hammer2_chain_modify()
658 * be called before any modifying operations.
660 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
661 !hammer2_io_isdirty(chain->dio)) {
662 hammer2_io_setdirty(chain->dio);
667 * Clear INITIAL. In this case we used io_new() and the buffer has
668 * been zero'd and marked dirty.
670 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
671 if (chain->flags & HAMMER2_CHAIN_INITIAL)
672 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
675 * Setup the data pointer, either pointing it to an embedded data
676 * structure and copying the data from the buffer, or pointing it
679 * The buffer is not retained when copying to an embedded data
680 * structure in order to avoid potential deadlocks or recursions
681 * on the same physical buffer.
683 switch (bref->type) {
684 case HAMMER2_BREF_TYPE_VOLUME:
685 case HAMMER2_BREF_TYPE_FREEMAP:
687 * Copy data from bp to embedded buffer
689 panic("hammer2_chain_lock: called on unresolved volume header");
691 case HAMMER2_BREF_TYPE_INODE:
692 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
693 case HAMMER2_BREF_TYPE_INDIRECT:
694 case HAMMER2_BREF_TYPE_DATA:
695 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
698 * Point data at the device buffer and leave dio intact.
700 chain->data = (void *)bdata;
703 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
708 * This basically calls hammer2_io_breadcb() but does some pre-processing
709 * of the chain first to handle certain cases.
712 hammer2_chain_load_async(hammer2_cluster_t *cluster,
713 void (*callback)(hammer2_io_t *dio,
714 hammer2_cluster_t *cluster,
715 hammer2_chain_t *chain,
716 void *arg_p, off_t arg_o),
719 hammer2_chain_t *chain;
720 hammer2_mount_t *hmp;
721 struct hammer2_io *dio;
722 hammer2_blockref_t *bref;
727 * If no chain specified see if any chain data is available and use
728 * that, otherwise begin an I/O iteration using the first chain.
731 for (i = 0; i < cluster->nchains; ++i) {
732 chain = cluster->array[i];
733 if (chain && chain->data)
736 if (i == cluster->nchains) {
737 chain = cluster->array[0];
742 callback(NULL, cluster, chain, arg_p, (off_t)i);
747 * We must resolve to a device buffer, either by issuing I/O or
748 * by creating a zero-fill element. We do not mark the buffer
749 * dirty when creating a zero-fill element (the hammer2_chain_modify()
750 * API must still be used to do that).
752 * The device buffer is variable-sized in powers of 2 down
753 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
754 * chunk always contains buffers of the same size. (XXX)
756 * The minimum physical IO size may be larger than the variable
763 * The getblk() optimization can only be used on newly created
764 * elements if the physical block size matches the request.
766 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
767 chain->bytes == hammer2_devblksize(chain->bytes)) {
768 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
769 KKASSERT(error == 0);
770 callback(dio, cluster, chain, arg_p, (off_t)i);
775 * Otherwise issue a read
777 hammer2_adjreadcounter(&chain->bref, chain->bytes);
778 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
779 callback, cluster, chain, arg_p, (off_t)i);
783 * Unlock and deref a chain element.
785 * On the last lock release any non-embedded data (chain->dio) will be
789 hammer2_chain_unlock(hammer2_chain_t *chain)
796 * The core->cst lock can be shared across several chains so we
797 * need to track the per-chain lockcnt separately.
799 * If multiple locks are present (or being attempted) on this
800 * particular chain we can just unlock, drop refs, and return.
802 * Otherwise fall-through on the 1->0 transition.
805 lockcnt = chain->lockcnt;
806 KKASSERT(lockcnt > 0);
809 if (atomic_cmpset_int(&chain->lockcnt,
810 lockcnt, lockcnt - 1)) {
811 ccms_thread_unlock(&chain->core.cst);
812 hammer2_chain_drop(chain);
816 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
823 * On the 1->0 transition we upgrade the core lock (if necessary)
824 * to exclusive for terminal processing. If after upgrading we find
825 * that lockcnt is non-zero, another thread is racing us and will
826 * handle the unload for us later on, so just cleanup and return
827 * leaving the data/io intact
829 * Otherwise if lockcnt is still 0 it is possible for it to become
830 * non-zero and race, but since we hold the core->cst lock
831 * exclusively all that will happen is that the chain will be
832 * reloaded after we unload it.
834 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
835 if (chain->lockcnt) {
836 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
837 hammer2_chain_drop(chain);
842 * Shortcut the case if the data is embedded or not resolved.
844 * Do NOT NULL out chain->data (e.g. inode data), it might be
847 if (chain->dio == NULL) {
848 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
849 hammer2_chain_drop_data(chain, 0);
850 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
851 hammer2_chain_drop(chain);
858 if (hammer2_io_isdirty(chain->dio) == 0) {
860 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
861 switch(chain->bref.type) {
862 case HAMMER2_BREF_TYPE_DATA:
863 counterp = &hammer2_ioa_file_write;
865 case HAMMER2_BREF_TYPE_INODE:
866 counterp = &hammer2_ioa_meta_write;
868 case HAMMER2_BREF_TYPE_INDIRECT:
869 counterp = &hammer2_ioa_indr_write;
871 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
872 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
873 counterp = &hammer2_ioa_fmap_write;
876 counterp = &hammer2_ioa_volu_write;
879 *counterp += chain->bytes;
881 switch(chain->bref.type) {
882 case HAMMER2_BREF_TYPE_DATA:
883 counterp = &hammer2_iod_file_write;
885 case HAMMER2_BREF_TYPE_INODE:
886 counterp = &hammer2_iod_meta_write;
888 case HAMMER2_BREF_TYPE_INDIRECT:
889 counterp = &hammer2_iod_indr_write;
891 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
892 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
893 counterp = &hammer2_iod_fmap_write;
896 counterp = &hammer2_iod_volu_write;
899 *counterp += chain->bytes;
905 * If a device buffer was used for data be sure to destroy the
906 * buffer when we are done to avoid aliases (XXX what about the
907 * underlying VM pages?).
909 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
912 * NOTE: The isdirty check tracks whether we have to bdwrite() the
913 * buffer or not. The buffer might already be dirty. The
914 * flag is re-set when chain_modify() is called, even if
915 * MODIFIED is already set, allowing the OS to retire the
916 * buffer independent of a hammer2 flush.
919 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
920 hammer2_io_isdirty(chain->dio)) {
921 hammer2_io_bawrite(&chain->dio);
923 hammer2_io_bqrelse(&chain->dio);
925 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
926 hammer2_chain_drop(chain);
930 * This counts the number of live blockrefs in a block array and
931 * also calculates the point at which all remaining blockrefs are empty.
932 * This routine can only be called on a live chain (DUPLICATED flag not set).
934 * NOTE: Flag is not set until after the count is complete, allowing
935 * callers to test the flag without holding the spinlock.
937 * NOTE: If base is NULL the related chain is still in the INITIAL
938 * state and there are no blockrefs to count.
940 * NOTE: live_count may already have some counts accumulated due to
941 * creation and deletion and could even be initially negative.
944 hammer2_chain_countbrefs(hammer2_chain_t *chain,
945 hammer2_blockref_t *base, int count)
947 spin_lock(&chain->core.cst.spin);
948 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
950 while (--count >= 0) {
951 if (base[count].type)
954 chain->core.live_zero = count + 1;
956 if (base[count].type)
957 atomic_add_int(&chain->core.live_count,
962 chain->core.live_zero = 0;
964 /* else do not modify live_count */
965 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
967 spin_unlock(&chain->core.cst.spin);
971 * Resize the chain's physical storage allocation in-place. This will
972 * modify the passed-in chain. Chains can be resized smaller without
973 * reallocating the storage. Resizing larger will reallocate the storage.
974 * Excess or prior storage is reclaimed asynchronously at a later time.
976 * Must be passed an exclusively locked parent and chain.
978 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
979 * to avoid instantiating a device buffer that conflicts with the vnode data
980 * buffer. That is, the passed-in bp is a logical buffer, whereas any
981 * chain-oriented bp would be a device buffer.
983 * XXX return error if cannot resize.
986 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
987 hammer2_chain_t *parent, hammer2_chain_t *chain,
988 int nradix, int flags)
990 hammer2_mount_t *hmp;
997 * Only data and indirect blocks can be resized for now.
998 * (The volu root, inodes, and freemap elements use a fixed size).
1000 KKASSERT(chain != &hmp->vchain);
1001 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1002 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1005 * Nothing to do if the element is already the proper size
1007 obytes = chain->bytes;
1008 nbytes = 1U << nradix;
1009 if (obytes == nbytes)
1013 * The parent does not have to be locked for the delete/duplicate call,
1014 * but is in this particular code path.
1016 * NOTE: If we are not crossing a synchronization point the
1017 * duplication code will simply reuse the existing chain
1020 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1022 hammer2_chain_modify(trans, chain, 0);
1025 * Relocate the block, even if making it smaller (because different
1026 * block sizes may be in different regions).
1028 * (data blocks only, we aren't copying the storage here).
1030 hammer2_freemap_alloc(trans, chain, nbytes);
1031 chain->bytes = nbytes;
1032 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1033 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1036 * For now just support it on DATA chains (and not on indirect
1039 KKASSERT(chain->dio == NULL);
1045 * REMOVED - see cluster code
1047 * Set a chain modified, making it read-write and duplicating it if necessary.
1048 * This function will assign a new physical block to the chain if necessary
1050 * Duplication of already-modified chains is possible when the modification
1051 * crosses a flush synchronization boundary.
1053 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1054 * level or the COW operation will not work.
1056 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1057 * run the data through the device buffers.
1059 * This function may return a different chain than was passed, in which case
1060 * the old chain will be unlocked and the new chain will be locked.
1062 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1064 hammer2_inode_data_t *
1065 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1066 hammer2_chain_t **chainp, int flags)
1068 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1069 hammer2_chain_modify(trans, chainp, flags);
1070 if (ip->chain != *chainp)
1071 hammer2_inode_repoint(ip, NULL, *chainp);
1073 vsetisdirty(ip->vp);
1074 return(&ip->chain->data->ipdata);
1080 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1082 hammer2_mount_t *hmp;
1092 * data is not optional for freemap chains (we must always be sure
1093 * to copy the data on COW storage allocations).
1095 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1096 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1097 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1098 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1102 * Data must be resolved if already assigned unless explicitly
1103 * flagged otherwise.
1105 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1106 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1107 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1108 hammer2_chain_unlock(chain);
1112 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1113 * that the chain has been modified. Set UPDATE to ensure that
1114 * the blockref is updated in the parent.
1116 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1117 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1118 hammer2_chain_ref(chain);
1119 hammer2_pfs_memory_inc(chain->pmp);
1124 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1125 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1126 hammer2_chain_ref(chain);
1130 * The modification or re-modification requires an allocation and
1133 * We normally always allocate new storage here. If storage exists
1134 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1136 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1137 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1138 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1140 hammer2_freemap_alloc(trans, chain, chain->bytes);
1141 /* XXX failed allocation */
1142 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1143 hammer2_freemap_alloc(trans, chain, chain->bytes);
1144 /* XXX failed allocation */
1146 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1150 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1151 * requires updating as well as to tell the delete code that the
1152 * chain's blockref might not exactly match (in terms of physical size
1153 * or block offset) the one in the parent's blocktable. The base key
1154 * of course will still match.
1156 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1157 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1160 * Do not COW BREF_TYPE_DATA when OPTDATA is set. This is because
1161 * data modifications are done via the logical buffer cache so COWing
1162 * it here would result in unnecessary extra copies (and possibly extra
1163 * block reallocations). The INITIAL flag remains unchanged in this
1166 * (This is a bit of a hack).
1168 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1169 (flags & HAMMER2_MODIFY_OPTDATA)) {
1174 * Clearing the INITIAL flag (for indirect blocks) indicates that
1175 * we've processed the uninitialized storage allocation.
1177 * If this flag is already clear we are likely in a copy-on-write
1178 * situation but we have to be sure NOT to bzero the storage if
1179 * no data is present.
1181 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1182 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1189 * Instantiate data buffer and possibly execute COW operation
1191 switch(chain->bref.type) {
1192 case HAMMER2_BREF_TYPE_VOLUME:
1193 case HAMMER2_BREF_TYPE_FREEMAP:
1195 * The data is embedded, no copy-on-write operation is
1198 KKASSERT(chain->dio == NULL);
1200 case HAMMER2_BREF_TYPE_INODE:
1201 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1202 case HAMMER2_BREF_TYPE_DATA:
1203 case HAMMER2_BREF_TYPE_INDIRECT:
1204 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1206 * Perform the copy-on-write operation
1208 * zero-fill or copy-on-write depending on whether
1209 * chain->data exists or not and set the dirty state for
1210 * the new buffer. hammer2_io_new() will handle the
1213 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1216 error = hammer2_io_new(hmp, chain->bref.data_off,
1217 chain->bytes, &dio);
1219 error = hammer2_io_bread(hmp, chain->bref.data_off,
1220 chain->bytes, &dio);
1222 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1223 KKASSERT(error == 0);
1225 bdata = hammer2_io_data(dio, chain->bref.data_off);
1228 KKASSERT(chain->dio != NULL);
1229 if (chain->data != (void *)bdata) {
1230 bcopy(chain->data, bdata, chain->bytes);
1232 } else if (wasinitial == 0) {
1234 * We have a problem. We were asked to COW but
1235 * we don't have any data to COW with!
1237 panic("hammer2_chain_modify: having a COW %p\n",
1242 * Retire the old buffer, replace with the new
1245 hammer2_io_brelse(&chain->dio);
1246 chain->data = (void *)bdata;
1248 hammer2_io_setdirty(dio); /* modified by bcopy above */
1251 panic("hammer2_chain_modify: illegal non-embedded type %d",
1258 * setflush on parent indicating that the parent must recurse down
1259 * to us. Do not call on chain itself which might already have it
1263 hammer2_chain_setflush(trans, chain->parent);
1267 * Volume header data locks
1270 hammer2_voldata_lock(hammer2_mount_t *hmp)
1272 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1276 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1278 lockmgr(&hmp->vollk, LK_RELEASE);
1282 hammer2_voldata_modify(hammer2_mount_t *hmp)
1284 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1285 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1286 hammer2_chain_ref(&hmp->vchain);
1287 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1292 * This function returns the chain at the nearest key within the specified
1293 * range. The core spinlock must be held on call and the returned chain
1294 * will be referenced but not locked.
1296 * This function will recurse through chain->rbtree as necessary and will
1297 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1298 * the iteration value is less than the current value of *key_nextp.
1300 * The caller should use (*key_nextp) to calculate the actual range of
1301 * the returned element, which will be (key_beg to *key_nextp - 1), because
1302 * there might be another element which is superior to the returned element
1305 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1306 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1307 * it will wind up being (key_end + 1).
1309 struct hammer2_chain_find_info {
1310 hammer2_chain_t *best;
1311 hammer2_key_t key_beg;
1312 hammer2_key_t key_end;
1313 hammer2_key_t key_next;
1316 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1317 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1321 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1322 hammer2_key_t key_beg, hammer2_key_t key_end)
1324 struct hammer2_chain_find_info info;
1327 info.key_beg = key_beg;
1328 info.key_end = key_end;
1329 info.key_next = *key_nextp;
1331 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1332 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1334 *key_nextp = info.key_next;
1336 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1337 parent, key_beg, key_end, *key_nextp);
1345 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1347 struct hammer2_chain_find_info *info = data;
1348 hammer2_key_t child_beg;
1349 hammer2_key_t child_end;
1351 child_beg = child->bref.key;
1352 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1354 if (child_end < info->key_beg)
1356 if (child_beg > info->key_end)
1363 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1365 struct hammer2_chain_find_info *info = data;
1366 hammer2_chain_t *best;
1367 hammer2_key_t child_end;
1370 * WARNING! Do not discard DUPLICATED chains, it is possible that
1371 * we are catching an insertion half-way done. If a
1372 * duplicated chain turns out to be the best choice the
1373 * caller will re-check its flags after locking it.
1375 * WARNING! Layerq is scanned forwards, exact matches should keep
1376 * the existing info->best.
1378 if ((best = info->best) == NULL) {
1380 * No previous best. Assign best
1383 } else if (best->bref.key <= info->key_beg &&
1384 child->bref.key <= info->key_beg) {
1389 /*info->best = child;*/
1390 } else if (child->bref.key < best->bref.key) {
1392 * Child has a nearer key and best is not flush with key_beg.
1393 * Set best to child. Truncate key_next to the old best key.
1396 if (info->key_next > best->bref.key || info->key_next == 0)
1397 info->key_next = best->bref.key;
1398 } else if (child->bref.key == best->bref.key) {
1400 * If our current best is flush with the child then this
1401 * is an illegal overlap.
1403 * key_next will automatically be limited to the smaller of
1404 * the two end-points.
1410 * Keep the current best but truncate key_next to the child's
1413 * key_next will also automatically be limited to the smaller
1414 * of the two end-points (probably not necessary for this case
1415 * but we do it anyway).
1417 if (info->key_next > child->bref.key || info->key_next == 0)
1418 info->key_next = child->bref.key;
1422 * Always truncate key_next based on child's end-of-range.
1424 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1425 if (child_end && (info->key_next > child_end || info->key_next == 0))
1426 info->key_next = child_end;
1432 * Retrieve the specified chain from a media blockref, creating the
1433 * in-memory chain structure which reflects it.
1435 * To handle insertion races pass the INSERT_RACE flag along with the
1436 * generation number of the core. NULL will be returned if the generation
1437 * number changes before we have a chance to insert the chain. Insert
1438 * races can occur because the parent might be held shared.
1440 * Caller must hold the parent locked shared or exclusive since we may
1441 * need the parent's bref array to find our block.
1443 * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1447 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1448 hammer2_blockref_t *bref)
1450 hammer2_mount_t *hmp = parent->hmp;
1451 hammer2_chain_t *chain;
1455 * Allocate a chain structure representing the existing media
1456 * entry. Resulting chain has one ref and is not locked.
1458 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1459 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1461 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1462 hammer2_chain_core_alloc(NULL, chain);
1463 /* ref'd chain returned */
1466 * Flag that the chain is in the parent's blockmap so delete/flush
1467 * knows what to do with it.
1469 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1472 * Link the chain into its parent. A spinlock is required to safely
1473 * access the RBTREE, and it is possible to collide with another
1474 * hammer2_chain_get() operation because the caller might only hold
1475 * a shared lock on the parent.
1477 KKASSERT(parent->refs > 0);
1478 error = hammer2_chain_insert(parent, chain,
1479 HAMMER2_CHAIN_INSERT_SPIN |
1480 HAMMER2_CHAIN_INSERT_RACE,
1483 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1484 kprintf("chain %p get race\n", chain);
1485 hammer2_chain_drop(chain);
1488 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1492 * Return our new chain referenced but not locked, or NULL if
1499 * Lookup initialization/completion API
1502 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1504 if (flags & HAMMER2_LOOKUP_SHARED) {
1505 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1506 HAMMER2_RESOLVE_SHARED);
1508 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1514 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1517 hammer2_chain_unlock(parent);
1522 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1524 hammer2_chain_t *oparent;
1525 hammer2_chain_t *nparent;
1528 * Be careful of order, oparent must be unlocked before nparent
1529 * is locked below to avoid a deadlock.
1532 spin_lock(&oparent->core.cst.spin);
1533 nparent = oparent->parent;
1534 hammer2_chain_ref(nparent);
1535 spin_unlock(&oparent->core.cst.spin);
1537 hammer2_chain_unlock(oparent);
1541 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1548 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1549 * (*parentp) typically points to an inode but can also point to a related
1550 * indirect block and this function will recurse upwards and find the inode
1553 * (*parentp) must be exclusively locked and referenced and can be an inode
1554 * or an existing indirect block within the inode.
1556 * On return (*parentp) will be modified to point at the deepest parent chain
1557 * element encountered during the search, as a helper for an insertion or
1558 * deletion. The new (*parentp) will be locked and referenced and the old
1559 * will be unlocked and dereferenced (no change if they are both the same).
1561 * The matching chain will be returned exclusively locked. If NOLOCK is
1562 * requested the chain will be returned only referenced.
1564 * NULL is returned if no match was found, but (*parentp) will still
1565 * potentially be adjusted.
1567 * On return (*key_nextp) will point to an iterative value for key_beg.
1568 * (If NULL is returned (*key_nextp) is set to key_end).
1570 * This function will also recurse up the chain if the key is not within the
1571 * current parent's range. (*parentp) can never be set to NULL. An iteration
1572 * can simply allow (*parentp) to float inside the loop.
1574 * NOTE! chain->data is not always resolved. By default it will not be
1575 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1576 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1577 * BREF_TYPE_DATA as the device buffer can alias the logical file
1581 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1582 hammer2_key_t key_beg, hammer2_key_t key_end,
1583 int *cache_indexp, int flags, int *ddflagp)
1585 hammer2_mount_t *hmp;
1586 hammer2_chain_t *parent;
1587 hammer2_chain_t *chain;
1588 hammer2_blockref_t *base;
1589 hammer2_blockref_t *bref;
1590 hammer2_blockref_t bcopy;
1591 hammer2_key_t scan_beg;
1592 hammer2_key_t scan_end;
1594 int how_always = HAMMER2_RESOLVE_ALWAYS;
1595 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1598 int maxloops = 300000;
1601 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1602 how_maybe = how_always;
1603 how = HAMMER2_RESOLVE_ALWAYS;
1604 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1605 how = HAMMER2_RESOLVE_NEVER;
1607 how = HAMMER2_RESOLVE_MAYBE;
1609 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1610 how_maybe |= HAMMER2_RESOLVE_SHARED;
1611 how_always |= HAMMER2_RESOLVE_SHARED;
1612 how |= HAMMER2_RESOLVE_SHARED;
1616 * Recurse (*parentp) upward if necessary until the parent completely
1617 * encloses the key range or we hit the inode.
1619 * This function handles races against the flusher doing a delete-
1620 * duplicate above us and re-homes the parent to the duplicate in
1621 * that case, otherwise we'd wind up recursing down a stale chain.
1626 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1627 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1628 scan_beg = parent->bref.key;
1629 scan_end = scan_beg +
1630 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1631 if (key_beg >= scan_beg && key_end <= scan_end)
1633 parent = hammer2_chain_getparent(parentp, how_maybe);
1637 if (--maxloops == 0)
1638 panic("hammer2_chain_lookup: maxloops");
1640 * Locate the blockref array. Currently we do a fully associative
1641 * search through the array.
1643 switch(parent->bref.type) {
1644 case HAMMER2_BREF_TYPE_INODE:
1646 * Special shortcut for embedded data returns the inode
1647 * itself. Callers must detect this condition and access
1648 * the embedded data (the strategy code does this for us).
1650 * This is only applicable to regular files and softlinks.
1652 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1653 if (flags & HAMMER2_LOOKUP_NOLOCK)
1654 hammer2_chain_ref(parent);
1656 hammer2_chain_lock(parent, how_always);
1657 *key_nextp = key_end + 1;
1661 base = &parent->data->ipdata.u.blockset.blockref[0];
1662 count = HAMMER2_SET_COUNT;
1664 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1665 case HAMMER2_BREF_TYPE_INDIRECT:
1667 * Handle MATCHIND on the parent
1669 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1670 scan_beg = parent->bref.key;
1671 scan_end = scan_beg +
1672 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1673 if (key_beg == scan_beg && key_end == scan_end) {
1675 hammer2_chain_lock(chain, how_maybe);
1676 *key_nextp = scan_end + 1;
1681 * Optimize indirect blocks in the INITIAL state to avoid
1684 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1687 if (parent->data == NULL)
1688 panic("parent->data is NULL");
1689 base = &parent->data->npdata[0];
1691 count = parent->bytes / sizeof(hammer2_blockref_t);
1693 case HAMMER2_BREF_TYPE_VOLUME:
1694 base = &hmp->voldata.sroot_blockset.blockref[0];
1695 count = HAMMER2_SET_COUNT;
1697 case HAMMER2_BREF_TYPE_FREEMAP:
1698 base = &hmp->voldata.freemap_blockset.blockref[0];
1699 count = HAMMER2_SET_COUNT;
1702 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1704 base = NULL; /* safety */
1705 count = 0; /* safety */
1709 * Merged scan to find next candidate.
1711 * hammer2_base_*() functions require the parent->core.live_* fields
1712 * to be synchronized.
1714 * We need to hold the spinlock to access the block array and RB tree
1715 * and to interlock chain creation.
1717 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1718 hammer2_chain_countbrefs(parent, base, count);
1723 spin_lock(&parent->core.cst.spin);
1724 chain = hammer2_combined_find(parent, base, count,
1725 cache_indexp, key_nextp,
1728 generation = parent->core.generation;
1731 * Exhausted parent chain, iterate.
1734 spin_unlock(&parent->core.cst.spin);
1735 if (key_beg == key_end) /* short cut single-key case */
1739 * Stop if we reached the end of the iteration.
1741 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1742 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1747 * Calculate next key, stop if we reached the end of the
1748 * iteration, otherwise go up one level and loop.
1750 key_beg = parent->bref.key +
1751 ((hammer2_key_t)1 << parent->bref.keybits);
1752 if (key_beg == 0 || key_beg > key_end)
1754 parent = hammer2_chain_getparent(parentp, how_maybe);
1759 * Selected from blockref or in-memory chain.
1761 if (chain == NULL) {
1763 spin_unlock(&parent->core.cst.spin);
1764 chain = hammer2_chain_get(parent, generation,
1766 if (chain == NULL) {
1767 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1768 parent, key_beg, key_end);
1771 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1772 hammer2_chain_drop(chain);
1776 hammer2_chain_ref(chain);
1777 spin_unlock(&parent->core.cst.spin);
1781 * chain is referenced but not locked. We must lock the chain
1782 * to obtain definitive DUPLICATED/DELETED state
1784 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1785 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1786 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1788 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1792 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1794 * NOTE: Chain's key range is not relevant as there might be
1795 * one-offs within the range that are not deleted.
1797 * NOTE: Lookups can race delete-duplicate because
1798 * delete-duplicate does not lock the parent's core
1799 * (they just use the spinlock on the core). We must
1800 * check for races by comparing the DUPLICATED flag before
1801 * releasing the spinlock with the flag after locking the
1804 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1805 hammer2_chain_unlock(chain);
1806 key_beg = *key_nextp;
1807 if (key_beg == 0 || key_beg > key_end)
1813 * If the chain element is an indirect block it becomes the new
1814 * parent and we loop on it. We must maintain our top-down locks
1815 * to prevent the flusher from interfering (i.e. doing a
1816 * delete-duplicate and leaving us recursing down a deleted chain).
1818 * The parent always has to be locked with at least RESOLVE_MAYBE
1819 * so we can access its data. It might need a fixup if the caller
1820 * passed incompatible flags. Be careful not to cause a deadlock
1821 * as a data-load requires an exclusive lock.
1823 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1824 * range is within the requested key range we return the indirect
1825 * block and do NOT loop. This is usually only used to acquire
1828 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1829 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1830 hammer2_chain_unlock(parent);
1831 *parentp = parent = chain;
1836 * All done, return the chain
1842 * After having issued a lookup we can iterate all matching keys.
1844 * If chain is non-NULL we continue the iteration from just after it's index.
1846 * If chain is NULL we assume the parent was exhausted and continue the
1847 * iteration at the next parent.
1849 * parent must be locked on entry and remains locked throughout. chain's
1850 * lock status must match flags. Chain is always at least referenced.
1852 * WARNING! The MATCHIND flag does not apply to this function.
1855 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1856 hammer2_key_t *key_nextp,
1857 hammer2_key_t key_beg, hammer2_key_t key_end,
1858 int *cache_indexp, int flags)
1860 hammer2_chain_t *parent;
1865 * Calculate locking flags for upward recursion.
1867 how_maybe = HAMMER2_RESOLVE_MAYBE;
1868 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1869 how_maybe |= HAMMER2_RESOLVE_SHARED;
1874 * Calculate the next index and recalculate the parent if necessary.
1877 key_beg = chain->bref.key +
1878 ((hammer2_key_t)1 << chain->bref.keybits);
1879 if (flags & HAMMER2_LOOKUP_NOLOCK)
1880 hammer2_chain_drop(chain);
1882 hammer2_chain_unlock(chain);
1885 * Any scan where the lookup returned degenerate data embedded
1886 * in the inode has an invalid index and must terminate.
1888 if (chain == parent)
1890 if (key_beg == 0 || key_beg > key_end)
1893 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1894 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1896 * We reached the end of the iteration.
1901 * Continue iteration with next parent unless the current
1902 * parent covers the range.
1904 key_beg = parent->bref.key +
1905 ((hammer2_key_t)1 << parent->bref.keybits);
1906 if (key_beg == 0 || key_beg > key_end)
1908 parent = hammer2_chain_getparent(parentp, how_maybe);
1914 return (hammer2_chain_lookup(parentp, key_nextp,
1916 cache_indexp, flags, &ddflag));
1920 * The raw scan function is similar to lookup/next but does not seek to a key.
1921 * Blockrefs are iterated via first_chain = (parent, NULL) and
1922 * next_chain = (parent, chain).
1924 * The passed-in parent must be locked and its data resolved. The returned
1925 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1926 * under parent and then iterate with the passed-in chain (which this
1927 * function will unlock).
1930 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1931 int *cache_indexp, int flags)
1933 hammer2_mount_t *hmp;
1934 hammer2_blockref_t *base;
1935 hammer2_blockref_t *bref;
1936 hammer2_blockref_t bcopy;
1938 hammer2_key_t next_key;
1940 int how_always = HAMMER2_RESOLVE_ALWAYS;
1941 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1944 int maxloops = 300000;
1949 * Scan flags borrowed from lookup
1951 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1952 how_maybe = how_always;
1953 how = HAMMER2_RESOLVE_ALWAYS;
1954 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1955 how = HAMMER2_RESOLVE_NEVER;
1957 how = HAMMER2_RESOLVE_MAYBE;
1959 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1960 how_maybe |= HAMMER2_RESOLVE_SHARED;
1961 how_always |= HAMMER2_RESOLVE_SHARED;
1962 how |= HAMMER2_RESOLVE_SHARED;
1966 * Calculate key to locate first/next element, unlocking the previous
1967 * element as we go. Be careful, the key calculation can overflow.
1970 key = chain->bref.key +
1971 ((hammer2_key_t)1 << chain->bref.keybits);
1972 hammer2_chain_unlock(chain);
1981 if (--maxloops == 0)
1982 panic("hammer2_chain_scan: maxloops");
1984 * Locate the blockref array. Currently we do a fully associative
1985 * search through the array.
1987 switch(parent->bref.type) {
1988 case HAMMER2_BREF_TYPE_INODE:
1990 * An inode with embedded data has no sub-chains.
1992 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1994 base = &parent->data->ipdata.u.blockset.blockref[0];
1995 count = HAMMER2_SET_COUNT;
1997 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1998 case HAMMER2_BREF_TYPE_INDIRECT:
2000 * Optimize indirect blocks in the INITIAL state to avoid
2003 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2006 if (parent->data == NULL)
2007 panic("parent->data is NULL");
2008 base = &parent->data->npdata[0];
2010 count = parent->bytes / sizeof(hammer2_blockref_t);
2012 case HAMMER2_BREF_TYPE_VOLUME:
2013 base = &hmp->voldata.sroot_blockset.blockref[0];
2014 count = HAMMER2_SET_COUNT;
2016 case HAMMER2_BREF_TYPE_FREEMAP:
2017 base = &hmp->voldata.freemap_blockset.blockref[0];
2018 count = HAMMER2_SET_COUNT;
2021 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2023 base = NULL; /* safety */
2024 count = 0; /* safety */
2028 * Merged scan to find next candidate.
2030 * hammer2_base_*() functions require the parent->core.live_* fields
2031 * to be synchronized.
2033 * We need to hold the spinlock to access the block array and RB tree
2034 * and to interlock chain creation.
2036 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2037 hammer2_chain_countbrefs(parent, base, count);
2040 spin_lock(&parent->core.cst.spin);
2041 chain = hammer2_combined_find(parent, base, count,
2042 cache_indexp, &next_key,
2043 key, HAMMER2_KEY_MAX,
2045 generation = parent->core.generation;
2048 * Exhausted parent chain, we're done.
2051 spin_unlock(&parent->core.cst.spin);
2052 KKASSERT(chain == NULL);
2057 * Selected from blockref or in-memory chain.
2059 if (chain == NULL) {
2061 spin_unlock(&parent->core.cst.spin);
2062 chain = hammer2_chain_get(parent, generation, &bcopy);
2063 if (chain == NULL) {
2064 kprintf("retry scan parent %p keys %016jx\n",
2068 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2069 hammer2_chain_drop(chain);
2074 hammer2_chain_ref(chain);
2075 spin_unlock(&parent->core.cst.spin);
2079 * chain is referenced but not locked. We must lock the chain
2080 * to obtain definitive DUPLICATED/DELETED state
2082 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2085 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2087 * NOTE: chain's key range is not relevant as there might be
2088 * one-offs within the range that are not deleted.
2090 * NOTE: XXX this could create problems with scans used in
2091 * situations other than mount-time recovery.
2093 * NOTE: Lookups can race delete-duplicate because
2094 * delete-duplicate does not lock the parent's core
2095 * (they just use the spinlock on the core). We must
2096 * check for races by comparing the DUPLICATED flag before
2097 * releasing the spinlock with the flag after locking the
2100 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2101 hammer2_chain_unlock(chain);
2112 * All done, return the chain or NULL
2118 * Create and return a new hammer2 system memory structure of the specified
2119 * key, type and size and insert it under (*parentp). This is a full
2120 * insertion, based on the supplied key/keybits, and may involve creating
2121 * indirect blocks and moving other chains around via delete/duplicate.
2123 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2124 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2125 * FULL. This typically means that the caller is creating the chain after
2126 * doing a hammer2_chain_lookup().
2128 * (*parentp) must be exclusive locked and may be replaced on return
2129 * depending on how much work the function had to do.
2131 * (*chainp) usually starts out NULL and returns the newly created chain,
2132 * but if the caller desires the caller may allocate a disconnected chain
2133 * and pass it in instead.
2135 * This function should NOT be used to insert INDIRECT blocks. It is
2136 * typically used to create/insert inodes and data blocks.
2138 * Caller must pass-in an exclusively locked parent the new chain is to
2139 * be inserted under, and optionally pass-in a disconnected, exclusively
2140 * locked chain to insert (else we create a new chain). The function will
2141 * adjust (*parentp) as necessary, create or connect the chain, and
2142 * return an exclusively locked chain in *chainp.
2145 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2146 hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2147 hammer2_key_t key, int keybits, int type, size_t bytes)
2149 hammer2_mount_t *hmp;
2150 hammer2_chain_t *chain;
2151 hammer2_chain_t *parent;
2152 hammer2_blockref_t *base;
2153 hammer2_blockref_t dummy;
2157 int maxloops = 300000;
2160 * Topology may be crossing a PFS boundary.
2163 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2167 if (chain == NULL) {
2169 * First allocate media space and construct the dummy bref,
2170 * then allocate the in-memory chain structure. Set the
2171 * INITIAL flag for fresh chains which do not have embedded
2174 bzero(&dummy, sizeof(dummy));
2177 dummy.keybits = keybits;
2178 dummy.data_off = hammer2_getradix(bytes);
2179 dummy.methods = parent->bref.methods;
2180 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2181 hammer2_chain_core_alloc(trans, chain);
2184 * Lock the chain manually, chain_lock will load the chain
2185 * which we do NOT want to do. (note: chain->refs is set
2186 * to 1 by chain_alloc() for us, but lockcnt is not).
2189 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
2193 * We do NOT set INITIAL here (yet). INITIAL is only
2194 * used for indirect blocks.
2196 * Recalculate bytes to reflect the actual media block
2199 bytes = (hammer2_off_t)1 <<
2200 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2201 chain->bytes = bytes;
2204 case HAMMER2_BREF_TYPE_VOLUME:
2205 case HAMMER2_BREF_TYPE_FREEMAP:
2206 panic("hammer2_chain_create: called with volume type");
2208 case HAMMER2_BREF_TYPE_INDIRECT:
2209 panic("hammer2_chain_create: cannot be used to"
2210 "create indirect block");
2212 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2213 panic("hammer2_chain_create: cannot be used to"
2214 "create freemap root or node");
2216 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2217 KKASSERT(bytes == sizeof(chain->data->bmdata));
2219 case HAMMER2_BREF_TYPE_INODE:
2220 case HAMMER2_BREF_TYPE_DATA:
2223 * leave chain->data NULL, set INITIAL
2225 KKASSERT(chain->data == NULL);
2226 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2231 * We are reattaching a previously deleted chain, possibly
2232 * under a new parent and possibly with a new key/keybits.
2233 * The chain does not have to be in a modified state. The
2234 * UPDATE flag will be set later on in this routine.
2236 * Do NOT mess with the current state of the INITIAL flag.
2238 chain->bref.key = key;
2239 chain->bref.keybits = keybits;
2240 if (chain->flags & HAMMER2_CHAIN_DELETED)
2241 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2242 KKASSERT(chain->parent == NULL);
2246 * Calculate how many entries we have in the blockref array and
2247 * determine if an indirect block is required.
2250 if (--maxloops == 0)
2251 panic("hammer2_chain_create: maxloops");
2253 switch(parent->bref.type) {
2254 case HAMMER2_BREF_TYPE_INODE:
2255 KKASSERT((parent->data->ipdata.op_flags &
2256 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2257 KKASSERT(parent->data != NULL);
2258 base = &parent->data->ipdata.u.blockset.blockref[0];
2259 count = HAMMER2_SET_COUNT;
2261 case HAMMER2_BREF_TYPE_INDIRECT:
2262 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2263 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2266 base = &parent->data->npdata[0];
2267 count = parent->bytes / sizeof(hammer2_blockref_t);
2269 case HAMMER2_BREF_TYPE_VOLUME:
2270 KKASSERT(parent->data != NULL);
2271 base = &hmp->voldata.sroot_blockset.blockref[0];
2272 count = HAMMER2_SET_COUNT;
2274 case HAMMER2_BREF_TYPE_FREEMAP:
2275 KKASSERT(parent->data != NULL);
2276 base = &hmp->voldata.freemap_blockset.blockref[0];
2277 count = HAMMER2_SET_COUNT;
2280 panic("hammer2_chain_create: unrecognized blockref type: %d",
2288 * Make sure we've counted the brefs
2290 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2291 hammer2_chain_countbrefs(parent, base, count);
2293 KKASSERT(parent->core.live_count >= 0 &&
2294 parent->core.live_count <= count);
2297 * If no free blockref could be found we must create an indirect
2298 * block and move a number of blockrefs into it. With the parent
2299 * locked we can safely lock each child in order to delete+duplicate
2300 * it without causing a deadlock.
2302 * This may return the new indirect block or the old parent depending
2303 * on where the key falls. NULL is returned on error.
2305 if (parent->core.live_count == count) {
2306 hammer2_chain_t *nparent;
2308 nparent = hammer2_chain_create_indirect(trans, parent,
2311 if (nparent == NULL) {
2313 hammer2_chain_drop(chain);
2317 if (parent != nparent) {
2318 hammer2_chain_unlock(parent);
2319 parent = *parentp = nparent;
2325 * Link the chain into its parent.
2327 if (chain->parent != NULL)
2328 panic("hammer2: hammer2_chain_create: chain already connected");
2329 KKASSERT(chain->parent == NULL);
2330 hammer2_chain_insert(parent, chain,
2331 HAMMER2_CHAIN_INSERT_SPIN |
2332 HAMMER2_CHAIN_INSERT_LIVE,
2337 * Mark the newly created chain modified. This will cause
2340 * Device buffers are not instantiated for DATA elements
2341 * as these are handled by logical buffers.
2343 * Indirect and freemap node indirect blocks are handled
2344 * by hammer2_chain_create_indirect() and not by this
2347 * Data for all other bref types is expected to be
2348 * instantiated (INODE, LEAF).
2350 switch(chain->bref.type) {
2351 case HAMMER2_BREF_TYPE_DATA:
2352 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2353 case HAMMER2_BREF_TYPE_INODE:
2354 hammer2_chain_modify(trans, chain,
2355 HAMMER2_MODIFY_OPTDATA |
2356 HAMMER2_MODIFY_ASSERTNOCOPY);
2360 * Remaining types are not supported by this function.
2361 * In particular, INDIRECT and LEAF_NODE types are
2362 * handled by create_indirect().
2364 panic("hammer2_chain_create: bad type: %d",
2371 * When reconnecting a chain we must set UPDATE and
2372 * setflush so the flush recognizes that it must update
2373 * the bref in the parent.
2375 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2376 hammer2_chain_ref(chain);
2377 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2382 * We must setflush(parent) to ensure that it recurses through to
2383 * chain. setflush(chain) might not work because ONFLUSH is possibly
2384 * already set in the chain (so it won't recurse up to set it in the
2387 hammer2_chain_setflush(trans, parent);
2396 * Move the chain from its old parent to a new parent. The chain must have
2397 * already been deleted or already disconnected (or never associated) with
2398 * a parent. The chain is reassociated with the new parent and the deleted
2399 * flag will be cleared (no longer deleted). The chain's modification state
2402 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2403 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2404 * FULL. This typically means that the caller is creating the chain after
2405 * doing a hammer2_chain_lookup().
2407 * A non-NULL bref is typically passed when key and keybits must be overridden.
2408 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2409 * from a passed-in bref and uses the old chain's bref for everything else.
2411 * If (parent) is non-NULL then the new duplicated chain is inserted under
2414 * If (parent) is NULL then the newly duplicated chain is not inserted
2415 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2416 * passing into hammer2_chain_create() after this function returns).
2418 * WARNING! This function calls create which means it can insert indirect
2419 * blocks. This can cause other unrelated chains in the parent to
2420 * be moved to a newly inserted indirect block in addition to the
2424 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2425 hammer2_chain_t **parentp, hammer2_chain_t *chain)
2427 hammer2_mount_t *hmp;
2428 hammer2_chain_t *parent;
2432 * WARNING! We should never resolve DATA to device buffers
2433 * (XXX allow it if the caller did?), and since
2434 * we currently do not have the logical buffer cache
2435 * buffer in-hand to fix its cached physical offset
2436 * we also force the modify code to not COW it. XXX
2439 KKASSERT(chain->parent == NULL);
2442 * Now create a duplicate of the chain structure, associating
2443 * it with the same core, making it the same size, pointing it
2444 * to the same bref (the same media block).
2447 bref = &chain->bref;
2448 bytes = (hammer2_off_t)1 <<
2449 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2452 * If parent is not NULL the duplicated chain will be entered under
2453 * the parent and the UPDATE bit set to tell flush to update
2456 * We must setflush(parent) to ensure that it recurses through to
2457 * chain. setflush(chain) might not work because ONFLUSH is possibly
2458 * already set in the chain (so it won't recurse up to set it in the
2461 * Having both chains locked is extremely important for atomicy.
2463 if (parentp && (parent = *parentp) != NULL) {
2464 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2465 KKASSERT(parent->refs > 0);
2467 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2468 bref->key, bref->keybits, bref->type,
2470 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2471 hammer2_chain_setflush(trans, *parentp);
2476 * Helper function for deleting chains.
2478 * The chain is removed from the live view (the RBTREE) as well as the parent's
2479 * blockmap. Both chain and its parent must be locked.
2482 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2483 hammer2_chain_t *parent, hammer2_chain_t *chain)
2485 hammer2_mount_t *hmp;
2487 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2490 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2492 * Chain is blockmapped, so there must be a parent.
2493 * Atomically remove the chain from the parent and remove
2494 * the blockmap entry.
2496 hammer2_blockref_t *base;
2499 KKASSERT(parent != NULL);
2500 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2501 hammer2_chain_modify(trans, parent,
2502 HAMMER2_MODIFY_OPTDATA);
2505 * Calculate blockmap pointer
2507 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2508 spin_lock(&parent->core.cst.spin);
2510 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2511 atomic_add_int(&parent->core.live_count, -1);
2512 ++parent->core.generation;
2513 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2514 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2515 --parent->core.chain_count;
2516 chain->parent = NULL;
2518 switch(parent->bref.type) {
2519 case HAMMER2_BREF_TYPE_INODE:
2521 * Access the inode's block array. However, there
2522 * is no block array if the inode is flagged
2523 * DIRECTDATA. The DIRECTDATA case typicaly only
2524 * occurs when a hardlink has been shifted up the
2525 * tree and the original inode gets replaced with
2526 * an OBJTYPE_HARDLINK placeholding inode.
2529 (parent->data->ipdata.op_flags &
2530 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2532 &parent->data->ipdata.u.blockset.blockref[0];
2536 count = HAMMER2_SET_COUNT;
2538 case HAMMER2_BREF_TYPE_INDIRECT:
2539 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2541 base = &parent->data->npdata[0];
2544 count = parent->bytes / sizeof(hammer2_blockref_t);
2546 case HAMMER2_BREF_TYPE_VOLUME:
2547 base = &hmp->voldata.sroot_blockset.blockref[0];
2548 count = HAMMER2_SET_COUNT;
2550 case HAMMER2_BREF_TYPE_FREEMAP:
2551 base = &parent->data->npdata[0];
2552 count = HAMMER2_SET_COUNT;
2557 panic("hammer2_flush_pass2: "
2558 "unrecognized blockref type: %d",
2562 int cache_index = -1;
2563 hammer2_base_delete(trans, parent, base, count,
2564 &cache_index, chain);
2566 spin_unlock(&parent->core.cst.spin);
2567 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2569 * Chain is not blockmapped but a parent is present.
2570 * Atomically remove the chain from the parent. There is
2571 * no blockmap entry to remove.
2573 spin_lock(&parent->core.cst.spin);
2574 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2575 atomic_add_int(&parent->core.live_count, -1);
2576 ++parent->core.generation;
2577 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2578 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2579 --parent->core.chain_count;
2580 chain->parent = NULL;
2581 spin_unlock(&parent->core.cst.spin);
2584 * Chain is not blockmapped and has no parent. This
2585 * is a degenerate case.
2587 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2592 * Create an indirect block that covers one or more of the elements in the
2593 * current parent. Either returns the existing parent with no locking or
2594 * ref changes or returns the new indirect block locked and referenced
2595 * and leaving the original parent lock/ref intact as well.
2597 * If an error occurs, NULL is returned and *errorp is set to the error.
2599 * The returned chain depends on where the specified key falls.
2601 * The key/keybits for the indirect mode only needs to follow three rules:
2603 * (1) That all elements underneath it fit within its key space and
2605 * (2) That all elements outside it are outside its key space.
2607 * (3) When creating the new indirect block any elements in the current
2608 * parent that fit within the new indirect block's keyspace must be
2609 * moved into the new indirect block.
2611 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2612 * keyspace the the current parent, but lookup/iteration rules will
2613 * ensure (and must ensure) that rule (2) for all parents leading up
2614 * to the nearest inode or the root volume header is adhered to. This
2615 * is accomplished by always recursing through matching keyspaces in
2616 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2618 * The current implementation calculates the current worst-case keyspace by
2619 * iterating the current parent and then divides it into two halves, choosing
2620 * whichever half has the most elements (not necessarily the half containing
2621 * the requested key).
2623 * We can also opt to use the half with the least number of elements. This
2624 * causes lower-numbered keys (aka logical file offsets) to recurse through
2625 * fewer indirect blocks and higher-numbered keys to recurse through more.
2626 * This also has the risk of not moving enough elements to the new indirect
2627 * block and being forced to create several indirect blocks before the element
2630 * Must be called with an exclusively locked parent.
2632 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2633 hammer2_key_t *keyp, int keybits,
2634 hammer2_blockref_t *base, int count);
2635 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2636 hammer2_key_t *keyp, int keybits,
2637 hammer2_blockref_t *base, int count);
2640 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2641 hammer2_key_t create_key, int create_bits,
2642 int for_type, int *errorp)
2644 hammer2_mount_t *hmp;
2645 hammer2_blockref_t *base;
2646 hammer2_blockref_t *bref;
2647 hammer2_blockref_t bcopy;
2648 hammer2_chain_t *chain;
2649 hammer2_chain_t *ichain;
2650 hammer2_chain_t dummy;
2651 hammer2_key_t key = create_key;
2652 hammer2_key_t key_beg;
2653 hammer2_key_t key_end;
2654 hammer2_key_t key_next;
2655 int keybits = create_bits;
2662 int maxloops = 300000;
2665 * Calculate the base blockref pointer or NULL if the chain
2666 * is known to be empty. We need to calculate the array count
2667 * for RB lookups either way.
2671 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2673 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2674 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2677 switch(parent->bref.type) {
2678 case HAMMER2_BREF_TYPE_INODE:
2679 count = HAMMER2_SET_COUNT;
2681 case HAMMER2_BREF_TYPE_INDIRECT:
2682 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2683 count = parent->bytes / sizeof(hammer2_blockref_t);
2685 case HAMMER2_BREF_TYPE_VOLUME:
2686 count = HAMMER2_SET_COUNT;
2688 case HAMMER2_BREF_TYPE_FREEMAP:
2689 count = HAMMER2_SET_COUNT;
2692 panic("hammer2_chain_create_indirect: "
2693 "unrecognized blockref type: %d",
2699 switch(parent->bref.type) {
2700 case HAMMER2_BREF_TYPE_INODE:
2701 base = &parent->data->ipdata.u.blockset.blockref[0];
2702 count = HAMMER2_SET_COUNT;
2704 case HAMMER2_BREF_TYPE_INDIRECT:
2705 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2706 base = &parent->data->npdata[0];
2707 count = parent->bytes / sizeof(hammer2_blockref_t);
2709 case HAMMER2_BREF_TYPE_VOLUME:
2710 base = &hmp->voldata.sroot_blockset.blockref[0];
2711 count = HAMMER2_SET_COUNT;
2713 case HAMMER2_BREF_TYPE_FREEMAP:
2714 base = &hmp->voldata.freemap_blockset.blockref[0];
2715 count = HAMMER2_SET_COUNT;
2718 panic("hammer2_chain_create_indirect: "
2719 "unrecognized blockref type: %d",
2727 * dummy used in later chain allocation (no longer used for lookups).
2729 bzero(&dummy, sizeof(dummy));
2732 * When creating an indirect block for a freemap node or leaf
2733 * the key/keybits must be fitted to static radix levels because
2734 * particular radix levels use particular reserved blocks in the
2737 * This routine calculates the key/radix of the indirect block
2738 * we need to create, and whether it is on the high-side or the
2741 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2742 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2743 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2746 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2751 * Normalize the key for the radix being represented, keeping the
2752 * high bits and throwing away the low bits.
2754 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2757 * How big should our new indirect block be? It has to be at least
2758 * as large as its parent.
2760 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2761 nbytes = HAMMER2_IND_BYTES_MIN;
2763 nbytes = HAMMER2_IND_BYTES_MAX;
2764 if (nbytes < count * sizeof(hammer2_blockref_t))
2765 nbytes = count * sizeof(hammer2_blockref_t);
2768 * Ok, create our new indirect block
2770 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2771 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2772 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2774 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2776 dummy.bref.key = key;
2777 dummy.bref.keybits = keybits;
2778 dummy.bref.data_off = hammer2_getradix(nbytes);
2779 dummy.bref.methods = parent->bref.methods;
2781 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2782 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2783 hammer2_chain_core_alloc(trans, ichain);
2784 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2785 hammer2_chain_drop(ichain); /* excess ref from alloc */
2788 * We have to mark it modified to allocate its block, but use
2789 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2790 * it won't be acted upon by the flush code.
2792 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2795 * Iterate the original parent and move the matching brefs into
2796 * the new indirect block.
2798 * XXX handle flushes.
2801 key_end = HAMMER2_KEY_MAX;
2803 spin_lock(&parent->core.cst.spin);
2808 if (++loops > 100000) {
2809 spin_unlock(&parent->core.cst.spin);
2810 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2811 reason, parent, base, count, key_next);
2815 * NOTE: spinlock stays intact, returned chain (if not NULL)
2816 * is not referenced or locked which means that we
2817 * cannot safely check its flagged / deletion status
2820 chain = hammer2_combined_find(parent, base, count,
2821 &cache_index, &key_next,
2824 generation = parent->core.generation;
2827 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2830 * Skip keys that are not within the key/radix of the new
2831 * indirect block. They stay in the parent.
2833 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2834 (key ^ bref->key)) != 0) {
2835 goto next_key_spinlocked;
2839 * Load the new indirect block by acquiring the related
2840 * chains (potentially from media as it might not be
2841 * in-memory). Then move it to the new parent (ichain)
2842 * via DELETE-DUPLICATE.
2844 * chain is referenced but not locked. We must lock the
2845 * chain to obtain definitive DUPLICATED/DELETED state
2849 * Use chain already present in the RBTREE
2851 hammer2_chain_ref(chain);
2852 spin_unlock(&parent->core.cst.spin);
2853 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2854 HAMMER2_RESOLVE_NOREF);
2857 * Get chain for blockref element. _get returns NULL
2858 * on insertion race.
2861 spin_unlock(&parent->core.cst.spin);
2862 chain = hammer2_chain_get(parent, generation, &bcopy);
2863 if (chain == NULL) {
2865 spin_lock(&parent->core.cst.spin);
2868 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2869 kprintf("REASON 2\n");
2871 hammer2_chain_drop(chain);
2872 spin_lock(&parent->core.cst.spin);
2875 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2876 HAMMER2_RESOLVE_NOREF);
2880 * This is always live so if the chain has been deleted
2881 * we raced someone and we have to retry.
2883 * NOTE: Lookups can race delete-duplicate because
2884 * delete-duplicate does not lock the parent's core
2885 * (they just use the spinlock on the core). We must
2886 * check for races by comparing the DUPLICATED flag before
2887 * releasing the spinlock with the flag after locking the
2890 * (note reversed logic for this one)
2892 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2893 hammer2_chain_unlock(chain);
2898 * Shift the chain to the indirect block.
2900 * WARNING! Can cause held-over chains to require a refactor.
2901 * Fortunately we have none (our locked chains are
2902 * passed into and modified by the call).
2904 hammer2_chain_delete(trans, parent, chain, 0);
2905 hammer2_chain_rename(trans, NULL, &ichain, chain);
2906 hammer2_chain_unlock(chain);
2907 KKASSERT(parent->refs > 0);
2910 spin_lock(&parent->core.cst.spin);
2911 next_key_spinlocked:
2912 if (--maxloops == 0)
2913 panic("hammer2_chain_create_indirect: maxloops");
2915 if (key_next == 0 || key_next > key_end)
2920 spin_unlock(&parent->core.cst.spin);
2923 * Insert the new indirect block into the parent now that we've
2924 * cleared out some entries in the parent. We calculated a good
2925 * insertion index in the loop above (ichain->index).
2927 * We don't have to set UPDATE here because we mark ichain
2928 * modified down below (so the normal modified -> flush -> set-moved
2929 * sequence applies).
2931 * The insertion shouldn't race as this is a completely new block
2932 * and the parent is locked.
2934 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2935 hammer2_chain_insert(parent, ichain,
2936 HAMMER2_CHAIN_INSERT_SPIN |
2937 HAMMER2_CHAIN_INSERT_LIVE,
2941 * Make sure flushes propogate after our manual insertion.
2943 hammer2_chain_setflush(trans, ichain);
2944 hammer2_chain_setflush(trans, parent);
2947 * Figure out what to return.
2949 if (~(((hammer2_key_t)1 << keybits) - 1) &
2950 (create_key ^ key)) {
2952 * Key being created is outside the key range,
2953 * return the original parent.
2955 hammer2_chain_unlock(ichain);
2958 * Otherwise its in the range, return the new parent.
2959 * (leave both the new and old parent locked).
2968 * Calculate the keybits and highside/lowside of the freemap node the
2969 * caller is creating.
2971 * This routine will specify the next higher-level freemap key/radix
2972 * representing the lowest-ordered set. By doing so, eventually all
2973 * low-ordered sets will be moved one level down.
2975 * We have to be careful here because the freemap reserves a limited
2976 * number of blocks for a limited number of levels. So we can't just
2977 * push indiscriminately.
2980 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2981 int keybits, hammer2_blockref_t *base, int count)
2983 hammer2_chain_t *chain;
2984 hammer2_blockref_t *bref;
2986 hammer2_key_t key_beg;
2987 hammer2_key_t key_end;
2988 hammer2_key_t key_next;
2992 int maxloops = 300000;
3000 * Calculate the range of keys in the array being careful to skip
3001 * slots which are overridden with a deletion.
3004 key_end = HAMMER2_KEY_MAX;
3006 spin_lock(&parent->core.cst.spin);
3009 if (--maxloops == 0) {
3010 panic("indkey_freemap shit %p %p:%d\n",
3011 parent, base, count);
3013 chain = hammer2_combined_find(parent, base, count,
3014 &cache_index, &key_next,
3025 * Skip deleted chains.
3027 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3028 if (key_next == 0 || key_next > key_end)
3035 * Use the full live (not deleted) element for the scan
3036 * iteration. HAMMER2 does not allow partial replacements.
3038 * XXX should be built into hammer2_combined_find().
3040 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3042 if (keybits > bref->keybits) {
3044 keybits = bref->keybits;
3045 } else if (keybits == bref->keybits && bref->key < key) {
3052 spin_unlock(&parent->core.cst.spin);
3055 * Return the keybits for a higher-level FREEMAP_NODE covering
3059 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3060 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3062 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3063 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3065 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3066 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3068 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3069 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3071 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3072 panic("hammer2_chain_indkey_freemap: level too high");
3075 panic("hammer2_chain_indkey_freemap: bad radix");
3084 * Calculate the keybits and highside/lowside of the indirect block the
3085 * caller is creating.
3088 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3089 int keybits, hammer2_blockref_t *base, int count)
3091 hammer2_blockref_t *bref;
3092 hammer2_chain_t *chain;
3093 hammer2_key_t key_beg;
3094 hammer2_key_t key_end;
3095 hammer2_key_t key_next;
3101 int maxloops = 300000;
3108 * Calculate the range of keys in the array being careful to skip
3109 * slots which are overridden with a deletion. Once the scan
3110 * completes we will cut the key range in half and shift half the
3111 * range into the new indirect block.
3114 key_end = HAMMER2_KEY_MAX;
3116 spin_lock(&parent->core.cst.spin);
3119 if (--maxloops == 0) {
3120 panic("indkey_freemap shit %p %p:%d\n",
3121 parent, base, count);
3123 chain = hammer2_combined_find(parent, base, count,
3124 &cache_index, &key_next,
3135 * NOTE: No need to check DUPLICATED here because we do
3136 * not release the spinlock.
3138 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3139 if (key_next == 0 || key_next > key_end)
3146 * Use the full live (not deleted) element for the scan
3147 * iteration. HAMMER2 does not allow partial replacements.
3149 * XXX should be built into hammer2_combined_find().
3151 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3154 * Expand our calculated key range (key, keybits) to fit
3155 * the scanned key. nkeybits represents the full range
3156 * that we will later cut in half (two halves @ nkeybits - 1).
3159 if (nkeybits < bref->keybits) {
3160 if (bref->keybits > 64) {
3161 kprintf("bad bref chain %p bref %p\n",
3165 nkeybits = bref->keybits;
3167 while (nkeybits < 64 &&
3168 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3169 (key ^ bref->key)) != 0) {
3174 * If the new key range is larger we have to determine
3175 * which side of the new key range the existing keys fall
3176 * under by checking the high bit, then collapsing the
3177 * locount into the hicount or vise-versa.
3179 if (keybits != nkeybits) {
3180 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3191 * The newly scanned key will be in the lower half or the
3192 * upper half of the (new) key range.
3194 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3203 spin_unlock(&parent->core.cst.spin);
3204 bref = NULL; /* now invalid (safety) */
3207 * Adjust keybits to represent half of the full range calculated
3208 * above (radix 63 max)
3213 * Select whichever half contains the most elements. Theoretically
3214 * we can select either side as long as it contains at least one
3215 * element (in order to ensure that a free slot is present to hold
3216 * the indirect block).
3218 if (hammer2_indirect_optimize) {
3220 * Insert node for least number of keys, this will arrange
3221 * the first few blocks of a large file or the first few
3222 * inodes in a directory with fewer indirect blocks when
3225 if (hicount < locount && hicount != 0)
3226 key |= (hammer2_key_t)1 << keybits;
3228 key &= ~(hammer2_key_t)1 << keybits;
3231 * Insert node for most number of keys, best for heavily
3234 if (hicount > locount)
3235 key |= (hammer2_key_t)1 << keybits;
3237 key &= ~(hammer2_key_t)1 << keybits;
3245 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3248 * Both parent and chain must be locked exclusively.
3250 * This function will modify the parent if the blockref requires removal
3251 * from the parent's block table.
3253 * This function is NOT recursive. Any entity already pushed into the
3254 * chain (such as an inode) may still need visibility into its contents,
3255 * as well as the ability to read and modify the contents. For example,
3256 * for an unlinked file which is still open.
3259 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3260 hammer2_chain_t *chain, int flags)
3262 KKASSERT(ccms_thread_lock_owned(&chain->core.cst));
3265 * Nothing to do if already marked.
3267 * We need the spinlock on the core whos RBTREE contains chain
3268 * to protect against races.
3270 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3271 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3272 chain->parent == parent);
3273 _hammer2_chain_delete_helper(trans, parent, chain);
3276 if (flags & HAMMER2_DELETE_PERMANENT) {
3277 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3278 hammer2_flush(trans, chain);
3280 /* XXX might not be needed */
3281 hammer2_chain_setflush(trans, chain);
3286 * Returns the index of the nearest element in the blockref array >= elm.
3287 * Returns (count) if no element could be found.
3289 * Sets *key_nextp to the next key for loop purposes but does not modify
3290 * it if the next key would be higher than the current value of *key_nextp.
3291 * Note that *key_nexp can overflow to 0, which should be tested by the
3294 * (*cache_indexp) is a heuristic and can be any value without effecting
3297 * The spin lock on the related chain must be held.
3300 hammer2_base_find(hammer2_chain_t *parent,
3301 hammer2_blockref_t *base, int count,
3302 int *cache_indexp, hammer2_key_t *key_nextp,
3303 hammer2_key_t key_beg, hammer2_key_t key_end)
3305 hammer2_blockref_t *scan;
3306 hammer2_key_t scan_end;
3311 * Require the live chain's already have their core's counted
3312 * so we can optimize operations.
3314 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3319 if (count == 0 || base == NULL)
3323 * Sequential optimization using *cache_indexp. This is the most
3326 * We can avoid trailing empty entries on live chains, otherwise
3327 * we might have to check the whole block array.
3331 limit = parent->core.live_zero;
3336 KKASSERT(i < count);
3342 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3349 * Search forwards, stop when we find a scan element which
3350 * encloses the key or until we know that there are no further
3354 if (scan->type != 0) {
3355 scan_end = scan->key +
3356 ((hammer2_key_t)1 << scan->keybits) - 1;
3357 if (scan->key > key_beg || scan_end >= key_beg)
3370 scan_end = scan->key +
3371 ((hammer2_key_t)1 << scan->keybits);
3372 if (scan_end && (*key_nextp > scan_end ||
3374 *key_nextp = scan_end;
3382 * Do a combined search and return the next match either from the blockref
3383 * array or from the in-memory chain. Sets *bresp to the returned bref in
3384 * both cases, or sets it to NULL if the search exhausted. Only returns
3385 * a non-NULL chain if the search matched from the in-memory chain.
3387 * When no in-memory chain has been found and a non-NULL bref is returned
3390 * Must be called with parent's spinlock held. Spinlock remains held
3391 * through the operation.
3393 * The returned chain is not locked or referenced. Use the returned bref
3394 * to determine if the search exhausted or not. Iterate if the base find
3395 * is chosen but matches a deleted chain.
3397 static hammer2_chain_t *
3398 hammer2_combined_find(hammer2_chain_t *parent,
3399 hammer2_blockref_t *base, int count,
3400 int *cache_indexp, hammer2_key_t *key_nextp,
3401 hammer2_key_t key_beg, hammer2_key_t key_end,
3402 hammer2_blockref_t **bresp)
3404 hammer2_blockref_t *bref;
3405 hammer2_chain_t *chain;
3409 * Lookup in block array and in rbtree.
3411 *key_nextp = key_end + 1;
3412 i = hammer2_base_find(parent, base, count, cache_indexp,
3413 key_nextp, key_beg, key_end);
3414 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3419 if (i == count && chain == NULL) {
3425 * Only chain matched.
3428 bref = &chain->bref;
3433 * Only blockref matched.
3435 if (chain == NULL) {
3441 * Both in-memory and blockref matched, select the nearer element.
3443 * If both are flush with the left-hand side or both are the
3444 * same distance away, select the chain. In this situation the
3445 * chain must have been loaded from the matching blockmap.
3447 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3448 chain->bref.key == base[i].key) {
3449 KKASSERT(chain->bref.key == base[i].key);
3450 bref = &chain->bref;
3455 * Select the nearer key
3457 if (chain->bref.key < base[i].key) {
3458 bref = &chain->bref;
3465 * If the bref is out of bounds we've exhausted our search.
3468 if (bref->key > key_end) {
3478 * Locate the specified block array element and delete it. The element
3481 * The spin lock on the related chain must be held.
3483 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3484 * need to be adjusted when we commit the media change.
3487 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3488 hammer2_blockref_t *base, int count,
3489 int *cache_indexp, hammer2_chain_t *chain)
3491 hammer2_blockref_t *elm = &chain->bref;
3492 hammer2_key_t key_next;
3496 * Delete element. Expect the element to exist.
3498 * XXX see caller, flush code not yet sophisticated enough to prevent
3499 * re-flushed in some cases.
3501 key_next = 0; /* max range */
3502 i = hammer2_base_find(parent, base, count, cache_indexp,
3503 &key_next, elm->key, elm->key);
3504 if (i == count || base[i].type == 0 ||
3505 base[i].key != elm->key ||
3506 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3507 base[i].keybits != elm->keybits)) {
3508 spin_unlock(&parent->core.cst.spin);
3509 panic("delete base %p element not found at %d/%d elm %p\n",
3510 base, i, count, elm);
3513 bzero(&base[i], sizeof(*base));
3516 * We can only optimize parent->core.live_zero for live chains.
3518 if (parent->core.live_zero == i + 1) {
3519 while (--i >= 0 && base[i].type == 0)
3521 parent->core.live_zero = i + 1;
3525 * Clear appropriate blockmap flags in chain.
3527 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3528 HAMMER2_CHAIN_BMAPUPD);
3532 * Insert the specified element. The block array must not already have the
3533 * element and must have space available for the insertion.
3535 * The spin lock on the related chain must be held.
3537 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3538 * need to be adjusted when we commit the media change.
3541 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3542 hammer2_blockref_t *base, int count,
3543 int *cache_indexp, hammer2_chain_t *chain)
3545 hammer2_blockref_t *elm = &chain->bref;
3546 hammer2_key_t key_next;
3555 * Insert new element. Expect the element to not already exist
3556 * unless we are replacing it.
3558 * XXX see caller, flush code not yet sophisticated enough to prevent
3559 * re-flushed in some cases.
3561 key_next = 0; /* max range */
3562 i = hammer2_base_find(parent, base, count, cache_indexp,
3563 &key_next, elm->key, elm->key);
3566 * Shortcut fill optimization, typical ordered insertion(s) may not
3569 KKASSERT(i >= 0 && i <= count);
3572 * Set appropriate blockmap flags in chain.
3574 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3577 * We can only optimize parent->core.live_zero for live chains.
3579 if (i == count && parent->core.live_zero < count) {
3580 i = parent->core.live_zero++;
3585 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3586 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3587 spin_unlock(&parent->core.cst.spin);
3588 panic("insert base %p overlapping elements at %d elm %p\n",
3593 * Try to find an empty slot before or after.
3597 while (j > 0 || k < count) {
3599 if (j >= 0 && base[j].type == 0) {
3603 bcopy(&base[j+1], &base[j],
3604 (i - j - 1) * sizeof(*base));
3610 if (k < count && base[k].type == 0) {
3611 bcopy(&base[i], &base[i+1],
3612 (k - i) * sizeof(hammer2_blockref_t));
3616 * We can only update parent->core.live_zero for live
3619 if (parent->core.live_zero <= k)
3620 parent->core.live_zero = k + 1;
3625 panic("hammer2_base_insert: no room!");
3632 for (l = 0; l < count; ++l) {
3634 key_next = base[l].key +
3635 ((hammer2_key_t)1 << base[l].keybits) - 1;
3639 while (++l < count) {
3641 if (base[l].key <= key_next)
3642 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3643 key_next = base[l].key +
3644 ((hammer2_key_t)1 << base[l].keybits) - 1;
3654 * Sort the blockref array for the chain. Used by the flush code to
3655 * sort the blockref[] array.
3657 * The chain must be exclusively locked AND spin-locked.
3659 typedef hammer2_blockref_t *hammer2_blockref_p;
3663 hammer2_base_sort_callback(const void *v1, const void *v2)
3665 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3666 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3669 * Make sure empty elements are placed at the end of the array
3671 if (bref1->type == 0) {
3672 if (bref2->type == 0)
3675 } else if (bref2->type == 0) {
3682 if (bref1->key < bref2->key)
3684 if (bref1->key > bref2->key)
3690 hammer2_base_sort(hammer2_chain_t *chain)
3692 hammer2_blockref_t *base;
3695 switch(chain->bref.type) {
3696 case HAMMER2_BREF_TYPE_INODE:
3698 * Special shortcut for embedded data returns the inode
3699 * itself. Callers must detect this condition and access
3700 * the embedded data (the strategy code does this for us).
3702 * This is only applicable to regular files and softlinks.
3704 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3706 base = &chain->data->ipdata.u.blockset.blockref[0];
3707 count = HAMMER2_SET_COUNT;
3709 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3710 case HAMMER2_BREF_TYPE_INDIRECT:
3712 * Optimize indirect blocks in the INITIAL state to avoid
3715 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3716 base = &chain->data->npdata[0];
3717 count = chain->bytes / sizeof(hammer2_blockref_t);
3719 case HAMMER2_BREF_TYPE_VOLUME:
3720 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3721 count = HAMMER2_SET_COUNT;
3723 case HAMMER2_BREF_TYPE_FREEMAP:
3724 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3725 count = HAMMER2_SET_COUNT;
3728 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3730 base = NULL; /* safety */
3731 count = 0; /* safety */
3733 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3739 * Chain memory management
3742 hammer2_chain_wait(hammer2_chain_t *chain)
3744 tsleep(chain, 0, "chnflw", 1);