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.
243 * (can be called with spinlock held)
246 hammer2_chain_ref(hammer2_chain_t *chain)
248 atomic_add_int(&chain->refs, 1);
252 * Insert the chain in the core rbtree.
254 * Normal insertions are placed in the live rbtree. Insertion of a deleted
255 * chain is a special case used by the flush code that is placed on the
256 * unstaged deleted list to avoid confusing the live view.
258 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
259 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
260 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
264 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
265 int flags, int generation)
267 hammer2_chain_t *xchain;
270 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
271 spin_lock(&parent->core.cst.spin);
274 * Interlocked by spinlock, check for race
276 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
277 parent->core.generation != generation) {
285 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
286 KASSERT(xchain == NULL,
287 ("hammer2_chain_insert: collision %p %p", chain, xchain));
288 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
289 chain->parent = parent;
290 ++parent->core.chain_count;
291 ++parent->core.generation; /* XXX incs for _get() too, XXX */
294 * We have to keep track of the effective live-view blockref count
295 * so the create code knows when to push an indirect block.
297 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
298 atomic_add_int(&parent->core.live_count, 1);
300 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
301 spin_unlock(&parent->core.cst.spin);
306 * Drop the caller's reference to the chain. When the ref count drops to
307 * zero this function will try to disassociate the chain from its parent and
308 * deallocate it, then recursely drop the parent using the implied ref
309 * from the chain's chain->parent.
311 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
314 hammer2_chain_drop(hammer2_chain_t *chain)
319 if (hammer2_debug & 0x200000)
322 if (chain->flags & HAMMER2_CHAIN_UPDATE)
324 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
326 KKASSERT(chain->refs > need);
334 chain = hammer2_chain_lastdrop(chain);
336 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
338 /* retry the same chain */
344 * Safe handling of the 1->0 transition on chain. Returns a chain for
345 * recursive drop or NULL, possibly returning the same chain if the atomic
348 * Whem two chains need to be recursively dropped we use the chain
349 * we would otherwise free to placehold the additional chain. It's a bit
350 * convoluted but we can't just recurse without potentially blowing out
353 * The chain cannot be freed if it has a non-empty core (children) or
354 * it is not at the head of ownerq.
356 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
360 hammer2_chain_lastdrop(hammer2_chain_t *chain)
362 hammer2_pfsmount_t *pmp;
363 hammer2_mount_t *hmp;
364 hammer2_chain_t *parent;
365 hammer2_chain_t *rdrop;
368 * Spinlock the core and check to see if it is empty. If it is
369 * not empty we leave chain intact with refs == 0. The elements
370 * in core->rbtree are associated with other chains contemporary
371 * with ours but not with our chain directly.
373 spin_lock(&chain->core.cst.spin);
376 * We can't free non-stale chains with children until we are
377 * able to free the children because there might be a flush
378 * dependency. Flushes of stale children (which should also
379 * have their deleted flag set) short-cut recursive flush
380 * dependencies and can be freed here. Any flushes which run
381 * through stale children due to the flush synchronization
382 * point should have a FLUSH_* bit set in the chain and not
383 * reach lastdrop at this time.
385 * NOTE: We return (chain) on failure to retry.
387 if (chain->core.chain_count) {
388 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
389 spin_unlock(&chain->core.cst.spin);
390 chain = NULL; /* success */
392 spin_unlock(&chain->core.cst.spin);
396 /* no chains left under us */
399 * chain->core has no children left so no accessors can get to our
400 * chain from there. Now we have to lock the parent core to interlock
401 * remaining possible accessors that might bump chain's refs before
402 * we can safely drop chain's refs with intent to free the chain.
405 pmp = chain->pmp; /* can be NULL */
409 * Spinlock the parent and try to drop the last ref on chain.
410 * On success remove chain from its parent, otherwise return NULL.
412 * (normal core locks are top-down recursive but we define core
413 * spinlocks as bottom-up recursive, so this is safe).
415 if ((parent = chain->parent) != NULL) {
416 spin_lock(&parent->core.cst.spin);
417 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
418 /* 1->0 transition failed */
419 spin_unlock(&parent->core.cst.spin);
420 spin_unlock(&chain->core.cst.spin);
421 return(chain); /* retry */
425 * 1->0 transition successful, remove chain from its
428 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
429 RB_REMOVE(hammer2_chain_tree,
430 &parent->core.rbtree, chain);
431 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
432 --parent->core.chain_count;
433 chain->parent = NULL;
437 * If our chain was the last chain in the parent's core the
438 * core is now empty and its parent might have to be
439 * re-dropped if it has 0 refs.
441 if (parent->core.chain_count == 0) {
443 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
447 spin_unlock(&parent->core.cst.spin);
448 parent = NULL; /* safety */
452 * Successful 1->0 transition and the chain can be destroyed now.
454 * We still have the core spinlock, and core's chain_count is 0.
455 * Any parent spinlock is gone.
457 spin_unlock(&chain->core.cst.spin);
458 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
459 chain->core.chain_count == 0);
460 KKASSERT(chain->core.cst.count == 0);
461 KKASSERT(chain->core.cst.upgrade == 0);
464 * All spin locks are gone, finish freeing stuff.
466 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
467 HAMMER2_CHAIN_MODIFIED)) == 0);
468 hammer2_chain_drop_data(chain, 1);
470 KKASSERT(chain->dio == NULL);
473 * Once chain resources are gone we can use the now dead chain
474 * structure to placehold what might otherwise require a recursive
475 * drop, because we have potentially two things to drop and can only
476 * return one directly.
478 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
479 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
481 kfree(chain, hmp->mchain);
485 * Possible chaining loop when parent re-drop needed.
491 * On either last lock release or last drop
494 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
496 /*hammer2_mount_t *hmp = chain->hmp;*/
498 switch(chain->bref.type) {
499 case HAMMER2_BREF_TYPE_VOLUME:
500 case HAMMER2_BREF_TYPE_FREEMAP:
505 KKASSERT(chain->data == NULL);
511 * Ref and lock a chain element, acquiring its data with I/O if necessary,
512 * and specify how you would like the data to be resolved.
514 * Returns 0 on success or an error code if the data could not be acquired.
515 * The chain element is locked on return regardless of whether an error
518 * The lock is allowed to recurse, multiple locking ops will aggregate
519 * the requested resolve types. Once data is assigned it will not be
520 * removed until the last unlock.
522 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
523 * (typically used to avoid device/logical buffer
526 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
527 * the INITIAL-create state (indirect blocks only).
529 * Do not resolve data elements for DATA chains.
530 * (typically used to avoid device/logical buffer
533 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
535 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
536 * it will be locked exclusive.
538 * NOTE: Embedded elements (volume header, inodes) are always resolved
541 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
542 * element will instantiate and zero its buffer, and flush it on
545 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
546 * so as not to instantiate a device buffer, which could alias against
547 * a logical file buffer. However, if ALWAYS is specified the
548 * device buffer will be instantiated anyway.
550 * WARNING! If data must be fetched a shared lock will temporarily be
551 * upgraded to exclusive. However, a deadlock can occur if
552 * the caller owns more than one shared lock.
555 hammer2_chain_lock(hammer2_chain_t *chain, int how)
557 hammer2_mount_t *hmp;
558 hammer2_blockref_t *bref;
564 * Ref and lock the element. Recursive locks are allowed.
566 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
567 hammer2_chain_ref(chain);
568 atomic_add_int(&chain->lockcnt, 1);
571 KKASSERT(hmp != NULL);
574 * Get the appropriate lock.
576 if (how & HAMMER2_RESOLVE_SHARED)
577 ccms_thread_lock(&chain->core.cst, CCMS_STATE_SHARED);
579 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
582 * If we already have a valid data pointer no further action is
589 * Do we have to resolve the data?
591 switch(how & HAMMER2_RESOLVE_MASK) {
592 case HAMMER2_RESOLVE_NEVER:
594 case HAMMER2_RESOLVE_MAYBE:
595 if (chain->flags & HAMMER2_CHAIN_INITIAL)
597 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
600 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
603 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
606 case HAMMER2_RESOLVE_ALWAYS:
611 * Upgrade to an exclusive lock so we can safely manipulate the
612 * buffer cache. If another thread got to it before us we
615 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
617 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
622 * We must resolve to a device buffer, either by issuing I/O or
623 * by creating a zero-fill element. We do not mark the buffer
624 * dirty when creating a zero-fill element (the hammer2_chain_modify()
625 * API must still be used to do that).
627 * The device buffer is variable-sized in powers of 2 down
628 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
629 * chunk always contains buffers of the same size. (XXX)
631 * The minimum physical IO size may be larger than the variable
637 * The getblk() optimization can only be used on newly created
638 * elements if the physical block size matches the request.
640 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
641 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
644 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
646 hammer2_adjreadcounter(&chain->bref, chain->bytes);
650 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
651 (intmax_t)bref->data_off, error);
652 hammer2_io_bqrelse(&chain->dio);
653 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
659 * No need for this, always require that hammer2_chain_modify()
660 * be called before any modifying operations.
662 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
663 !hammer2_io_isdirty(chain->dio)) {
664 hammer2_io_setdirty(chain->dio);
669 * Clear INITIAL. In this case we used io_new() and the buffer has
670 * been zero'd and marked dirty.
672 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
673 if (chain->flags & HAMMER2_CHAIN_INITIAL)
674 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
677 * Setup the data pointer, either pointing it to an embedded data
678 * structure and copying the data from the buffer, or pointing it
681 * The buffer is not retained when copying to an embedded data
682 * structure in order to avoid potential deadlocks or recursions
683 * on the same physical buffer.
685 switch (bref->type) {
686 case HAMMER2_BREF_TYPE_VOLUME:
687 case HAMMER2_BREF_TYPE_FREEMAP:
689 * Copy data from bp to embedded buffer
691 panic("hammer2_chain_lock: called on unresolved volume header");
693 case HAMMER2_BREF_TYPE_INODE:
694 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
695 case HAMMER2_BREF_TYPE_INDIRECT:
696 case HAMMER2_BREF_TYPE_DATA:
697 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
700 * Point data at the device buffer and leave dio intact.
702 chain->data = (void *)bdata;
705 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
710 * This basically calls hammer2_io_breadcb() but does some pre-processing
711 * of the chain first to handle certain cases.
714 hammer2_chain_load_async(hammer2_cluster_t *cluster,
715 void (*callback)(hammer2_io_t *dio,
716 hammer2_cluster_t *cluster,
717 hammer2_chain_t *chain,
718 void *arg_p, off_t arg_o),
721 hammer2_chain_t *chain;
722 hammer2_mount_t *hmp;
723 struct hammer2_io *dio;
724 hammer2_blockref_t *bref;
729 * If no chain specified see if any chain data is available and use
730 * that, otherwise begin an I/O iteration using the first chain.
733 for (i = 0; i < cluster->nchains; ++i) {
734 chain = cluster->array[i];
735 if (chain && chain->data)
738 if (i == cluster->nchains) {
739 chain = cluster->array[0];
744 callback(NULL, cluster, chain, arg_p, (off_t)i);
749 * We must resolve to a device buffer, either by issuing I/O or
750 * by creating a zero-fill element. We do not mark the buffer
751 * dirty when creating a zero-fill element (the hammer2_chain_modify()
752 * API must still be used to do that).
754 * The device buffer is variable-sized in powers of 2 down
755 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
756 * chunk always contains buffers of the same size. (XXX)
758 * The minimum physical IO size may be larger than the variable
765 * The getblk() optimization can only be used on newly created
766 * elements if the physical block size matches the request.
768 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
769 chain->bytes == hammer2_devblksize(chain->bytes)) {
770 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
771 KKASSERT(error == 0);
772 callback(dio, cluster, chain, arg_p, (off_t)i);
777 * Otherwise issue a read
779 hammer2_adjreadcounter(&chain->bref, chain->bytes);
780 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
781 callback, cluster, chain, arg_p, (off_t)i);
785 * Unlock and deref a chain element.
787 * On the last lock release any non-embedded data (chain->dio) will be
791 hammer2_chain_unlock(hammer2_chain_t *chain)
798 * The core->cst lock can be shared across several chains so we
799 * need to track the per-chain lockcnt separately.
801 * If multiple locks are present (or being attempted) on this
802 * particular chain we can just unlock, drop refs, and return.
804 * Otherwise fall-through on the 1->0 transition.
807 lockcnt = chain->lockcnt;
808 KKASSERT(lockcnt > 0);
811 if (atomic_cmpset_int(&chain->lockcnt,
812 lockcnt, lockcnt - 1)) {
813 ccms_thread_unlock(&chain->core.cst);
814 hammer2_chain_drop(chain);
818 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
825 * On the 1->0 transition we upgrade the core lock (if necessary)
826 * to exclusive for terminal processing. If after upgrading we find
827 * that lockcnt is non-zero, another thread is racing us and will
828 * handle the unload for us later on, so just cleanup and return
829 * leaving the data/io intact
831 * Otherwise if lockcnt is still 0 it is possible for it to become
832 * non-zero and race, but since we hold the core->cst lock
833 * exclusively all that will happen is that the chain will be
834 * reloaded after we unload it.
836 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
837 if (chain->lockcnt) {
838 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
839 hammer2_chain_drop(chain);
844 * Shortcut the case if the data is embedded or not resolved.
846 * Do NOT NULL out chain->data (e.g. inode data), it might be
849 if (chain->dio == NULL) {
850 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
851 hammer2_chain_drop_data(chain, 0);
852 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
853 hammer2_chain_drop(chain);
860 if (hammer2_io_isdirty(chain->dio) == 0) {
862 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
863 switch(chain->bref.type) {
864 case HAMMER2_BREF_TYPE_DATA:
865 counterp = &hammer2_ioa_file_write;
867 case HAMMER2_BREF_TYPE_INODE:
868 counterp = &hammer2_ioa_meta_write;
870 case HAMMER2_BREF_TYPE_INDIRECT:
871 counterp = &hammer2_ioa_indr_write;
873 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
874 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
875 counterp = &hammer2_ioa_fmap_write;
878 counterp = &hammer2_ioa_volu_write;
881 *counterp += chain->bytes;
883 switch(chain->bref.type) {
884 case HAMMER2_BREF_TYPE_DATA:
885 counterp = &hammer2_iod_file_write;
887 case HAMMER2_BREF_TYPE_INODE:
888 counterp = &hammer2_iod_meta_write;
890 case HAMMER2_BREF_TYPE_INDIRECT:
891 counterp = &hammer2_iod_indr_write;
893 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
894 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
895 counterp = &hammer2_iod_fmap_write;
898 counterp = &hammer2_iod_volu_write;
901 *counterp += chain->bytes;
907 * If a device buffer was used for data be sure to destroy the
908 * buffer when we are done to avoid aliases (XXX what about the
909 * underlying VM pages?).
911 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
914 * NOTE: The isdirty check tracks whether we have to bdwrite() the
915 * buffer or not. The buffer might already be dirty. The
916 * flag is re-set when chain_modify() is called, even if
917 * MODIFIED is already set, allowing the OS to retire the
918 * buffer independent of a hammer2 flush.
921 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
922 hammer2_io_isdirty(chain->dio)) {
923 hammer2_io_bawrite(&chain->dio);
925 hammer2_io_bqrelse(&chain->dio);
927 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
928 hammer2_chain_drop(chain);
932 * This counts the number of live blockrefs in a block array and
933 * also calculates the point at which all remaining blockrefs are empty.
934 * This routine can only be called on a live chain (DUPLICATED flag not set).
936 * NOTE: Flag is not set until after the count is complete, allowing
937 * callers to test the flag without holding the spinlock.
939 * NOTE: If base is NULL the related chain is still in the INITIAL
940 * state and there are no blockrefs to count.
942 * NOTE: live_count may already have some counts accumulated due to
943 * creation and deletion and could even be initially negative.
946 hammer2_chain_countbrefs(hammer2_chain_t *chain,
947 hammer2_blockref_t *base, int count)
949 spin_lock(&chain->core.cst.spin);
950 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
952 while (--count >= 0) {
953 if (base[count].type)
956 chain->core.live_zero = count + 1;
958 if (base[count].type)
959 atomic_add_int(&chain->core.live_count,
964 chain->core.live_zero = 0;
966 /* else do not modify live_count */
967 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
969 spin_unlock(&chain->core.cst.spin);
973 * Resize the chain's physical storage allocation in-place. This function does
974 * not adjust the data pointer and must be followed by (typically) a
975 * hammer2_chain_modify() call to copy any old data over and adjust the
978 * Chains can be resized smaller without reallocating the storage. Resizing
979 * larger will reallocate the storage. Excess or prior storage is reclaimed
980 * asynchronously at a later time.
982 * Must be passed an exclusively locked parent and chain.
984 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
985 * to avoid instantiating a device buffer that conflicts with the vnode data
986 * buffer. However, because H2 can compress or encrypt data, the chain may
987 * have a dio assigned to it in those situations, and they do not conflict.
989 * XXX return error if cannot resize.
992 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
993 hammer2_chain_t *parent, hammer2_chain_t *chain,
994 int nradix, int flags)
996 hammer2_mount_t *hmp;
1003 * Only data and indirect blocks can be resized for now.
1004 * (The volu root, inodes, and freemap elements use a fixed size).
1006 KKASSERT(chain != &hmp->vchain);
1007 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1008 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1011 * Nothing to do if the element is already the proper size
1013 obytes = chain->bytes;
1014 nbytes = 1U << nradix;
1015 if (obytes == nbytes)
1019 * Make sure the old data is instantiated so we can copy it. If this
1020 * is a data block, the device data may be superfluous since the data
1021 * might be in a logical block, but compressed or encrypted data is
1024 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1026 hammer2_chain_modify(trans, chain, 0);
1029 * Relocate the block, even if making it smaller (because different
1030 * block sizes may be in different regions).
1032 * (data blocks only, we aren't copying the storage here).
1034 hammer2_freemap_alloc(trans, chain, nbytes);
1035 chain->bytes = nbytes;
1036 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1037 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1040 * We don't want the followup chain_modify() to try to copy data
1041 * from the old (wrong-sized) buffer. It won't know how much to
1042 * copy. This case should only occur during writes when the
1043 * originator already has the data to write in-hand.
1046 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1047 hammer2_io_brelse(&chain->dio);
1055 * REMOVED - see cluster code
1057 * Set a chain modified, making it read-write and duplicating it if necessary.
1058 * This function will assign a new physical block to the chain if necessary
1060 * Duplication of already-modified chains is possible when the modification
1061 * crosses a flush synchronization boundary.
1063 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1064 * level or the COW operation will not work.
1066 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1067 * run the data through the device buffers.
1069 * This function may return a different chain than was passed, in which case
1070 * the old chain will be unlocked and the new chain will be locked.
1072 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1074 hammer2_inode_data_t *
1075 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1076 hammer2_chain_t **chainp, int flags)
1078 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1079 hammer2_chain_modify(trans, chainp, flags);
1080 if (ip->chain != *chainp)
1081 hammer2_inode_repoint(ip, NULL, *chainp);
1083 vsetisdirty(ip->vp);
1084 return(&ip->chain->data->ipdata);
1090 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1092 hammer2_mount_t *hmp;
1102 * data is not optional for freemap chains (we must always be sure
1103 * to copy the data on COW storage allocations).
1105 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1106 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1107 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1108 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1112 * Data must be resolved if already assigned unless explicitly
1113 * flagged otherwise.
1115 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1116 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1117 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1118 hammer2_chain_unlock(chain);
1122 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1123 * that the chain has been modified. Set UPDATE to ensure that
1124 * the blockref is updated in the parent.
1126 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1127 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1128 hammer2_chain_ref(chain);
1129 hammer2_pfs_memory_inc(chain->pmp);
1134 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1135 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1136 hammer2_chain_ref(chain);
1140 * The modification or re-modification requires an allocation and
1143 * We normally always allocate new storage here. If storage exists
1144 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1146 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1147 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1148 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1150 hammer2_freemap_alloc(trans, chain, chain->bytes);
1151 /* XXX failed allocation */
1152 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1153 hammer2_freemap_alloc(trans, chain, chain->bytes);
1154 /* XXX failed allocation */
1156 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1160 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1161 * requires updating as well as to tell the delete code that the
1162 * chain's blockref might not exactly match (in terms of physical size
1163 * or block offset) the one in the parent's blocktable. The base key
1164 * of course will still match.
1166 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1167 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1170 * Do not COW BREF_TYPE_DATA when OPTDATA is set. This is because
1171 * data modifications are done via the logical buffer cache so COWing
1172 * it here would result in unnecessary extra copies (and possibly extra
1173 * block reallocations). The INITIAL flag remains unchanged in this
1176 * (This is a bit of a hack).
1178 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1179 (flags & HAMMER2_MODIFY_OPTDATA)) {
1184 * Clearing the INITIAL flag (for indirect blocks) indicates that
1185 * we've processed the uninitialized storage allocation.
1187 * If this flag is already clear we are likely in a copy-on-write
1188 * situation but we have to be sure NOT to bzero the storage if
1189 * no data is present.
1191 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1192 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1199 * Instantiate data buffer and possibly execute COW operation
1201 switch(chain->bref.type) {
1202 case HAMMER2_BREF_TYPE_VOLUME:
1203 case HAMMER2_BREF_TYPE_FREEMAP:
1205 * The data is embedded, no copy-on-write operation is
1208 KKASSERT(chain->dio == NULL);
1210 case HAMMER2_BREF_TYPE_INODE:
1211 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1212 case HAMMER2_BREF_TYPE_DATA:
1213 case HAMMER2_BREF_TYPE_INDIRECT:
1214 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1216 * Perform the copy-on-write operation
1218 * zero-fill or copy-on-write depending on whether
1219 * chain->data exists or not and set the dirty state for
1220 * the new buffer. hammer2_io_new() will handle the
1223 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1226 error = hammer2_io_new(hmp, chain->bref.data_off,
1227 chain->bytes, &dio);
1229 error = hammer2_io_bread(hmp, chain->bref.data_off,
1230 chain->bytes, &dio);
1232 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1233 KKASSERT(error == 0);
1235 bdata = hammer2_io_data(dio, chain->bref.data_off);
1238 KKASSERT(chain->dio != NULL);
1239 if (chain->data != (void *)bdata) {
1240 bcopy(chain->data, bdata, chain->bytes);
1242 } else if (wasinitial == 0) {
1244 * We have a problem. We were asked to COW but
1245 * we don't have any data to COW with!
1247 panic("hammer2_chain_modify: having a COW %p\n",
1252 * Retire the old buffer, replace with the new
1255 hammer2_io_brelse(&chain->dio);
1256 chain->data = (void *)bdata;
1258 hammer2_io_setdirty(dio); /* modified by bcopy above */
1261 panic("hammer2_chain_modify: illegal non-embedded type %d",
1268 * setflush on parent indicating that the parent must recurse down
1269 * to us. Do not call on chain itself which might already have it
1273 hammer2_chain_setflush(trans, chain->parent);
1277 * Volume header data locks
1280 hammer2_voldata_lock(hammer2_mount_t *hmp)
1282 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1286 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1288 lockmgr(&hmp->vollk, LK_RELEASE);
1292 hammer2_voldata_modify(hammer2_mount_t *hmp)
1294 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1295 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1296 hammer2_chain_ref(&hmp->vchain);
1297 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1302 * This function returns the chain at the nearest key within the specified
1303 * range. The returned chain will be referenced but not locked.
1305 * This function will recurse through chain->rbtree as necessary and will
1306 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1307 * the iteration value is less than the current value of *key_nextp.
1309 * The caller should use (*key_nextp) to calculate the actual range of
1310 * the returned element, which will be (key_beg to *key_nextp - 1), because
1311 * there might be another element which is superior to the returned element
1314 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1315 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1316 * it will wind up being (key_end + 1).
1318 * WARNING! Must be called with child's spinlock held. Spinlock remains
1319 * held through the operation.
1321 struct hammer2_chain_find_info {
1322 hammer2_chain_t *best;
1323 hammer2_key_t key_beg;
1324 hammer2_key_t key_end;
1325 hammer2_key_t key_next;
1328 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1329 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1333 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1334 hammer2_key_t key_beg, hammer2_key_t key_end)
1336 struct hammer2_chain_find_info info;
1339 info.key_beg = key_beg;
1340 info.key_end = key_end;
1341 info.key_next = *key_nextp;
1343 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1344 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1346 *key_nextp = info.key_next;
1348 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1349 parent, key_beg, key_end, *key_nextp);
1357 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1359 struct hammer2_chain_find_info *info = data;
1360 hammer2_key_t child_beg;
1361 hammer2_key_t child_end;
1363 child_beg = child->bref.key;
1364 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1366 if (child_end < info->key_beg)
1368 if (child_beg > info->key_end)
1375 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1377 struct hammer2_chain_find_info *info = data;
1378 hammer2_chain_t *best;
1379 hammer2_key_t child_end;
1382 * WARNING! Do not discard DUPLICATED chains, it is possible that
1383 * we are catching an insertion half-way done. If a
1384 * duplicated chain turns out to be the best choice the
1385 * caller will re-check its flags after locking it.
1387 * WARNING! Layerq is scanned forwards, exact matches should keep
1388 * the existing info->best.
1390 if ((best = info->best) == NULL) {
1392 * No previous best. Assign best
1395 } else if (best->bref.key <= info->key_beg &&
1396 child->bref.key <= info->key_beg) {
1401 /*info->best = child;*/
1402 } else if (child->bref.key < best->bref.key) {
1404 * Child has a nearer key and best is not flush with key_beg.
1405 * Set best to child. Truncate key_next to the old best key.
1408 if (info->key_next > best->bref.key || info->key_next == 0)
1409 info->key_next = best->bref.key;
1410 } else if (child->bref.key == best->bref.key) {
1412 * If our current best is flush with the child then this
1413 * is an illegal overlap.
1415 * key_next will automatically be limited to the smaller of
1416 * the two end-points.
1422 * Keep the current best but truncate key_next to the child's
1425 * key_next will also automatically be limited to the smaller
1426 * of the two end-points (probably not necessary for this case
1427 * but we do it anyway).
1429 if (info->key_next > child->bref.key || info->key_next == 0)
1430 info->key_next = child->bref.key;
1434 * Always truncate key_next based on child's end-of-range.
1436 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1437 if (child_end && (info->key_next > child_end || info->key_next == 0))
1438 info->key_next = child_end;
1444 * Retrieve the specified chain from a media blockref, creating the
1445 * in-memory chain structure which reflects it.
1447 * To handle insertion races pass the INSERT_RACE flag along with the
1448 * generation number of the core. NULL will be returned if the generation
1449 * number changes before we have a chance to insert the chain. Insert
1450 * races can occur because the parent might be held shared.
1452 * Caller must hold the parent locked shared or exclusive since we may
1453 * need the parent's bref array to find our block.
1455 * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1459 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1460 hammer2_blockref_t *bref)
1462 hammer2_mount_t *hmp = parent->hmp;
1463 hammer2_chain_t *chain;
1467 * Allocate a chain structure representing the existing media
1468 * entry. Resulting chain has one ref and is not locked.
1470 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1471 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1473 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1474 hammer2_chain_core_alloc(NULL, chain);
1475 /* ref'd chain returned */
1478 * Flag that the chain is in the parent's blockmap so delete/flush
1479 * knows what to do with it.
1481 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1484 * Link the chain into its parent. A spinlock is required to safely
1485 * access the RBTREE, and it is possible to collide with another
1486 * hammer2_chain_get() operation because the caller might only hold
1487 * a shared lock on the parent.
1489 KKASSERT(parent->refs > 0);
1490 error = hammer2_chain_insert(parent, chain,
1491 HAMMER2_CHAIN_INSERT_SPIN |
1492 HAMMER2_CHAIN_INSERT_RACE,
1495 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1496 kprintf("chain %p get race\n", chain);
1497 hammer2_chain_drop(chain);
1500 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1504 * Return our new chain referenced but not locked, or NULL if
1511 * Lookup initialization/completion API
1514 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1516 if (flags & HAMMER2_LOOKUP_SHARED) {
1517 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1518 HAMMER2_RESOLVE_SHARED);
1520 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1526 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1529 hammer2_chain_unlock(parent);
1534 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1536 hammer2_chain_t *oparent;
1537 hammer2_chain_t *nparent;
1540 * Be careful of order, oparent must be unlocked before nparent
1541 * is locked below to avoid a deadlock.
1544 spin_lock(&oparent->core.cst.spin);
1545 nparent = oparent->parent;
1546 hammer2_chain_ref(nparent);
1547 spin_unlock(&oparent->core.cst.spin);
1549 hammer2_chain_unlock(oparent);
1553 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1560 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1561 * (*parentp) typically points to an inode but can also point to a related
1562 * indirect block and this function will recurse upwards and find the inode
1565 * (*parentp) must be exclusively locked and referenced and can be an inode
1566 * or an existing indirect block within the inode.
1568 * On return (*parentp) will be modified to point at the deepest parent chain
1569 * element encountered during the search, as a helper for an insertion or
1570 * deletion. The new (*parentp) will be locked and referenced and the old
1571 * will be unlocked and dereferenced (no change if they are both the same).
1573 * The matching chain will be returned exclusively locked. If NOLOCK is
1574 * requested the chain will be returned only referenced.
1576 * NULL is returned if no match was found, but (*parentp) will still
1577 * potentially be adjusted.
1579 * On return (*key_nextp) will point to an iterative value for key_beg.
1580 * (If NULL is returned (*key_nextp) is set to key_end).
1582 * This function will also recurse up the chain if the key is not within the
1583 * current parent's range. (*parentp) can never be set to NULL. An iteration
1584 * can simply allow (*parentp) to float inside the loop.
1586 * NOTE! chain->data is not always resolved. By default it will not be
1587 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1588 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1589 * BREF_TYPE_DATA as the device buffer can alias the logical file
1593 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1594 hammer2_key_t key_beg, hammer2_key_t key_end,
1595 int *cache_indexp, int flags, int *ddflagp)
1597 hammer2_mount_t *hmp;
1598 hammer2_chain_t *parent;
1599 hammer2_chain_t *chain;
1600 hammer2_blockref_t *base;
1601 hammer2_blockref_t *bref;
1602 hammer2_blockref_t bcopy;
1603 hammer2_key_t scan_beg;
1604 hammer2_key_t scan_end;
1606 int how_always = HAMMER2_RESOLVE_ALWAYS;
1607 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1610 int maxloops = 300000;
1613 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1614 how_maybe = how_always;
1615 how = HAMMER2_RESOLVE_ALWAYS;
1616 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1617 how = HAMMER2_RESOLVE_NEVER;
1619 how = HAMMER2_RESOLVE_MAYBE;
1621 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1622 how_maybe |= HAMMER2_RESOLVE_SHARED;
1623 how_always |= HAMMER2_RESOLVE_SHARED;
1624 how |= HAMMER2_RESOLVE_SHARED;
1628 * Recurse (*parentp) upward if necessary until the parent completely
1629 * encloses the key range or we hit the inode.
1631 * This function handles races against the flusher doing a delete-
1632 * duplicate above us and re-homes the parent to the duplicate in
1633 * that case, otherwise we'd wind up recursing down a stale chain.
1638 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1639 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1640 scan_beg = parent->bref.key;
1641 scan_end = scan_beg +
1642 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1643 if (key_beg >= scan_beg && key_end <= scan_end)
1645 parent = hammer2_chain_getparent(parentp, how_maybe);
1649 if (--maxloops == 0)
1650 panic("hammer2_chain_lookup: maxloops");
1652 * Locate the blockref array. Currently we do a fully associative
1653 * search through the array.
1655 switch(parent->bref.type) {
1656 case HAMMER2_BREF_TYPE_INODE:
1658 * Special shortcut for embedded data returns the inode
1659 * itself. Callers must detect this condition and access
1660 * the embedded data (the strategy code does this for us).
1662 * This is only applicable to regular files and softlinks.
1664 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1665 if (flags & HAMMER2_LOOKUP_NOLOCK)
1666 hammer2_chain_ref(parent);
1668 hammer2_chain_lock(parent, how_always);
1669 *key_nextp = key_end + 1;
1673 base = &parent->data->ipdata.u.blockset.blockref[0];
1674 count = HAMMER2_SET_COUNT;
1676 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1677 case HAMMER2_BREF_TYPE_INDIRECT:
1679 * Handle MATCHIND on the parent
1681 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1682 scan_beg = parent->bref.key;
1683 scan_end = scan_beg +
1684 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1685 if (key_beg == scan_beg && key_end == scan_end) {
1687 hammer2_chain_lock(chain, how_maybe);
1688 *key_nextp = scan_end + 1;
1693 * Optimize indirect blocks in the INITIAL state to avoid
1696 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1699 if (parent->data == NULL)
1700 panic("parent->data is NULL");
1701 base = &parent->data->npdata[0];
1703 count = parent->bytes / sizeof(hammer2_blockref_t);
1705 case HAMMER2_BREF_TYPE_VOLUME:
1706 base = &hmp->voldata.sroot_blockset.blockref[0];
1707 count = HAMMER2_SET_COUNT;
1709 case HAMMER2_BREF_TYPE_FREEMAP:
1710 base = &hmp->voldata.freemap_blockset.blockref[0];
1711 count = HAMMER2_SET_COUNT;
1714 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1716 base = NULL; /* safety */
1717 count = 0; /* safety */
1721 * Merged scan to find next candidate.
1723 * hammer2_base_*() functions require the parent->core.live_* fields
1724 * to be synchronized.
1726 * We need to hold the spinlock to access the block array and RB tree
1727 * and to interlock chain creation.
1729 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1730 hammer2_chain_countbrefs(parent, base, count);
1735 spin_lock(&parent->core.cst.spin);
1736 chain = hammer2_combined_find(parent, base, count,
1737 cache_indexp, key_nextp,
1740 generation = parent->core.generation;
1743 * Exhausted parent chain, iterate.
1746 spin_unlock(&parent->core.cst.spin);
1747 if (key_beg == key_end) /* short cut single-key case */
1751 * Stop if we reached the end of the iteration.
1753 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1754 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1759 * Calculate next key, stop if we reached the end of the
1760 * iteration, otherwise go up one level and loop.
1762 key_beg = parent->bref.key +
1763 ((hammer2_key_t)1 << parent->bref.keybits);
1764 if (key_beg == 0 || key_beg > key_end)
1766 parent = hammer2_chain_getparent(parentp, how_maybe);
1771 * Selected from blockref or in-memory chain.
1773 if (chain == NULL) {
1775 spin_unlock(&parent->core.cst.spin);
1776 chain = hammer2_chain_get(parent, generation,
1778 if (chain == NULL) {
1779 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1780 parent, key_beg, key_end);
1783 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1784 hammer2_chain_drop(chain);
1788 hammer2_chain_ref(chain);
1789 spin_unlock(&parent->core.cst.spin);
1793 * chain is referenced but not locked. We must lock the chain
1794 * to obtain definitive DUPLICATED/DELETED state
1796 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1797 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1798 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1800 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1804 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1806 * NOTE: Chain's key range is not relevant as there might be
1807 * one-offs within the range that are not deleted.
1809 * NOTE: Lookups can race delete-duplicate because
1810 * delete-duplicate does not lock the parent's core
1811 * (they just use the spinlock on the core). We must
1812 * check for races by comparing the DUPLICATED flag before
1813 * releasing the spinlock with the flag after locking the
1816 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1817 hammer2_chain_unlock(chain);
1818 key_beg = *key_nextp;
1819 if (key_beg == 0 || key_beg > key_end)
1825 * If the chain element is an indirect block it becomes the new
1826 * parent and we loop on it. We must maintain our top-down locks
1827 * to prevent the flusher from interfering (i.e. doing a
1828 * delete-duplicate and leaving us recursing down a deleted chain).
1830 * The parent always has to be locked with at least RESOLVE_MAYBE
1831 * so we can access its data. It might need a fixup if the caller
1832 * passed incompatible flags. Be careful not to cause a deadlock
1833 * as a data-load requires an exclusive lock.
1835 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1836 * range is within the requested key range we return the indirect
1837 * block and do NOT loop. This is usually only used to acquire
1840 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1841 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1842 hammer2_chain_unlock(parent);
1843 *parentp = parent = chain;
1848 * All done, return the chain
1854 * After having issued a lookup we can iterate all matching keys.
1856 * If chain is non-NULL we continue the iteration from just after it's index.
1858 * If chain is NULL we assume the parent was exhausted and continue the
1859 * iteration at the next parent.
1861 * parent must be locked on entry and remains locked throughout. chain's
1862 * lock status must match flags. Chain is always at least referenced.
1864 * WARNING! The MATCHIND flag does not apply to this function.
1867 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1868 hammer2_key_t *key_nextp,
1869 hammer2_key_t key_beg, hammer2_key_t key_end,
1870 int *cache_indexp, int flags)
1872 hammer2_chain_t *parent;
1877 * Calculate locking flags for upward recursion.
1879 how_maybe = HAMMER2_RESOLVE_MAYBE;
1880 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1881 how_maybe |= HAMMER2_RESOLVE_SHARED;
1886 * Calculate the next index and recalculate the parent if necessary.
1889 key_beg = chain->bref.key +
1890 ((hammer2_key_t)1 << chain->bref.keybits);
1891 if (flags & HAMMER2_LOOKUP_NOLOCK)
1892 hammer2_chain_drop(chain);
1894 hammer2_chain_unlock(chain);
1897 * Any scan where the lookup returned degenerate data embedded
1898 * in the inode has an invalid index and must terminate.
1900 if (chain == parent)
1902 if (key_beg == 0 || key_beg > key_end)
1905 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1906 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1908 * We reached the end of the iteration.
1913 * Continue iteration with next parent unless the current
1914 * parent covers the range.
1916 key_beg = parent->bref.key +
1917 ((hammer2_key_t)1 << parent->bref.keybits);
1918 if (key_beg == 0 || key_beg > key_end)
1920 parent = hammer2_chain_getparent(parentp, how_maybe);
1926 return (hammer2_chain_lookup(parentp, key_nextp,
1928 cache_indexp, flags, &ddflag));
1932 * The raw scan function is similar to lookup/next but does not seek to a key.
1933 * Blockrefs are iterated via first_chain = (parent, NULL) and
1934 * next_chain = (parent, chain).
1936 * The passed-in parent must be locked and its data resolved. The returned
1937 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1938 * under parent and then iterate with the passed-in chain (which this
1939 * function will unlock).
1942 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1943 int *cache_indexp, int flags)
1945 hammer2_mount_t *hmp;
1946 hammer2_blockref_t *base;
1947 hammer2_blockref_t *bref;
1948 hammer2_blockref_t bcopy;
1950 hammer2_key_t next_key;
1952 int how_always = HAMMER2_RESOLVE_ALWAYS;
1953 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1956 int maxloops = 300000;
1961 * Scan flags borrowed from lookup
1963 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1964 how_maybe = how_always;
1965 how = HAMMER2_RESOLVE_ALWAYS;
1966 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1967 how = HAMMER2_RESOLVE_NEVER;
1969 how = HAMMER2_RESOLVE_MAYBE;
1971 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1972 how_maybe |= HAMMER2_RESOLVE_SHARED;
1973 how_always |= HAMMER2_RESOLVE_SHARED;
1974 how |= HAMMER2_RESOLVE_SHARED;
1978 * Calculate key to locate first/next element, unlocking the previous
1979 * element as we go. Be careful, the key calculation can overflow.
1982 key = chain->bref.key +
1983 ((hammer2_key_t)1 << chain->bref.keybits);
1984 hammer2_chain_unlock(chain);
1993 if (--maxloops == 0)
1994 panic("hammer2_chain_scan: maxloops");
1996 * Locate the blockref array. Currently we do a fully associative
1997 * search through the array.
1999 switch(parent->bref.type) {
2000 case HAMMER2_BREF_TYPE_INODE:
2002 * An inode with embedded data has no sub-chains.
2004 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2006 base = &parent->data->ipdata.u.blockset.blockref[0];
2007 count = HAMMER2_SET_COUNT;
2009 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2010 case HAMMER2_BREF_TYPE_INDIRECT:
2012 * Optimize indirect blocks in the INITIAL state to avoid
2015 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2018 if (parent->data == NULL)
2019 panic("parent->data is NULL");
2020 base = &parent->data->npdata[0];
2022 count = parent->bytes / sizeof(hammer2_blockref_t);
2024 case HAMMER2_BREF_TYPE_VOLUME:
2025 base = &hmp->voldata.sroot_blockset.blockref[0];
2026 count = HAMMER2_SET_COUNT;
2028 case HAMMER2_BREF_TYPE_FREEMAP:
2029 base = &hmp->voldata.freemap_blockset.blockref[0];
2030 count = HAMMER2_SET_COUNT;
2033 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2035 base = NULL; /* safety */
2036 count = 0; /* safety */
2040 * Merged scan to find next candidate.
2042 * hammer2_base_*() functions require the parent->core.live_* fields
2043 * to be synchronized.
2045 * We need to hold the spinlock to access the block array and RB tree
2046 * and to interlock chain creation.
2048 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2049 hammer2_chain_countbrefs(parent, base, count);
2052 spin_lock(&parent->core.cst.spin);
2053 chain = hammer2_combined_find(parent, base, count,
2054 cache_indexp, &next_key,
2055 key, HAMMER2_KEY_MAX,
2057 generation = parent->core.generation;
2060 * Exhausted parent chain, we're done.
2063 spin_unlock(&parent->core.cst.spin);
2064 KKASSERT(chain == NULL);
2069 * Selected from blockref or in-memory chain.
2071 if (chain == NULL) {
2073 spin_unlock(&parent->core.cst.spin);
2074 chain = hammer2_chain_get(parent, generation, &bcopy);
2075 if (chain == NULL) {
2076 kprintf("retry scan parent %p keys %016jx\n",
2080 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2081 hammer2_chain_drop(chain);
2086 hammer2_chain_ref(chain);
2087 spin_unlock(&parent->core.cst.spin);
2091 * chain is referenced but not locked. We must lock the chain
2092 * to obtain definitive DUPLICATED/DELETED state
2094 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2097 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2099 * NOTE: chain's key range is not relevant as there might be
2100 * one-offs within the range that are not deleted.
2102 * NOTE: XXX this could create problems with scans used in
2103 * situations other than mount-time recovery.
2105 * NOTE: Lookups can race delete-duplicate because
2106 * delete-duplicate does not lock the parent's core
2107 * (they just use the spinlock on the core). We must
2108 * check for races by comparing the DUPLICATED flag before
2109 * releasing the spinlock with the flag after locking the
2112 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2113 hammer2_chain_unlock(chain);
2124 * All done, return the chain or NULL
2130 * Create and return a new hammer2 system memory structure of the specified
2131 * key, type and size and insert it under (*parentp). This is a full
2132 * insertion, based on the supplied key/keybits, and may involve creating
2133 * indirect blocks and moving other chains around via delete/duplicate.
2135 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2136 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2137 * FULL. This typically means that the caller is creating the chain after
2138 * doing a hammer2_chain_lookup().
2140 * (*parentp) must be exclusive locked and may be replaced on return
2141 * depending on how much work the function had to do.
2143 * (*chainp) usually starts out NULL and returns the newly created chain,
2144 * but if the caller desires the caller may allocate a disconnected chain
2145 * and pass it in instead.
2147 * This function should NOT be used to insert INDIRECT blocks. It is
2148 * typically used to create/insert inodes and data blocks.
2150 * Caller must pass-in an exclusively locked parent the new chain is to
2151 * be inserted under, and optionally pass-in a disconnected, exclusively
2152 * locked chain to insert (else we create a new chain). The function will
2153 * adjust (*parentp) as necessary, create or connect the chain, and
2154 * return an exclusively locked chain in *chainp.
2157 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2158 hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2159 hammer2_key_t key, int keybits, int type, size_t bytes)
2161 hammer2_mount_t *hmp;
2162 hammer2_chain_t *chain;
2163 hammer2_chain_t *parent;
2164 hammer2_blockref_t *base;
2165 hammer2_blockref_t dummy;
2169 int maxloops = 300000;
2172 * Topology may be crossing a PFS boundary.
2175 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2179 if (chain == NULL) {
2181 * First allocate media space and construct the dummy bref,
2182 * then allocate the in-memory chain structure. Set the
2183 * INITIAL flag for fresh chains which do not have embedded
2186 bzero(&dummy, sizeof(dummy));
2189 dummy.keybits = keybits;
2190 dummy.data_off = hammer2_getradix(bytes);
2191 dummy.methods = parent->bref.methods;
2192 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2193 hammer2_chain_core_alloc(trans, chain);
2196 * Lock the chain manually, chain_lock will load the chain
2197 * which we do NOT want to do. (note: chain->refs is set
2198 * to 1 by chain_alloc() for us, but lockcnt is not).
2201 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
2205 * We do NOT set INITIAL here (yet). INITIAL is only
2206 * used for indirect blocks.
2208 * Recalculate bytes to reflect the actual media block
2211 bytes = (hammer2_off_t)1 <<
2212 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2213 chain->bytes = bytes;
2216 case HAMMER2_BREF_TYPE_VOLUME:
2217 case HAMMER2_BREF_TYPE_FREEMAP:
2218 panic("hammer2_chain_create: called with volume type");
2220 case HAMMER2_BREF_TYPE_INDIRECT:
2221 panic("hammer2_chain_create: cannot be used to"
2222 "create indirect block");
2224 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2225 panic("hammer2_chain_create: cannot be used to"
2226 "create freemap root or node");
2228 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2229 KKASSERT(bytes == sizeof(chain->data->bmdata));
2231 case HAMMER2_BREF_TYPE_INODE:
2232 case HAMMER2_BREF_TYPE_DATA:
2235 * leave chain->data NULL, set INITIAL
2237 KKASSERT(chain->data == NULL);
2238 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2243 * We are reattaching a previously deleted chain, possibly
2244 * under a new parent and possibly with a new key/keybits.
2245 * The chain does not have to be in a modified state. The
2246 * UPDATE flag will be set later on in this routine.
2248 * Do NOT mess with the current state of the INITIAL flag.
2250 chain->bref.key = key;
2251 chain->bref.keybits = keybits;
2252 if (chain->flags & HAMMER2_CHAIN_DELETED)
2253 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2254 KKASSERT(chain->parent == NULL);
2258 * Calculate how many entries we have in the blockref array and
2259 * determine if an indirect block is required.
2262 if (--maxloops == 0)
2263 panic("hammer2_chain_create: maxloops");
2265 switch(parent->bref.type) {
2266 case HAMMER2_BREF_TYPE_INODE:
2267 KKASSERT((parent->data->ipdata.op_flags &
2268 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2269 KKASSERT(parent->data != NULL);
2270 base = &parent->data->ipdata.u.blockset.blockref[0];
2271 count = HAMMER2_SET_COUNT;
2273 case HAMMER2_BREF_TYPE_INDIRECT:
2274 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2275 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2278 base = &parent->data->npdata[0];
2279 count = parent->bytes / sizeof(hammer2_blockref_t);
2281 case HAMMER2_BREF_TYPE_VOLUME:
2282 KKASSERT(parent->data != NULL);
2283 base = &hmp->voldata.sroot_blockset.blockref[0];
2284 count = HAMMER2_SET_COUNT;
2286 case HAMMER2_BREF_TYPE_FREEMAP:
2287 KKASSERT(parent->data != NULL);
2288 base = &hmp->voldata.freemap_blockset.blockref[0];
2289 count = HAMMER2_SET_COUNT;
2292 panic("hammer2_chain_create: unrecognized blockref type: %d",
2300 * Make sure we've counted the brefs
2302 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2303 hammer2_chain_countbrefs(parent, base, count);
2305 KKASSERT(parent->core.live_count >= 0 &&
2306 parent->core.live_count <= count);
2309 * If no free blockref could be found we must create an indirect
2310 * block and move a number of blockrefs into it. With the parent
2311 * locked we can safely lock each child in order to delete+duplicate
2312 * it without causing a deadlock.
2314 * This may return the new indirect block or the old parent depending
2315 * on where the key falls. NULL is returned on error.
2317 if (parent->core.live_count == count) {
2318 hammer2_chain_t *nparent;
2320 nparent = hammer2_chain_create_indirect(trans, parent,
2323 if (nparent == NULL) {
2325 hammer2_chain_drop(chain);
2329 if (parent != nparent) {
2330 hammer2_chain_unlock(parent);
2331 parent = *parentp = nparent;
2337 * Link the chain into its parent.
2339 if (chain->parent != NULL)
2340 panic("hammer2: hammer2_chain_create: chain already connected");
2341 KKASSERT(chain->parent == NULL);
2342 hammer2_chain_insert(parent, chain,
2343 HAMMER2_CHAIN_INSERT_SPIN |
2344 HAMMER2_CHAIN_INSERT_LIVE,
2349 * Mark the newly created chain modified. This will cause
2352 * Device buffers are not instantiated for DATA elements
2353 * as these are handled by logical buffers.
2355 * Indirect and freemap node indirect blocks are handled
2356 * by hammer2_chain_create_indirect() and not by this
2359 * Data for all other bref types is expected to be
2360 * instantiated (INODE, LEAF).
2362 switch(chain->bref.type) {
2363 case HAMMER2_BREF_TYPE_DATA:
2364 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2365 case HAMMER2_BREF_TYPE_INODE:
2366 hammer2_chain_modify(trans, chain,
2367 HAMMER2_MODIFY_OPTDATA);
2371 * Remaining types are not supported by this function.
2372 * In particular, INDIRECT and LEAF_NODE types are
2373 * handled by create_indirect().
2375 panic("hammer2_chain_create: bad type: %d",
2382 * When reconnecting a chain we must set UPDATE and
2383 * setflush so the flush recognizes that it must update
2384 * the bref in the parent.
2386 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2387 hammer2_chain_ref(chain);
2388 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2393 * We must setflush(parent) to ensure that it recurses through to
2394 * chain. setflush(chain) might not work because ONFLUSH is possibly
2395 * already set in the chain (so it won't recurse up to set it in the
2398 hammer2_chain_setflush(trans, parent);
2407 * Move the chain from its old parent to a new parent. The chain must have
2408 * already been deleted or already disconnected (or never associated) with
2409 * a parent. The chain is reassociated with the new parent and the deleted
2410 * flag will be cleared (no longer deleted). The chain's modification state
2413 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2414 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2415 * FULL. This typically means that the caller is creating the chain after
2416 * doing a hammer2_chain_lookup().
2418 * A non-NULL bref is typically passed when key and keybits must be overridden.
2419 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2420 * from a passed-in bref and uses the old chain's bref for everything else.
2422 * If (parent) is non-NULL then the new duplicated chain is inserted under
2425 * If (parent) is NULL then the newly duplicated chain is not inserted
2426 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2427 * passing into hammer2_chain_create() after this function returns).
2429 * WARNING! This function calls create which means it can insert indirect
2430 * blocks. This can cause other unrelated chains in the parent to
2431 * be moved to a newly inserted indirect block in addition to the
2435 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2436 hammer2_chain_t **parentp, hammer2_chain_t *chain)
2438 hammer2_mount_t *hmp;
2439 hammer2_chain_t *parent;
2443 * WARNING! We should never resolve DATA to device buffers
2444 * (XXX allow it if the caller did?), and since
2445 * we currently do not have the logical buffer cache
2446 * buffer in-hand to fix its cached physical offset
2447 * we also force the modify code to not COW it. XXX
2450 KKASSERT(chain->parent == NULL);
2453 * Now create a duplicate of the chain structure, associating
2454 * it with the same core, making it the same size, pointing it
2455 * to the same bref (the same media block).
2458 bref = &chain->bref;
2459 bytes = (hammer2_off_t)1 <<
2460 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2463 * If parent is not NULL the duplicated chain will be entered under
2464 * the parent and the UPDATE bit set to tell flush to update
2467 * We must setflush(parent) to ensure that it recurses through to
2468 * chain. setflush(chain) might not work because ONFLUSH is possibly
2469 * already set in the chain (so it won't recurse up to set it in the
2472 * Having both chains locked is extremely important for atomicy.
2474 if (parentp && (parent = *parentp) != NULL) {
2475 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2476 KKASSERT(parent->refs > 0);
2478 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2479 bref->key, bref->keybits, bref->type,
2481 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2482 hammer2_chain_setflush(trans, *parentp);
2487 * Helper function for deleting chains.
2489 * The chain is removed from the live view (the RBTREE) as well as the parent's
2490 * blockmap. Both chain and its parent must be locked.
2493 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2494 hammer2_chain_t *parent, hammer2_chain_t *chain)
2496 hammer2_mount_t *hmp;
2498 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2501 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2503 * Chain is blockmapped, so there must be a parent.
2504 * Atomically remove the chain from the parent and remove
2505 * the blockmap entry.
2507 hammer2_blockref_t *base;
2510 KKASSERT(parent != NULL);
2511 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2512 hammer2_chain_modify(trans, parent,
2513 HAMMER2_MODIFY_OPTDATA);
2516 * Calculate blockmap pointer
2518 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2519 spin_lock(&parent->core.cst.spin);
2521 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2522 atomic_add_int(&parent->core.live_count, -1);
2523 ++parent->core.generation;
2524 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2525 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2526 --parent->core.chain_count;
2527 chain->parent = NULL;
2529 switch(parent->bref.type) {
2530 case HAMMER2_BREF_TYPE_INODE:
2532 * Access the inode's block array. However, there
2533 * is no block array if the inode is flagged
2534 * DIRECTDATA. The DIRECTDATA case typicaly only
2535 * occurs when a hardlink has been shifted up the
2536 * tree and the original inode gets replaced with
2537 * an OBJTYPE_HARDLINK placeholding inode.
2540 (parent->data->ipdata.op_flags &
2541 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2543 &parent->data->ipdata.u.blockset.blockref[0];
2547 count = HAMMER2_SET_COUNT;
2549 case HAMMER2_BREF_TYPE_INDIRECT:
2550 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2552 base = &parent->data->npdata[0];
2555 count = parent->bytes / sizeof(hammer2_blockref_t);
2557 case HAMMER2_BREF_TYPE_VOLUME:
2558 base = &hmp->voldata.sroot_blockset.blockref[0];
2559 count = HAMMER2_SET_COUNT;
2561 case HAMMER2_BREF_TYPE_FREEMAP:
2562 base = &parent->data->npdata[0];
2563 count = HAMMER2_SET_COUNT;
2568 panic("hammer2_flush_pass2: "
2569 "unrecognized blockref type: %d",
2573 int cache_index = -1;
2574 hammer2_base_delete(trans, parent, base, count,
2575 &cache_index, chain);
2577 spin_unlock(&parent->core.cst.spin);
2578 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2580 * Chain is not blockmapped but a parent is present.
2581 * Atomically remove the chain from the parent. There is
2582 * no blockmap entry to remove.
2584 spin_lock(&parent->core.cst.spin);
2585 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2586 atomic_add_int(&parent->core.live_count, -1);
2587 ++parent->core.generation;
2588 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2589 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2590 --parent->core.chain_count;
2591 chain->parent = NULL;
2592 spin_unlock(&parent->core.cst.spin);
2595 * Chain is not blockmapped and has no parent. This
2596 * is a degenerate case.
2598 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2603 * Create an indirect block that covers one or more of the elements in the
2604 * current parent. Either returns the existing parent with no locking or
2605 * ref changes or returns the new indirect block locked and referenced
2606 * and leaving the original parent lock/ref intact as well.
2608 * If an error occurs, NULL is returned and *errorp is set to the error.
2610 * The returned chain depends on where the specified key falls.
2612 * The key/keybits for the indirect mode only needs to follow three rules:
2614 * (1) That all elements underneath it fit within its key space and
2616 * (2) That all elements outside it are outside its key space.
2618 * (3) When creating the new indirect block any elements in the current
2619 * parent that fit within the new indirect block's keyspace must be
2620 * moved into the new indirect block.
2622 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2623 * keyspace the the current parent, but lookup/iteration rules will
2624 * ensure (and must ensure) that rule (2) for all parents leading up
2625 * to the nearest inode or the root volume header is adhered to. This
2626 * is accomplished by always recursing through matching keyspaces in
2627 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2629 * The current implementation calculates the current worst-case keyspace by
2630 * iterating the current parent and then divides it into two halves, choosing
2631 * whichever half has the most elements (not necessarily the half containing
2632 * the requested key).
2634 * We can also opt to use the half with the least number of elements. This
2635 * causes lower-numbered keys (aka logical file offsets) to recurse through
2636 * fewer indirect blocks and higher-numbered keys to recurse through more.
2637 * This also has the risk of not moving enough elements to the new indirect
2638 * block and being forced to create several indirect blocks before the element
2641 * Must be called with an exclusively locked parent.
2643 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2644 hammer2_key_t *keyp, int keybits,
2645 hammer2_blockref_t *base, int count);
2646 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2647 hammer2_key_t *keyp, int keybits,
2648 hammer2_blockref_t *base, int count);
2651 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2652 hammer2_key_t create_key, int create_bits,
2653 int for_type, int *errorp)
2655 hammer2_mount_t *hmp;
2656 hammer2_blockref_t *base;
2657 hammer2_blockref_t *bref;
2658 hammer2_blockref_t bcopy;
2659 hammer2_chain_t *chain;
2660 hammer2_chain_t *ichain;
2661 hammer2_chain_t dummy;
2662 hammer2_key_t key = create_key;
2663 hammer2_key_t key_beg;
2664 hammer2_key_t key_end;
2665 hammer2_key_t key_next;
2666 int keybits = create_bits;
2673 int maxloops = 300000;
2676 * Calculate the base blockref pointer or NULL if the chain
2677 * is known to be empty. We need to calculate the array count
2678 * for RB lookups either way.
2682 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2684 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2685 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2688 switch(parent->bref.type) {
2689 case HAMMER2_BREF_TYPE_INODE:
2690 count = HAMMER2_SET_COUNT;
2692 case HAMMER2_BREF_TYPE_INDIRECT:
2693 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2694 count = parent->bytes / sizeof(hammer2_blockref_t);
2696 case HAMMER2_BREF_TYPE_VOLUME:
2697 count = HAMMER2_SET_COUNT;
2699 case HAMMER2_BREF_TYPE_FREEMAP:
2700 count = HAMMER2_SET_COUNT;
2703 panic("hammer2_chain_create_indirect: "
2704 "unrecognized blockref type: %d",
2710 switch(parent->bref.type) {
2711 case HAMMER2_BREF_TYPE_INODE:
2712 base = &parent->data->ipdata.u.blockset.blockref[0];
2713 count = HAMMER2_SET_COUNT;
2715 case HAMMER2_BREF_TYPE_INDIRECT:
2716 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2717 base = &parent->data->npdata[0];
2718 count = parent->bytes / sizeof(hammer2_blockref_t);
2720 case HAMMER2_BREF_TYPE_VOLUME:
2721 base = &hmp->voldata.sroot_blockset.blockref[0];
2722 count = HAMMER2_SET_COUNT;
2724 case HAMMER2_BREF_TYPE_FREEMAP:
2725 base = &hmp->voldata.freemap_blockset.blockref[0];
2726 count = HAMMER2_SET_COUNT;
2729 panic("hammer2_chain_create_indirect: "
2730 "unrecognized blockref type: %d",
2738 * dummy used in later chain allocation (no longer used for lookups).
2740 bzero(&dummy, sizeof(dummy));
2743 * When creating an indirect block for a freemap node or leaf
2744 * the key/keybits must be fitted to static radix levels because
2745 * particular radix levels use particular reserved blocks in the
2748 * This routine calculates the key/radix of the indirect block
2749 * we need to create, and whether it is on the high-side or the
2752 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2753 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2754 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2757 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2762 * Normalize the key for the radix being represented, keeping the
2763 * high bits and throwing away the low bits.
2765 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2768 * How big should our new indirect block be? It has to be at least
2769 * as large as its parent.
2771 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2772 nbytes = HAMMER2_IND_BYTES_MIN;
2774 nbytes = HAMMER2_IND_BYTES_MAX;
2775 if (nbytes < count * sizeof(hammer2_blockref_t))
2776 nbytes = count * sizeof(hammer2_blockref_t);
2779 * Ok, create our new indirect block
2781 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2782 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2783 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2785 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2787 dummy.bref.key = key;
2788 dummy.bref.keybits = keybits;
2789 dummy.bref.data_off = hammer2_getradix(nbytes);
2790 dummy.bref.methods = parent->bref.methods;
2792 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2793 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2794 hammer2_chain_core_alloc(trans, ichain);
2795 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2796 hammer2_chain_drop(ichain); /* excess ref from alloc */
2799 * We have to mark it modified to allocate its block, but use
2800 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2801 * it won't be acted upon by the flush code.
2803 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2806 * Iterate the original parent and move the matching brefs into
2807 * the new indirect block.
2809 * XXX handle flushes.
2812 key_end = HAMMER2_KEY_MAX;
2814 spin_lock(&parent->core.cst.spin);
2819 if (++loops > 100000) {
2820 spin_unlock(&parent->core.cst.spin);
2821 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2822 reason, parent, base, count, key_next);
2826 * NOTE: spinlock stays intact, returned chain (if not NULL)
2827 * is not referenced or locked which means that we
2828 * cannot safely check its flagged / deletion status
2831 chain = hammer2_combined_find(parent, base, count,
2832 &cache_index, &key_next,
2835 generation = parent->core.generation;
2838 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2841 * Skip keys that are not within the key/radix of the new
2842 * indirect block. They stay in the parent.
2844 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2845 (key ^ bref->key)) != 0) {
2846 goto next_key_spinlocked;
2850 * Load the new indirect block by acquiring the related
2851 * chains (potentially from media as it might not be
2852 * in-memory). Then move it to the new parent (ichain)
2853 * via DELETE-DUPLICATE.
2855 * chain is referenced but not locked. We must lock the
2856 * chain to obtain definitive DUPLICATED/DELETED state
2860 * Use chain already present in the RBTREE
2862 hammer2_chain_ref(chain);
2863 spin_unlock(&parent->core.cst.spin);
2864 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2865 HAMMER2_RESOLVE_NOREF);
2868 * Get chain for blockref element. _get returns NULL
2869 * on insertion race.
2872 spin_unlock(&parent->core.cst.spin);
2873 chain = hammer2_chain_get(parent, generation, &bcopy);
2874 if (chain == NULL) {
2876 spin_lock(&parent->core.cst.spin);
2879 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2880 kprintf("REASON 2\n");
2882 hammer2_chain_drop(chain);
2883 spin_lock(&parent->core.cst.spin);
2886 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2887 HAMMER2_RESOLVE_NOREF);
2891 * This is always live so if the chain has been deleted
2892 * we raced someone and we have to retry.
2894 * NOTE: Lookups can race delete-duplicate because
2895 * delete-duplicate does not lock the parent's core
2896 * (they just use the spinlock on the core). We must
2897 * check for races by comparing the DUPLICATED flag before
2898 * releasing the spinlock with the flag after locking the
2901 * (note reversed logic for this one)
2903 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2904 hammer2_chain_unlock(chain);
2909 * Shift the chain to the indirect block.
2911 * WARNING! Can cause held-over chains to require a refactor.
2912 * Fortunately we have none (our locked chains are
2913 * passed into and modified by the call).
2915 hammer2_chain_delete(trans, parent, chain, 0);
2916 hammer2_chain_rename(trans, NULL, &ichain, chain);
2917 hammer2_chain_unlock(chain);
2918 KKASSERT(parent->refs > 0);
2921 spin_lock(&parent->core.cst.spin);
2922 next_key_spinlocked:
2923 if (--maxloops == 0)
2924 panic("hammer2_chain_create_indirect: maxloops");
2926 if (key_next == 0 || key_next > key_end)
2931 spin_unlock(&parent->core.cst.spin);
2934 * Insert the new indirect block into the parent now that we've
2935 * cleared out some entries in the parent. We calculated a good
2936 * insertion index in the loop above (ichain->index).
2938 * We don't have to set UPDATE here because we mark ichain
2939 * modified down below (so the normal modified -> flush -> set-moved
2940 * sequence applies).
2942 * The insertion shouldn't race as this is a completely new block
2943 * and the parent is locked.
2945 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2946 hammer2_chain_insert(parent, ichain,
2947 HAMMER2_CHAIN_INSERT_SPIN |
2948 HAMMER2_CHAIN_INSERT_LIVE,
2952 * Make sure flushes propogate after our manual insertion.
2954 hammer2_chain_setflush(trans, ichain);
2955 hammer2_chain_setflush(trans, parent);
2958 * Figure out what to return.
2960 if (~(((hammer2_key_t)1 << keybits) - 1) &
2961 (create_key ^ key)) {
2963 * Key being created is outside the key range,
2964 * return the original parent.
2966 hammer2_chain_unlock(ichain);
2969 * Otherwise its in the range, return the new parent.
2970 * (leave both the new and old parent locked).
2979 * Calculate the keybits and highside/lowside of the freemap node the
2980 * caller is creating.
2982 * This routine will specify the next higher-level freemap key/radix
2983 * representing the lowest-ordered set. By doing so, eventually all
2984 * low-ordered sets will be moved one level down.
2986 * We have to be careful here because the freemap reserves a limited
2987 * number of blocks for a limited number of levels. So we can't just
2988 * push indiscriminately.
2991 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2992 int keybits, hammer2_blockref_t *base, int count)
2994 hammer2_chain_t *chain;
2995 hammer2_blockref_t *bref;
2997 hammer2_key_t key_beg;
2998 hammer2_key_t key_end;
2999 hammer2_key_t key_next;
3003 int maxloops = 300000;
3011 * Calculate the range of keys in the array being careful to skip
3012 * slots which are overridden with a deletion.
3015 key_end = HAMMER2_KEY_MAX;
3017 spin_lock(&parent->core.cst.spin);
3020 if (--maxloops == 0) {
3021 panic("indkey_freemap shit %p %p:%d\n",
3022 parent, base, count);
3024 chain = hammer2_combined_find(parent, base, count,
3025 &cache_index, &key_next,
3036 * Skip deleted chains.
3038 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3039 if (key_next == 0 || key_next > key_end)
3046 * Use the full live (not deleted) element for the scan
3047 * iteration. HAMMER2 does not allow partial replacements.
3049 * XXX should be built into hammer2_combined_find().
3051 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3053 if (keybits > bref->keybits) {
3055 keybits = bref->keybits;
3056 } else if (keybits == bref->keybits && bref->key < key) {
3063 spin_unlock(&parent->core.cst.spin);
3066 * Return the keybits for a higher-level FREEMAP_NODE covering
3070 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3071 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3073 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3074 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3076 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3077 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3079 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3080 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3082 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3083 panic("hammer2_chain_indkey_freemap: level too high");
3086 panic("hammer2_chain_indkey_freemap: bad radix");
3095 * Calculate the keybits and highside/lowside of the indirect block the
3096 * caller is creating.
3099 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3100 int keybits, hammer2_blockref_t *base, int count)
3102 hammer2_blockref_t *bref;
3103 hammer2_chain_t *chain;
3104 hammer2_key_t key_beg;
3105 hammer2_key_t key_end;
3106 hammer2_key_t key_next;
3112 int maxloops = 300000;
3119 * Calculate the range of keys in the array being careful to skip
3120 * slots which are overridden with a deletion. Once the scan
3121 * completes we will cut the key range in half and shift half the
3122 * range into the new indirect block.
3125 key_end = HAMMER2_KEY_MAX;
3127 spin_lock(&parent->core.cst.spin);
3130 if (--maxloops == 0) {
3131 panic("indkey_freemap shit %p %p:%d\n",
3132 parent, base, count);
3134 chain = hammer2_combined_find(parent, base, count,
3135 &cache_index, &key_next,
3146 * NOTE: No need to check DUPLICATED here because we do
3147 * not release the spinlock.
3149 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3150 if (key_next == 0 || key_next > key_end)
3157 * Use the full live (not deleted) element for the scan
3158 * iteration. HAMMER2 does not allow partial replacements.
3160 * XXX should be built into hammer2_combined_find().
3162 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3165 * Expand our calculated key range (key, keybits) to fit
3166 * the scanned key. nkeybits represents the full range
3167 * that we will later cut in half (two halves @ nkeybits - 1).
3170 if (nkeybits < bref->keybits) {
3171 if (bref->keybits > 64) {
3172 kprintf("bad bref chain %p bref %p\n",
3176 nkeybits = bref->keybits;
3178 while (nkeybits < 64 &&
3179 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3180 (key ^ bref->key)) != 0) {
3185 * If the new key range is larger we have to determine
3186 * which side of the new key range the existing keys fall
3187 * under by checking the high bit, then collapsing the
3188 * locount into the hicount or vise-versa.
3190 if (keybits != nkeybits) {
3191 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3202 * The newly scanned key will be in the lower half or the
3203 * upper half of the (new) key range.
3205 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3214 spin_unlock(&parent->core.cst.spin);
3215 bref = NULL; /* now invalid (safety) */
3218 * Adjust keybits to represent half of the full range calculated
3219 * above (radix 63 max)
3224 * Select whichever half contains the most elements. Theoretically
3225 * we can select either side as long as it contains at least one
3226 * element (in order to ensure that a free slot is present to hold
3227 * the indirect block).
3229 if (hammer2_indirect_optimize) {
3231 * Insert node for least number of keys, this will arrange
3232 * the first few blocks of a large file or the first few
3233 * inodes in a directory with fewer indirect blocks when
3236 if (hicount < locount && hicount != 0)
3237 key |= (hammer2_key_t)1 << keybits;
3239 key &= ~(hammer2_key_t)1 << keybits;
3242 * Insert node for most number of keys, best for heavily
3245 if (hicount > locount)
3246 key |= (hammer2_key_t)1 << keybits;
3248 key &= ~(hammer2_key_t)1 << keybits;
3256 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3259 * Both parent and chain must be locked exclusively.
3261 * This function will modify the parent if the blockref requires removal
3262 * from the parent's block table.
3264 * This function is NOT recursive. Any entity already pushed into the
3265 * chain (such as an inode) may still need visibility into its contents,
3266 * as well as the ability to read and modify the contents. For example,
3267 * for an unlinked file which is still open.
3270 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3271 hammer2_chain_t *chain, int flags)
3273 KKASSERT(ccms_thread_lock_owned(&chain->core.cst));
3276 * Nothing to do if already marked.
3278 * We need the spinlock on the core whos RBTREE contains chain
3279 * to protect against races.
3281 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3282 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3283 chain->parent == parent);
3284 _hammer2_chain_delete_helper(trans, parent, chain);
3287 if (flags & HAMMER2_DELETE_PERMANENT) {
3288 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3289 hammer2_flush(trans, chain);
3291 /* XXX might not be needed */
3292 hammer2_chain_setflush(trans, chain);
3297 * Returns the index of the nearest element in the blockref array >= elm.
3298 * Returns (count) if no element could be found.
3300 * Sets *key_nextp to the next key for loop purposes but does not modify
3301 * it if the next key would be higher than the current value of *key_nextp.
3302 * Note that *key_nexp can overflow to 0, which should be tested by the
3305 * (*cache_indexp) is a heuristic and can be any value without effecting
3308 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3309 * held through the operation.
3312 hammer2_base_find(hammer2_chain_t *parent,
3313 hammer2_blockref_t *base, int count,
3314 int *cache_indexp, hammer2_key_t *key_nextp,
3315 hammer2_key_t key_beg, hammer2_key_t key_end)
3317 hammer2_blockref_t *scan;
3318 hammer2_key_t scan_end;
3323 * Require the live chain's already have their core's counted
3324 * so we can optimize operations.
3326 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3331 if (count == 0 || base == NULL)
3335 * Sequential optimization using *cache_indexp. This is the most
3338 * We can avoid trailing empty entries on live chains, otherwise
3339 * we might have to check the whole block array.
3343 limit = parent->core.live_zero;
3348 KKASSERT(i < count);
3354 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3361 * Search forwards, stop when we find a scan element which
3362 * encloses the key or until we know that there are no further
3366 if (scan->type != 0) {
3367 scan_end = scan->key +
3368 ((hammer2_key_t)1 << scan->keybits) - 1;
3369 if (scan->key > key_beg || scan_end >= key_beg)
3382 scan_end = scan->key +
3383 ((hammer2_key_t)1 << scan->keybits);
3384 if (scan_end && (*key_nextp > scan_end ||
3386 *key_nextp = scan_end;
3394 * Do a combined search and return the next match either from the blockref
3395 * array or from the in-memory chain. Sets *bresp to the returned bref in
3396 * both cases, or sets it to NULL if the search exhausted. Only returns
3397 * a non-NULL chain if the search matched from the in-memory chain.
3399 * When no in-memory chain has been found and a non-NULL bref is returned
3403 * The returned chain is not locked or referenced. Use the returned bref
3404 * to determine if the search exhausted or not. Iterate if the base find
3405 * is chosen but matches a deleted chain.
3407 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3408 * held through the operation.
3410 static hammer2_chain_t *
3411 hammer2_combined_find(hammer2_chain_t *parent,
3412 hammer2_blockref_t *base, int count,
3413 int *cache_indexp, hammer2_key_t *key_nextp,
3414 hammer2_key_t key_beg, hammer2_key_t key_end,
3415 hammer2_blockref_t **bresp)
3417 hammer2_blockref_t *bref;
3418 hammer2_chain_t *chain;
3422 * Lookup in block array and in rbtree.
3424 *key_nextp = key_end + 1;
3425 i = hammer2_base_find(parent, base, count, cache_indexp,
3426 key_nextp, key_beg, key_end);
3427 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3432 if (i == count && chain == NULL) {
3438 * Only chain matched.
3441 bref = &chain->bref;
3446 * Only blockref matched.
3448 if (chain == NULL) {
3454 * Both in-memory and blockref matched, select the nearer element.
3456 * If both are flush with the left-hand side or both are the
3457 * same distance away, select the chain. In this situation the
3458 * chain must have been loaded from the matching blockmap.
3460 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3461 chain->bref.key == base[i].key) {
3462 KKASSERT(chain->bref.key == base[i].key);
3463 bref = &chain->bref;
3468 * Select the nearer key
3470 if (chain->bref.key < base[i].key) {
3471 bref = &chain->bref;
3478 * If the bref is out of bounds we've exhausted our search.
3481 if (bref->key > key_end) {
3491 * Locate the specified block array element and delete it. The element
3494 * The spin lock on the related chain must be held.
3496 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3497 * need to be adjusted when we commit the media change.
3500 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3501 hammer2_blockref_t *base, int count,
3502 int *cache_indexp, hammer2_chain_t *chain)
3504 hammer2_blockref_t *elm = &chain->bref;
3505 hammer2_key_t key_next;
3509 * Delete element. Expect the element to exist.
3511 * XXX see caller, flush code not yet sophisticated enough to prevent
3512 * re-flushed in some cases.
3514 key_next = 0; /* max range */
3515 i = hammer2_base_find(parent, base, count, cache_indexp,
3516 &key_next, elm->key, elm->key);
3517 if (i == count || base[i].type == 0 ||
3518 base[i].key != elm->key ||
3519 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3520 base[i].keybits != elm->keybits)) {
3521 spin_unlock(&parent->core.cst.spin);
3522 panic("delete base %p element not found at %d/%d elm %p\n",
3523 base, i, count, elm);
3526 bzero(&base[i], sizeof(*base));
3529 * We can only optimize parent->core.live_zero for live chains.
3531 if (parent->core.live_zero == i + 1) {
3532 while (--i >= 0 && base[i].type == 0)
3534 parent->core.live_zero = i + 1;
3538 * Clear appropriate blockmap flags in chain.
3540 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3541 HAMMER2_CHAIN_BMAPUPD);
3545 * Insert the specified element. The block array must not already have the
3546 * element and must have space available for the insertion.
3548 * The spin lock on the related chain must be held.
3550 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3551 * need to be adjusted when we commit the media change.
3554 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3555 hammer2_blockref_t *base, int count,
3556 int *cache_indexp, hammer2_chain_t *chain)
3558 hammer2_blockref_t *elm = &chain->bref;
3559 hammer2_key_t key_next;
3568 * Insert new element. Expect the element to not already exist
3569 * unless we are replacing it.
3571 * XXX see caller, flush code not yet sophisticated enough to prevent
3572 * re-flushed in some cases.
3574 key_next = 0; /* max range */
3575 i = hammer2_base_find(parent, base, count, cache_indexp,
3576 &key_next, elm->key, elm->key);
3579 * Shortcut fill optimization, typical ordered insertion(s) may not
3582 KKASSERT(i >= 0 && i <= count);
3585 * Set appropriate blockmap flags in chain.
3587 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3590 * We can only optimize parent->core.live_zero for live chains.
3592 if (i == count && parent->core.live_zero < count) {
3593 i = parent->core.live_zero++;
3598 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3599 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3600 spin_unlock(&parent->core.cst.spin);
3601 panic("insert base %p overlapping elements at %d elm %p\n",
3606 * Try to find an empty slot before or after.
3610 while (j > 0 || k < count) {
3612 if (j >= 0 && base[j].type == 0) {
3616 bcopy(&base[j+1], &base[j],
3617 (i - j - 1) * sizeof(*base));
3623 if (k < count && base[k].type == 0) {
3624 bcopy(&base[i], &base[i+1],
3625 (k - i) * sizeof(hammer2_blockref_t));
3629 * We can only update parent->core.live_zero for live
3632 if (parent->core.live_zero <= k)
3633 parent->core.live_zero = k + 1;
3638 panic("hammer2_base_insert: no room!");
3645 for (l = 0; l < count; ++l) {
3647 key_next = base[l].key +
3648 ((hammer2_key_t)1 << base[l].keybits) - 1;
3652 while (++l < count) {
3654 if (base[l].key <= key_next)
3655 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3656 key_next = base[l].key +
3657 ((hammer2_key_t)1 << base[l].keybits) - 1;
3667 * Sort the blockref array for the chain. Used by the flush code to
3668 * sort the blockref[] array.
3670 * The chain must be exclusively locked AND spin-locked.
3672 typedef hammer2_blockref_t *hammer2_blockref_p;
3676 hammer2_base_sort_callback(const void *v1, const void *v2)
3678 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3679 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3682 * Make sure empty elements are placed at the end of the array
3684 if (bref1->type == 0) {
3685 if (bref2->type == 0)
3688 } else if (bref2->type == 0) {
3695 if (bref1->key < bref2->key)
3697 if (bref1->key > bref2->key)
3703 hammer2_base_sort(hammer2_chain_t *chain)
3705 hammer2_blockref_t *base;
3708 switch(chain->bref.type) {
3709 case HAMMER2_BREF_TYPE_INODE:
3711 * Special shortcut for embedded data returns the inode
3712 * itself. Callers must detect this condition and access
3713 * the embedded data (the strategy code does this for us).
3715 * This is only applicable to regular files and softlinks.
3717 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3719 base = &chain->data->ipdata.u.blockset.blockref[0];
3720 count = HAMMER2_SET_COUNT;
3722 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3723 case HAMMER2_BREF_TYPE_INDIRECT:
3725 * Optimize indirect blocks in the INITIAL state to avoid
3728 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3729 base = &chain->data->npdata[0];
3730 count = chain->bytes / sizeof(hammer2_blockref_t);
3732 case HAMMER2_BREF_TYPE_VOLUME:
3733 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3734 count = HAMMER2_SET_COUNT;
3736 case HAMMER2_BREF_TYPE_FREEMAP:
3737 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3738 count = HAMMER2_SET_COUNT;
3741 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3743 base = NULL; /* safety */
3744 count = 0; /* safety */
3746 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3752 * Chain memory management
3755 hammer2_chain_wait(hammer2_chain_t *chain)
3757 tsleep(chain, 0, "chnflw", 1);