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>
63 #include <crypto/sha2/sha2.h>
67 static int hammer2_indirect_optimize; /* XXX SYSCTL */
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70 hammer2_trans_t *trans, hammer2_chain_t *parent,
71 hammer2_key_t key, int keybits, int for_type, int *errorp);
72 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
73 static hammer2_chain_t *hammer2_combined_find(
74 hammer2_chain_t *parent,
75 hammer2_blockref_t *base, int count,
76 int *cache_indexp, hammer2_key_t *key_nextp,
77 hammer2_key_t key_beg, hammer2_key_t key_end,
78 hammer2_blockref_t **bresp);
81 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
82 * overlap in the RB trees. Deleted chains are moved from rbtree to either
85 * Chains in delete-duplicate sequences can always iterate through core_entry
86 * to locate the live version of the chain.
88 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
91 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
99 * Compare chains. Overlaps are not supposed to happen and catch
100 * any software issues early we count overlaps as a match.
102 c1_beg = chain1->bref.key;
103 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
104 c2_beg = chain2->bref.key;
105 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
107 if (c1_end < c2_beg) /* fully to the left */
109 if (c1_beg > c2_end) /* fully to the right */
111 return(0); /* overlap (must not cross edge boundary) */
116 hammer2_isclusterable(hammer2_chain_t *chain)
118 if (hammer2_cluster_enable) {
119 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
120 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
121 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
129 * Make a chain visible to the flusher. The flusher needs to be able to
130 * do flushes of a subdirectory chains or single files so it does a top-down
131 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
132 * or UPDATE chains and flushes back up the chain to the root.
135 hammer2_chain_setflush(hammer2_trans_t *trans, hammer2_chain_t *chain)
137 hammer2_chain_t *parent;
139 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
140 spin_lock(&chain->core.cst.spin);
141 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
142 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
143 if ((parent = chain->parent) == NULL)
145 spin_lock(&parent->core.cst.spin);
146 spin_unlock(&chain->core.cst.spin);
149 spin_unlock(&chain->core.cst.spin);
154 * Allocate a new disconnected chain element representing the specified
155 * bref. chain->refs is set to 1 and the passed bref is copied to
156 * chain->bref. chain->bytes is derived from the bref.
158 * chain->core is NOT allocated and the media data and bp pointers are left
159 * NULL. The caller must call chain_core_alloc() to allocate or associate
160 * a core with the chain.
162 * chain->pmp inherits pmp unless the chain is an inode (other than the
165 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
168 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
169 hammer2_trans_t *trans, hammer2_blockref_t *bref)
171 hammer2_chain_t *chain;
172 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
175 * Construct the appropriate system structure.
178 case HAMMER2_BREF_TYPE_INODE:
179 case HAMMER2_BREF_TYPE_INDIRECT:
180 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
181 case HAMMER2_BREF_TYPE_DATA:
182 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
184 * Chain's are really only associated with the hmp but we
185 * maintain a pmp association for per-mount memory tracking
186 * purposes. The pmp can be NULL.
188 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
190 case HAMMER2_BREF_TYPE_VOLUME:
191 case HAMMER2_BREF_TYPE_FREEMAP:
193 panic("hammer2_chain_alloc volume type illegal for op");
196 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
201 * Initialize the new chain structure.
206 chain->bytes = bytes;
208 chain->flags = HAMMER2_CHAIN_ALLOCATED;
211 * Set the PFS boundary flag if this chain represents a PFS root.
213 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
214 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
220 * Associate an existing core with the chain or allocate a new core.
222 * The core is not locked. No additional refs on the chain are made.
223 * (trans) must not be NULL if (core) is not NULL.
225 * When chains are delete-duplicated during flushes we insert nchain on
226 * the ownerq after ochain instead of at the end in order to give the
227 * drop code visibility in the correct order, otherwise drops can be missed.
230 hammer2_chain_core_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain)
232 hammer2_chain_core_t *core = &chain->core;
235 * Fresh core under nchain (no multi-homing of ochain's
238 RB_INIT(&core->rbtree); /* live chains */
239 ccms_cst_init(&core->cst, chain);
243 * Add a reference to a chain element, preventing its destruction.
245 * (can be called with spinlock held)
248 hammer2_chain_ref(hammer2_chain_t *chain)
250 atomic_add_int(&chain->refs, 1);
254 * Insert the chain in the core rbtree.
256 * Normal insertions are placed in the live rbtree. Insertion of a deleted
257 * chain is a special case used by the flush code that is placed on the
258 * unstaged deleted list to avoid confusing the live view.
260 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
261 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
262 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
266 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
267 int flags, int generation)
269 hammer2_chain_t *xchain;
272 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
273 spin_lock(&parent->core.cst.spin);
276 * Interlocked by spinlock, check for race
278 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
279 parent->core.generation != generation) {
287 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
288 KASSERT(xchain == NULL,
289 ("hammer2_chain_insert: collision %p %p", chain, xchain));
290 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
291 chain->parent = parent;
292 ++parent->core.chain_count;
293 ++parent->core.generation; /* XXX incs for _get() too, XXX */
296 * We have to keep track of the effective live-view blockref count
297 * so the create code knows when to push an indirect block.
299 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
300 atomic_add_int(&parent->core.live_count, 1);
302 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
303 spin_unlock(&parent->core.cst.spin);
308 * Drop the caller's reference to the chain. When the ref count drops to
309 * zero this function will try to disassociate the chain from its parent and
310 * deallocate it, then recursely drop the parent using the implied ref
311 * from the chain's chain->parent.
313 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
316 hammer2_chain_drop(hammer2_chain_t *chain)
321 if (hammer2_debug & 0x200000)
324 if (chain->flags & HAMMER2_CHAIN_UPDATE)
326 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
328 KKASSERT(chain->refs > need);
336 chain = hammer2_chain_lastdrop(chain);
338 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
340 /* retry the same chain */
346 * Safe handling of the 1->0 transition on chain. Returns a chain for
347 * recursive drop or NULL, possibly returning the same chain if the atomic
350 * Whem two chains need to be recursively dropped we use the chain
351 * we would otherwise free to placehold the additional chain. It's a bit
352 * convoluted but we can't just recurse without potentially blowing out
355 * The chain cannot be freed if it has a non-empty core (children) or
356 * it is not at the head of ownerq.
358 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
362 hammer2_chain_lastdrop(hammer2_chain_t *chain)
364 hammer2_pfsmount_t *pmp;
365 hammer2_mount_t *hmp;
366 hammer2_chain_t *parent;
367 hammer2_chain_t *rdrop;
370 * Spinlock the core and check to see if it is empty. If it is
371 * not empty we leave chain intact with refs == 0. The elements
372 * in core->rbtree are associated with other chains contemporary
373 * with ours but not with our chain directly.
375 spin_lock(&chain->core.cst.spin);
378 * We can't free non-stale chains with children until we are
379 * able to free the children because there might be a flush
380 * dependency. Flushes of stale children (which should also
381 * have their deleted flag set) short-cut recursive flush
382 * dependencies and can be freed here. Any flushes which run
383 * through stale children due to the flush synchronization
384 * point should have a FLUSH_* bit set in the chain and not
385 * reach lastdrop at this time.
387 * NOTE: We return (chain) on failure to retry.
389 if (chain->core.chain_count) {
390 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
391 spin_unlock(&chain->core.cst.spin);
392 chain = NULL; /* success */
394 spin_unlock(&chain->core.cst.spin);
398 /* no chains left under us */
401 * chain->core has no children left so no accessors can get to our
402 * chain from there. Now we have to lock the parent core to interlock
403 * remaining possible accessors that might bump chain's refs before
404 * we can safely drop chain's refs with intent to free the chain.
407 pmp = chain->pmp; /* can be NULL */
411 * Spinlock the parent and try to drop the last ref on chain.
412 * On success remove chain from its parent, otherwise return NULL.
414 * (normal core locks are top-down recursive but we define core
415 * spinlocks as bottom-up recursive, so this is safe).
417 if ((parent = chain->parent) != NULL) {
418 spin_lock(&parent->core.cst.spin);
419 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
420 /* 1->0 transition failed */
421 spin_unlock(&parent->core.cst.spin);
422 spin_unlock(&chain->core.cst.spin);
423 return(chain); /* retry */
427 * 1->0 transition successful, remove chain from its
430 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
431 RB_REMOVE(hammer2_chain_tree,
432 &parent->core.rbtree, chain);
433 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
434 --parent->core.chain_count;
435 chain->parent = NULL;
439 * If our chain was the last chain in the parent's core the
440 * core is now empty and its parent might have to be
441 * re-dropped if it has 0 refs.
443 if (parent->core.chain_count == 0) {
445 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
449 spin_unlock(&parent->core.cst.spin);
450 parent = NULL; /* safety */
454 * Successful 1->0 transition and the chain can be destroyed now.
456 * We still have the core spinlock, and core's chain_count is 0.
457 * Any parent spinlock is gone.
459 spin_unlock(&chain->core.cst.spin);
460 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
461 chain->core.chain_count == 0);
462 KKASSERT(chain->core.cst.count == 0);
463 KKASSERT(chain->core.cst.upgrade == 0);
466 * All spin locks are gone, finish freeing stuff.
468 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
469 HAMMER2_CHAIN_MODIFIED)) == 0);
470 hammer2_chain_drop_data(chain, 1);
472 KKASSERT(chain->dio == NULL);
475 * Once chain resources are gone we can use the now dead chain
476 * structure to placehold what might otherwise require a recursive
477 * drop, because we have potentially two things to drop and can only
478 * return one directly.
480 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
481 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
483 kfree(chain, hmp->mchain);
487 * Possible chaining loop when parent re-drop needed.
493 * On either last lock release or last drop
496 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
498 /*hammer2_mount_t *hmp = chain->hmp;*/
500 switch(chain->bref.type) {
501 case HAMMER2_BREF_TYPE_VOLUME:
502 case HAMMER2_BREF_TYPE_FREEMAP:
507 KKASSERT(chain->data == NULL);
513 * Ref and lock a chain element, acquiring its data with I/O if necessary,
514 * and specify how you would like the data to be resolved.
516 * Returns 0 on success or an error code if the data could not be acquired.
517 * The chain element is locked on return regardless of whether an error
520 * The lock is allowed to recurse, multiple locking ops will aggregate
521 * the requested resolve types. Once data is assigned it will not be
522 * removed until the last unlock.
524 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
525 * (typically used to avoid device/logical buffer
528 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
529 * the INITIAL-create state (indirect blocks only).
531 * Do not resolve data elements for DATA chains.
532 * (typically used to avoid device/logical buffer
535 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
537 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
538 * it will be locked exclusive.
540 * NOTE: Embedded elements (volume header, inodes) are always resolved
543 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
544 * element will instantiate and zero its buffer, and flush it on
547 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
548 * so as not to instantiate a device buffer, which could alias against
549 * a logical file buffer. However, if ALWAYS is specified the
550 * device buffer will be instantiated anyway.
552 * WARNING! If data must be fetched a shared lock will temporarily be
553 * upgraded to exclusive. However, a deadlock can occur if
554 * the caller owns more than one shared lock.
557 hammer2_chain_lock(hammer2_chain_t *chain, int how)
559 hammer2_mount_t *hmp;
560 hammer2_blockref_t *bref;
566 * Ref and lock the element. Recursive locks are allowed.
568 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
569 hammer2_chain_ref(chain);
570 atomic_add_int(&chain->lockcnt, 1);
573 KKASSERT(hmp != NULL);
576 * Get the appropriate lock.
578 if (how & HAMMER2_RESOLVE_SHARED)
579 ccms_thread_lock(&chain->core.cst, CCMS_STATE_SHARED);
581 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
584 * If we already have a valid data pointer no further action is
591 * Do we have to resolve the data?
593 switch(how & HAMMER2_RESOLVE_MASK) {
594 case HAMMER2_RESOLVE_NEVER:
596 case HAMMER2_RESOLVE_MAYBE:
597 if (chain->flags & HAMMER2_CHAIN_INITIAL)
599 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
602 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
604 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
608 case HAMMER2_RESOLVE_ALWAYS:
613 * Upgrade to an exclusive lock so we can safely manipulate the
614 * buffer cache. If another thread got to it before us we
617 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
619 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
624 * We must resolve to a device buffer, either by issuing I/O or
625 * by creating a zero-fill element. We do not mark the buffer
626 * dirty when creating a zero-fill element (the hammer2_chain_modify()
627 * API must still be used to do that).
629 * The device buffer is variable-sized in powers of 2 down
630 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
631 * chunk always contains buffers of the same size. (XXX)
633 * The minimum physical IO size may be larger than the variable
639 * The getblk() optimization can only be used on newly created
640 * elements if the physical block size matches the request.
642 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
643 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
646 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
648 hammer2_adjreadcounter(&chain->bref, chain->bytes);
652 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
653 (intmax_t)bref->data_off, error);
654 hammer2_io_bqrelse(&chain->dio);
655 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
661 * No need for this, always require that hammer2_chain_modify()
662 * be called before any modifying operations, which ensures that
663 * the underlying dio is dirty.
665 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
666 !hammer2_io_isdirty(chain->dio)) {
667 hammer2_io_setdirty(chain->dio);
672 * Clear INITIAL. In this case we used io_new() and the buffer has
673 * been zero'd and marked dirty.
675 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
676 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
677 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
678 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
679 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
681 * check data not currently synchronized due to
682 * modification. XXX assumes data stays in the buffer
683 * cache, which might not be true (need biodep on flush
684 * to calculate crc? or simple crc?).
687 if (hammer2_chain_testcheck(chain, bdata) == 0) {
688 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL %08x (flags=%08x)\n",
690 chain->bref.data_off,
693 hammer2_icrc32(bdata, chain->bytes),
699 * Setup the data pointer, either pointing it to an embedded data
700 * structure and copying the data from the buffer, or pointing it
703 * The buffer is not retained when copying to an embedded data
704 * structure in order to avoid potential deadlocks or recursions
705 * on the same physical buffer.
707 switch (bref->type) {
708 case HAMMER2_BREF_TYPE_VOLUME:
709 case HAMMER2_BREF_TYPE_FREEMAP:
711 * Copy data from bp to embedded buffer
713 panic("hammer2_chain_lock: called on unresolved volume header");
715 case HAMMER2_BREF_TYPE_INODE:
716 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
717 case HAMMER2_BREF_TYPE_INDIRECT:
718 case HAMMER2_BREF_TYPE_DATA:
719 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
722 * Point data at the device buffer and leave dio intact.
724 chain->data = (void *)bdata;
727 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
732 * Unlock and deref a chain element.
734 * On the last lock release any non-embedded data (chain->dio) will be
738 hammer2_chain_unlock(hammer2_chain_t *chain)
745 * The core->cst lock can be shared across several chains so we
746 * need to track the per-chain lockcnt separately.
748 * If multiple locks are present (or being attempted) on this
749 * particular chain we can just unlock, drop refs, and return.
751 * Otherwise fall-through on the 1->0 transition.
754 lockcnt = chain->lockcnt;
755 KKASSERT(lockcnt > 0);
758 if (atomic_cmpset_int(&chain->lockcnt,
759 lockcnt, lockcnt - 1)) {
760 ccms_thread_unlock(&chain->core.cst);
761 hammer2_chain_drop(chain);
765 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
772 * On the 1->0 transition we upgrade the core lock (if necessary)
773 * to exclusive for terminal processing. If after upgrading we find
774 * that lockcnt is non-zero, another thread is racing us and will
775 * handle the unload for us later on, so just cleanup and return
776 * leaving the data/io intact
778 * Otherwise if lockcnt is still 0 it is possible for it to become
779 * non-zero and race, but since we hold the core->cst lock
780 * exclusively all that will happen is that the chain will be
781 * reloaded after we unload it.
783 ostate = ccms_thread_lock_upgrade(&chain->core.cst);
784 if (chain->lockcnt) {
785 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
786 hammer2_chain_drop(chain);
791 * Shortcut the case if the data is embedded or not resolved.
793 * Do NOT NULL out chain->data (e.g. inode data), it might be
796 if (chain->dio == NULL) {
797 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
798 hammer2_chain_drop_data(chain, 0);
799 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
800 hammer2_chain_drop(chain);
807 if (hammer2_io_isdirty(chain->dio) == 0) {
809 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
810 switch(chain->bref.type) {
811 case HAMMER2_BREF_TYPE_DATA:
812 counterp = &hammer2_ioa_file_write;
814 case HAMMER2_BREF_TYPE_INODE:
815 counterp = &hammer2_ioa_meta_write;
817 case HAMMER2_BREF_TYPE_INDIRECT:
818 counterp = &hammer2_ioa_indr_write;
820 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
821 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
822 counterp = &hammer2_ioa_fmap_write;
825 counterp = &hammer2_ioa_volu_write;
828 *counterp += chain->bytes;
830 switch(chain->bref.type) {
831 case HAMMER2_BREF_TYPE_DATA:
832 counterp = &hammer2_iod_file_write;
834 case HAMMER2_BREF_TYPE_INODE:
835 counterp = &hammer2_iod_meta_write;
837 case HAMMER2_BREF_TYPE_INDIRECT:
838 counterp = &hammer2_iod_indr_write;
840 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
841 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
842 counterp = &hammer2_iod_fmap_write;
845 counterp = &hammer2_iod_volu_write;
848 *counterp += chain->bytes;
854 * If a device buffer was used for data be sure to destroy the
855 * buffer when we are done to avoid aliases (XXX what about the
856 * underlying VM pages?).
858 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
861 * NOTE: The isdirty check tracks whether we have to bdwrite() the
862 * buffer or not. The buffer might already be dirty. The
863 * flag is re-set when chain_modify() is called, even if
864 * MODIFIED is already set, allowing the OS to retire the
865 * buffer independent of a hammer2 flush.
868 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
869 hammer2_io_isdirty(chain->dio)) {
870 hammer2_io_bawrite(&chain->dio);
872 hammer2_io_bqrelse(&chain->dio);
874 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
875 hammer2_chain_drop(chain);
879 * This counts the number of live blockrefs in a block array and
880 * also calculates the point at which all remaining blockrefs are empty.
881 * This routine can only be called on a live chain (DUPLICATED flag not set).
883 * NOTE: Flag is not set until after the count is complete, allowing
884 * callers to test the flag without holding the spinlock.
886 * NOTE: If base is NULL the related chain is still in the INITIAL
887 * state and there are no blockrefs to count.
889 * NOTE: live_count may already have some counts accumulated due to
890 * creation and deletion and could even be initially negative.
893 hammer2_chain_countbrefs(hammer2_chain_t *chain,
894 hammer2_blockref_t *base, int count)
896 spin_lock(&chain->core.cst.spin);
897 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
899 while (--count >= 0) {
900 if (base[count].type)
903 chain->core.live_zero = count + 1;
905 if (base[count].type)
906 atomic_add_int(&chain->core.live_count,
911 chain->core.live_zero = 0;
913 /* else do not modify live_count */
914 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
916 spin_unlock(&chain->core.cst.spin);
920 * Resize the chain's physical storage allocation in-place. This function does
921 * not adjust the data pointer and must be followed by (typically) a
922 * hammer2_chain_modify() call to copy any old data over and adjust the
925 * Chains can be resized smaller without reallocating the storage. Resizing
926 * larger will reallocate the storage. Excess or prior storage is reclaimed
927 * asynchronously at a later time.
929 * Must be passed an exclusively locked parent and chain.
931 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
932 * to avoid instantiating a device buffer that conflicts with the vnode data
933 * buffer. However, because H2 can compress or encrypt data, the chain may
934 * have a dio assigned to it in those situations, and they do not conflict.
936 * XXX return error if cannot resize.
939 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
940 hammer2_chain_t *parent, hammer2_chain_t *chain,
941 int nradix, int flags)
943 hammer2_mount_t *hmp;
950 * Only data and indirect blocks can be resized for now.
951 * (The volu root, inodes, and freemap elements use a fixed size).
953 KKASSERT(chain != &hmp->vchain);
954 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
955 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
958 * Nothing to do if the element is already the proper size
960 obytes = chain->bytes;
961 nbytes = 1U << nradix;
962 if (obytes == nbytes)
964 chain->data_count += (ssize_t)(nbytes - obytes);
967 * Make sure the old data is instantiated so we can copy it. If this
968 * is a data block, the device data may be superfluous since the data
969 * might be in a logical block, but compressed or encrypted data is
972 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
974 hammer2_chain_modify(trans, chain, 0);
977 * Relocate the block, even if making it smaller (because different
978 * block sizes may be in different regions).
980 * (data blocks only, we aren't copying the storage here).
982 hammer2_freemap_alloc(trans, chain, nbytes);
983 chain->bytes = nbytes;
984 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
987 * We don't want the followup chain_modify() to try to copy data
988 * from the old (wrong-sized) buffer. It won't know how much to
989 * copy. This case should only occur during writes when the
990 * originator already has the data to write in-hand.
993 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
994 hammer2_io_brelse(&chain->dio);
1002 * REMOVED - see cluster code
1004 * Set a chain modified, making it read-write and duplicating it if necessary.
1005 * This function will assign a new physical block to the chain if necessary
1007 * Duplication of already-modified chains is possible when the modification
1008 * crosses a flush synchronization boundary.
1010 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1011 * level or the COW operation will not work.
1013 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1014 * run the data through the device buffers.
1016 * This function may return a different chain than was passed, in which case
1017 * the old chain will be unlocked and the new chain will be locked.
1019 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1021 hammer2_inode_data_t *
1022 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1023 hammer2_chain_t **chainp, int flags)
1025 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1026 hammer2_chain_modify(trans, chainp, flags);
1027 if (ip->chain != *chainp)
1028 hammer2_inode_repoint(ip, NULL, *chainp);
1030 vsetisdirty(ip->vp);
1031 return(&ip->chain->data->ipdata);
1037 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1039 hammer2_blockref_t obref;
1040 hammer2_mount_t *hmp;
1048 obref = chain->bref;
1051 * Data is not optional for freemap chains (we must always be sure
1052 * to copy the data on COW storage allocations).
1054 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1055 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1056 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1057 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1061 * Data must be resolved if already assigned unless explicitly
1062 * flagged otherwise.
1064 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1065 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1066 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1067 hammer2_chain_unlock(chain);
1071 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1072 * that the chain has been modified. Set UPDATE to ensure that
1073 * the blockref is updated in the parent.
1075 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1076 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1077 hammer2_chain_ref(chain);
1078 hammer2_pfs_memory_inc(chain->pmp);
1083 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1084 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1085 hammer2_chain_ref(chain);
1089 * The modification or re-modification requires an allocation and
1092 * We normally always allocate new storage here. If storage exists
1093 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1095 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1096 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1097 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1099 hammer2_freemap_alloc(trans, chain, chain->bytes);
1100 /* XXX failed allocation */
1105 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1106 * requires updating as well as to tell the delete code that the
1107 * chain's blockref might not exactly match (in terms of physical size
1108 * or block offset) the one in the parent's blocktable. The base key
1109 * of course will still match.
1111 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1112 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1115 * Short-cut data blocks which the caller does not need an actual
1116 * data reference to (aka OPTDATA), as long as the chain does not
1117 * already have a data pointer to the data. This generally means
1118 * that the modifications are being done via the logical buffer cache.
1119 * The INITIAL flag relates only to the device data buffer and thus
1120 * remains unchange in this situation.
1122 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1123 (flags & HAMMER2_MODIFY_OPTDATA) &&
1124 chain->data == NULL) {
1129 * Clearing the INITIAL flag (for indirect blocks) indicates that
1130 * we've processed the uninitialized storage allocation.
1132 * If this flag is already clear we are likely in a copy-on-write
1133 * situation but we have to be sure NOT to bzero the storage if
1134 * no data is present.
1136 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1137 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1144 * Instantiate data buffer and possibly execute COW operation
1146 switch(chain->bref.type) {
1147 case HAMMER2_BREF_TYPE_VOLUME:
1148 case HAMMER2_BREF_TYPE_FREEMAP:
1150 * The data is embedded, no copy-on-write operation is
1153 KKASSERT(chain->dio == NULL);
1155 case HAMMER2_BREF_TYPE_INODE:
1156 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1157 case HAMMER2_BREF_TYPE_DATA:
1158 case HAMMER2_BREF_TYPE_INDIRECT:
1159 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1161 * Perform the copy-on-write operation
1163 * zero-fill or copy-on-write depending on whether
1164 * chain->data exists or not and set the dirty state for
1165 * the new buffer. hammer2_io_new() will handle the
1168 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1171 error = hammer2_io_new(hmp, chain->bref.data_off,
1172 chain->bytes, &dio);
1174 error = hammer2_io_bread(hmp, chain->bref.data_off,
1175 chain->bytes, &dio);
1177 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1178 KKASSERT(error == 0);
1180 bdata = hammer2_io_data(dio, chain->bref.data_off);
1183 KKASSERT(chain->dio != NULL);
1184 if (chain->data != (void *)bdata) {
1185 bcopy(chain->data, bdata, chain->bytes);
1187 } else if (wasinitial == 0) {
1189 * We have a problem. We were asked to COW but
1190 * we don't have any data to COW with!
1192 panic("hammer2_chain_modify: having a COW %p\n",
1197 * Retire the old buffer, replace with the new. Dirty or
1198 * redirty the new buffer.
1200 * WARNING! The system buffer cache may have already flushed
1201 * the buffer, so we must be sure to [re]dirty it
1202 * for further modification.
1205 hammer2_io_brelse(&chain->dio);
1206 chain->data = (void *)bdata;
1208 hammer2_io_setdirty(dio); /* modified by bcopy above */
1211 panic("hammer2_chain_modify: illegal non-embedded type %d",
1218 * setflush on parent indicating that the parent must recurse down
1219 * to us. Do not call on chain itself which might already have it
1223 hammer2_chain_setflush(trans, chain->parent);
1227 * Adjust the freemap bitmap to indicate that the related blocks
1228 * MIGHT be freeable. Bulkfree must still determine that the blocks
1229 * are actually freeable.
1231 * We no longer do this in the normal filesystem operations path
1232 * as it interferes with the bulkfree algorithm.
1234 if (obref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
1235 obref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
1236 (obref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1237 hammer2_freemap_adjust(trans, hmp,
1238 &obref, HAMMER2_FREEMAP_DOMAYFREE);
1244 * Volume header data locks
1247 hammer2_voldata_lock(hammer2_mount_t *hmp)
1249 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1253 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1255 lockmgr(&hmp->vollk, LK_RELEASE);
1259 hammer2_voldata_modify(hammer2_mount_t *hmp)
1261 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1262 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1263 hammer2_chain_ref(&hmp->vchain);
1264 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1269 * This function returns the chain at the nearest key within the specified
1270 * range. The returned chain will be referenced but not locked.
1272 * This function will recurse through chain->rbtree as necessary and will
1273 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1274 * the iteration value is less than the current value of *key_nextp.
1276 * The caller should use (*key_nextp) to calculate the actual range of
1277 * the returned element, which will be (key_beg to *key_nextp - 1), because
1278 * there might be another element which is superior to the returned element
1281 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1282 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1283 * it will wind up being (key_end + 1).
1285 * WARNING! Must be called with child's spinlock held. Spinlock remains
1286 * held through the operation.
1288 struct hammer2_chain_find_info {
1289 hammer2_chain_t *best;
1290 hammer2_key_t key_beg;
1291 hammer2_key_t key_end;
1292 hammer2_key_t key_next;
1295 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1296 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1300 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1301 hammer2_key_t key_beg, hammer2_key_t key_end)
1303 struct hammer2_chain_find_info info;
1306 info.key_beg = key_beg;
1307 info.key_end = key_end;
1308 info.key_next = *key_nextp;
1310 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1311 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1313 *key_nextp = info.key_next;
1315 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1316 parent, key_beg, key_end, *key_nextp);
1324 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1326 struct hammer2_chain_find_info *info = data;
1327 hammer2_key_t child_beg;
1328 hammer2_key_t child_end;
1330 child_beg = child->bref.key;
1331 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1333 if (child_end < info->key_beg)
1335 if (child_beg > info->key_end)
1342 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1344 struct hammer2_chain_find_info *info = data;
1345 hammer2_chain_t *best;
1346 hammer2_key_t child_end;
1349 * WARNING! Do not discard DUPLICATED chains, it is possible that
1350 * we are catching an insertion half-way done. If a
1351 * duplicated chain turns out to be the best choice the
1352 * caller will re-check its flags after locking it.
1354 * WARNING! Layerq is scanned forwards, exact matches should keep
1355 * the existing info->best.
1357 if ((best = info->best) == NULL) {
1359 * No previous best. Assign best
1362 } else if (best->bref.key <= info->key_beg &&
1363 child->bref.key <= info->key_beg) {
1368 /*info->best = child;*/
1369 } else if (child->bref.key < best->bref.key) {
1371 * Child has a nearer key and best is not flush with key_beg.
1372 * Set best to child. Truncate key_next to the old best key.
1375 if (info->key_next > best->bref.key || info->key_next == 0)
1376 info->key_next = best->bref.key;
1377 } else if (child->bref.key == best->bref.key) {
1379 * If our current best is flush with the child then this
1380 * is an illegal overlap.
1382 * key_next will automatically be limited to the smaller of
1383 * the two end-points.
1389 * Keep the current best but truncate key_next to the child's
1392 * key_next will also automatically be limited to the smaller
1393 * of the two end-points (probably not necessary for this case
1394 * but we do it anyway).
1396 if (info->key_next > child->bref.key || info->key_next == 0)
1397 info->key_next = child->bref.key;
1401 * Always truncate key_next based on child's end-of-range.
1403 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1404 if (child_end && (info->key_next > child_end || info->key_next == 0))
1405 info->key_next = child_end;
1411 * Retrieve the specified chain from a media blockref, creating the
1412 * in-memory chain structure which reflects it.
1414 * To handle insertion races pass the INSERT_RACE flag along with the
1415 * generation number of the core. NULL will be returned if the generation
1416 * number changes before we have a chance to insert the chain. Insert
1417 * races can occur because the parent might be held shared.
1419 * Caller must hold the parent locked shared or exclusive since we may
1420 * need the parent's bref array to find our block.
1422 * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1426 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1427 hammer2_blockref_t *bref)
1429 hammer2_mount_t *hmp = parent->hmp;
1430 hammer2_chain_t *chain;
1434 * Allocate a chain structure representing the existing media
1435 * entry. Resulting chain has one ref and is not locked.
1437 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1438 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1440 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1441 hammer2_chain_core_alloc(NULL, chain);
1442 /* ref'd chain returned */
1445 * Flag that the chain is in the parent's blockmap so delete/flush
1446 * knows what to do with it.
1448 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1451 * Link the chain into its parent. A spinlock is required to safely
1452 * access the RBTREE, and it is possible to collide with another
1453 * hammer2_chain_get() operation because the caller might only hold
1454 * a shared lock on the parent.
1456 KKASSERT(parent->refs > 0);
1457 error = hammer2_chain_insert(parent, chain,
1458 HAMMER2_CHAIN_INSERT_SPIN |
1459 HAMMER2_CHAIN_INSERT_RACE,
1462 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1463 kprintf("chain %p get race\n", chain);
1464 hammer2_chain_drop(chain);
1467 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1471 * Return our new chain referenced but not locked, or NULL if
1478 * Lookup initialization/completion API
1481 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1483 if (flags & HAMMER2_LOOKUP_SHARED) {
1484 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1485 HAMMER2_RESOLVE_SHARED);
1487 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1493 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1496 hammer2_chain_unlock(parent);
1501 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1503 hammer2_chain_t *oparent;
1504 hammer2_chain_t *nparent;
1507 * Be careful of order, oparent must be unlocked before nparent
1508 * is locked below to avoid a deadlock.
1511 spin_lock(&oparent->core.cst.spin);
1512 nparent = oparent->parent;
1513 hammer2_chain_ref(nparent);
1514 spin_unlock(&oparent->core.cst.spin);
1516 hammer2_chain_unlock(oparent);
1520 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1527 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1528 * (*parentp) typically points to an inode but can also point to a related
1529 * indirect block and this function will recurse upwards and find the inode
1532 * (*parentp) must be exclusively locked and referenced and can be an inode
1533 * or an existing indirect block within the inode.
1535 * On return (*parentp) will be modified to point at the deepest parent chain
1536 * element encountered during the search, as a helper for an insertion or
1537 * deletion. The new (*parentp) will be locked and referenced and the old
1538 * will be unlocked and dereferenced (no change if they are both the same).
1540 * The matching chain will be returned exclusively locked. If NOLOCK is
1541 * requested the chain will be returned only referenced.
1543 * NULL is returned if no match was found, but (*parentp) will still
1544 * potentially be adjusted.
1546 * On return (*key_nextp) will point to an iterative value for key_beg.
1547 * (If NULL is returned (*key_nextp) is set to key_end).
1549 * This function will also recurse up the chain if the key is not within the
1550 * current parent's range. (*parentp) can never be set to NULL. An iteration
1551 * can simply allow (*parentp) to float inside the loop.
1553 * NOTE! chain->data is not always resolved. By default it will not be
1554 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1555 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1556 * BREF_TYPE_DATA as the device buffer can alias the logical file
1560 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1561 hammer2_key_t key_beg, hammer2_key_t key_end,
1562 int *cache_indexp, int flags, int *ddflagp)
1564 hammer2_mount_t *hmp;
1565 hammer2_chain_t *parent;
1566 hammer2_chain_t *chain;
1567 hammer2_blockref_t *base;
1568 hammer2_blockref_t *bref;
1569 hammer2_blockref_t bcopy;
1570 hammer2_key_t scan_beg;
1571 hammer2_key_t scan_end;
1573 int how_always = HAMMER2_RESOLVE_ALWAYS;
1574 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1577 int maxloops = 300000;
1580 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1581 how_maybe = how_always;
1582 how = HAMMER2_RESOLVE_ALWAYS;
1583 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1584 how = HAMMER2_RESOLVE_NEVER;
1586 how = HAMMER2_RESOLVE_MAYBE;
1588 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1589 how_maybe |= HAMMER2_RESOLVE_SHARED;
1590 how_always |= HAMMER2_RESOLVE_SHARED;
1591 how |= HAMMER2_RESOLVE_SHARED;
1595 * Recurse (*parentp) upward if necessary until the parent completely
1596 * encloses the key range or we hit the inode.
1598 * This function handles races against the flusher doing a delete-
1599 * duplicate above us and re-homes the parent to the duplicate in
1600 * that case, otherwise we'd wind up recursing down a stale chain.
1605 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1606 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1607 scan_beg = parent->bref.key;
1608 scan_end = scan_beg +
1609 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1610 if (key_beg >= scan_beg && key_end <= scan_end)
1612 parent = hammer2_chain_getparent(parentp, how_maybe);
1616 if (--maxloops == 0)
1617 panic("hammer2_chain_lookup: maxloops");
1619 * Locate the blockref array. Currently we do a fully associative
1620 * search through the array.
1622 switch(parent->bref.type) {
1623 case HAMMER2_BREF_TYPE_INODE:
1625 * Special shortcut for embedded data returns the inode
1626 * itself. Callers must detect this condition and access
1627 * the embedded data (the strategy code does this for us).
1629 * This is only applicable to regular files and softlinks.
1631 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1632 if (flags & HAMMER2_LOOKUP_NOLOCK)
1633 hammer2_chain_ref(parent);
1635 hammer2_chain_lock(parent, how_always);
1636 *key_nextp = key_end + 1;
1640 base = &parent->data->ipdata.u.blockset.blockref[0];
1641 count = HAMMER2_SET_COUNT;
1643 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1644 case HAMMER2_BREF_TYPE_INDIRECT:
1646 * Handle MATCHIND on the parent
1648 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1649 scan_beg = parent->bref.key;
1650 scan_end = scan_beg +
1651 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1652 if (key_beg == scan_beg && key_end == scan_end) {
1654 hammer2_chain_lock(chain, how_maybe);
1655 *key_nextp = scan_end + 1;
1660 * Optimize indirect blocks in the INITIAL state to avoid
1663 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1666 if (parent->data == NULL)
1667 panic("parent->data is NULL");
1668 base = &parent->data->npdata[0];
1670 count = parent->bytes / sizeof(hammer2_blockref_t);
1672 case HAMMER2_BREF_TYPE_VOLUME:
1673 base = &hmp->voldata.sroot_blockset.blockref[0];
1674 count = HAMMER2_SET_COUNT;
1676 case HAMMER2_BREF_TYPE_FREEMAP:
1677 base = &hmp->voldata.freemap_blockset.blockref[0];
1678 count = HAMMER2_SET_COUNT;
1681 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1683 base = NULL; /* safety */
1684 count = 0; /* safety */
1688 * Merged scan to find next candidate.
1690 * hammer2_base_*() functions require the parent->core.live_* fields
1691 * to be synchronized.
1693 * We need to hold the spinlock to access the block array and RB tree
1694 * and to interlock chain creation.
1696 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1697 hammer2_chain_countbrefs(parent, base, count);
1702 spin_lock(&parent->core.cst.spin);
1703 chain = hammer2_combined_find(parent, base, count,
1704 cache_indexp, key_nextp,
1707 generation = parent->core.generation;
1710 * Exhausted parent chain, iterate.
1713 spin_unlock(&parent->core.cst.spin);
1714 if (key_beg == key_end) /* short cut single-key case */
1718 * Stop if we reached the end of the iteration.
1720 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1721 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1726 * Calculate next key, stop if we reached the end of the
1727 * iteration, otherwise go up one level and loop.
1729 key_beg = parent->bref.key +
1730 ((hammer2_key_t)1 << parent->bref.keybits);
1731 if (key_beg == 0 || key_beg > key_end)
1733 parent = hammer2_chain_getparent(parentp, how_maybe);
1738 * Selected from blockref or in-memory chain.
1740 if (chain == NULL) {
1742 spin_unlock(&parent->core.cst.spin);
1743 chain = hammer2_chain_get(parent, generation,
1745 if (chain == NULL) {
1746 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1747 parent, key_beg, key_end);
1750 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1751 hammer2_chain_drop(chain);
1755 hammer2_chain_ref(chain);
1756 spin_unlock(&parent->core.cst.spin);
1760 * chain is referenced but not locked. We must lock the chain
1761 * to obtain definitive DUPLICATED/DELETED state
1763 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1764 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1765 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1767 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1771 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1773 * NOTE: Chain's key range is not relevant as there might be
1774 * one-offs within the range that are not deleted.
1776 * NOTE: Lookups can race delete-duplicate because
1777 * delete-duplicate does not lock the parent's core
1778 * (they just use the spinlock on the core). We must
1779 * check for races by comparing the DUPLICATED flag before
1780 * releasing the spinlock with the flag after locking the
1783 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1784 hammer2_chain_unlock(chain);
1785 key_beg = *key_nextp;
1786 if (key_beg == 0 || key_beg > key_end)
1792 * If the chain element is an indirect block it becomes the new
1793 * parent and we loop on it. We must maintain our top-down locks
1794 * to prevent the flusher from interfering (i.e. doing a
1795 * delete-duplicate and leaving us recursing down a deleted chain).
1797 * The parent always has to be locked with at least RESOLVE_MAYBE
1798 * so we can access its data. It might need a fixup if the caller
1799 * passed incompatible flags. Be careful not to cause a deadlock
1800 * as a data-load requires an exclusive lock.
1802 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1803 * range is within the requested key range we return the indirect
1804 * block and do NOT loop. This is usually only used to acquire
1807 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1808 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1809 hammer2_chain_unlock(parent);
1810 *parentp = parent = chain;
1815 * All done, return the chain
1821 * After having issued a lookup we can iterate all matching keys.
1823 * If chain is non-NULL we continue the iteration from just after it's index.
1825 * If chain is NULL we assume the parent was exhausted and continue the
1826 * iteration at the next parent.
1828 * parent must be locked on entry and remains locked throughout. chain's
1829 * lock status must match flags. Chain is always at least referenced.
1831 * WARNING! The MATCHIND flag does not apply to this function.
1834 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1835 hammer2_key_t *key_nextp,
1836 hammer2_key_t key_beg, hammer2_key_t key_end,
1837 int *cache_indexp, int flags)
1839 hammer2_chain_t *parent;
1844 * Calculate locking flags for upward recursion.
1846 how_maybe = HAMMER2_RESOLVE_MAYBE;
1847 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1848 how_maybe |= HAMMER2_RESOLVE_SHARED;
1853 * Calculate the next index and recalculate the parent if necessary.
1856 key_beg = chain->bref.key +
1857 ((hammer2_key_t)1 << chain->bref.keybits);
1858 if (flags & HAMMER2_LOOKUP_NOLOCK)
1859 hammer2_chain_drop(chain);
1861 hammer2_chain_unlock(chain);
1864 * Any scan where the lookup returned degenerate data embedded
1865 * in the inode has an invalid index and must terminate.
1867 if (chain == parent)
1869 if (key_beg == 0 || key_beg > key_end)
1872 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1873 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1875 * We reached the end of the iteration.
1880 * Continue iteration with next parent unless the current
1881 * parent covers the range.
1883 key_beg = parent->bref.key +
1884 ((hammer2_key_t)1 << parent->bref.keybits);
1885 if (key_beg == 0 || key_beg > key_end)
1887 parent = hammer2_chain_getparent(parentp, how_maybe);
1893 return (hammer2_chain_lookup(parentp, key_nextp,
1895 cache_indexp, flags, &ddflag));
1899 * The raw scan function is similar to lookup/next but does not seek to a key.
1900 * Blockrefs are iterated via first_chain = (parent, NULL) and
1901 * next_chain = (parent, chain).
1903 * The passed-in parent must be locked and its data resolved. The returned
1904 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1905 * under parent and then iterate with the passed-in chain (which this
1906 * function will unlock).
1909 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1910 int *cache_indexp, int flags)
1912 hammer2_mount_t *hmp;
1913 hammer2_blockref_t *base;
1914 hammer2_blockref_t *bref;
1915 hammer2_blockref_t bcopy;
1917 hammer2_key_t next_key;
1919 int how_always = HAMMER2_RESOLVE_ALWAYS;
1920 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1923 int maxloops = 300000;
1928 * Scan flags borrowed from lookup
1930 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1931 how_maybe = how_always;
1932 how = HAMMER2_RESOLVE_ALWAYS;
1933 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1934 how = HAMMER2_RESOLVE_NEVER;
1936 how = HAMMER2_RESOLVE_MAYBE;
1938 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1939 how_maybe |= HAMMER2_RESOLVE_SHARED;
1940 how_always |= HAMMER2_RESOLVE_SHARED;
1941 how |= HAMMER2_RESOLVE_SHARED;
1945 * Calculate key to locate first/next element, unlocking the previous
1946 * element as we go. Be careful, the key calculation can overflow.
1949 key = chain->bref.key +
1950 ((hammer2_key_t)1 << chain->bref.keybits);
1951 hammer2_chain_unlock(chain);
1960 if (--maxloops == 0)
1961 panic("hammer2_chain_scan: maxloops");
1963 * Locate the blockref array. Currently we do a fully associative
1964 * search through the array.
1966 switch(parent->bref.type) {
1967 case HAMMER2_BREF_TYPE_INODE:
1969 * An inode with embedded data has no sub-chains.
1971 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1973 base = &parent->data->ipdata.u.blockset.blockref[0];
1974 count = HAMMER2_SET_COUNT;
1976 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1977 case HAMMER2_BREF_TYPE_INDIRECT:
1979 * Optimize indirect blocks in the INITIAL state to avoid
1982 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1985 if (parent->data == NULL)
1986 panic("parent->data is NULL");
1987 base = &parent->data->npdata[0];
1989 count = parent->bytes / sizeof(hammer2_blockref_t);
1991 case HAMMER2_BREF_TYPE_VOLUME:
1992 base = &hmp->voldata.sroot_blockset.blockref[0];
1993 count = HAMMER2_SET_COUNT;
1995 case HAMMER2_BREF_TYPE_FREEMAP:
1996 base = &hmp->voldata.freemap_blockset.blockref[0];
1997 count = HAMMER2_SET_COUNT;
2000 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2002 base = NULL; /* safety */
2003 count = 0; /* safety */
2007 * Merged scan to find next candidate.
2009 * hammer2_base_*() functions require the parent->core.live_* fields
2010 * to be synchronized.
2012 * We need to hold the spinlock to access the block array and RB tree
2013 * and to interlock chain creation.
2015 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2016 hammer2_chain_countbrefs(parent, base, count);
2019 spin_lock(&parent->core.cst.spin);
2020 chain = hammer2_combined_find(parent, base, count,
2021 cache_indexp, &next_key,
2022 key, HAMMER2_KEY_MAX,
2024 generation = parent->core.generation;
2027 * Exhausted parent chain, we're done.
2030 spin_unlock(&parent->core.cst.spin);
2031 KKASSERT(chain == NULL);
2036 * Selected from blockref or in-memory chain.
2038 if (chain == NULL) {
2040 spin_unlock(&parent->core.cst.spin);
2041 chain = hammer2_chain_get(parent, generation, &bcopy);
2042 if (chain == NULL) {
2043 kprintf("retry scan parent %p keys %016jx\n",
2047 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2048 hammer2_chain_drop(chain);
2053 hammer2_chain_ref(chain);
2054 spin_unlock(&parent->core.cst.spin);
2058 * chain is referenced but not locked. We must lock the chain
2059 * to obtain definitive DUPLICATED/DELETED state
2061 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2064 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2066 * NOTE: chain's key range is not relevant as there might be
2067 * one-offs within the range that are not deleted.
2069 * NOTE: XXX this could create problems with scans used in
2070 * situations other than mount-time recovery.
2072 * NOTE: Lookups can race delete-duplicate because
2073 * delete-duplicate does not lock the parent's core
2074 * (they just use the spinlock on the core). We must
2075 * check for races by comparing the DUPLICATED flag before
2076 * releasing the spinlock with the flag after locking the
2079 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2080 hammer2_chain_unlock(chain);
2091 * All done, return the chain or NULL
2097 * Create and return a new hammer2 system memory structure of the specified
2098 * key, type and size and insert it under (*parentp). This is a full
2099 * insertion, based on the supplied key/keybits, and may involve creating
2100 * indirect blocks and moving other chains around via delete/duplicate.
2102 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2103 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2104 * FULL. This typically means that the caller is creating the chain after
2105 * doing a hammer2_chain_lookup().
2107 * (*parentp) must be exclusive locked and may be replaced on return
2108 * depending on how much work the function had to do.
2110 * (*chainp) usually starts out NULL and returns the newly created chain,
2111 * but if the caller desires the caller may allocate a disconnected chain
2112 * and pass it in instead.
2114 * This function should NOT be used to insert INDIRECT blocks. It is
2115 * typically used to create/insert inodes and data blocks.
2117 * Caller must pass-in an exclusively locked parent the new chain is to
2118 * be inserted under, and optionally pass-in a disconnected, exclusively
2119 * locked chain to insert (else we create a new chain). The function will
2120 * adjust (*parentp) as necessary, create or connect the chain, and
2121 * return an exclusively locked chain in *chainp.
2124 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2125 hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2126 hammer2_key_t key, int keybits, int type, size_t bytes,
2129 hammer2_mount_t *hmp;
2130 hammer2_chain_t *chain;
2131 hammer2_chain_t *parent;
2132 hammer2_blockref_t *base;
2133 hammer2_blockref_t dummy;
2137 int maxloops = 300000;
2140 * Topology may be crossing a PFS boundary.
2143 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2147 if (chain == NULL) {
2149 * First allocate media space and construct the dummy bref,
2150 * then allocate the in-memory chain structure. Set the
2151 * INITIAL flag for fresh chains which do not have embedded
2154 bzero(&dummy, sizeof(dummy));
2157 dummy.keybits = keybits;
2158 dummy.data_off = hammer2_getradix(bytes);
2159 dummy.methods = parent->bref.methods;
2160 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2161 hammer2_chain_core_alloc(trans, chain);
2164 * Lock the chain manually, chain_lock will load the chain
2165 * which we do NOT want to do. (note: chain->refs is set
2166 * to 1 by chain_alloc() for us, but lockcnt is not).
2169 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
2173 * We do NOT set INITIAL here (yet). INITIAL is only
2174 * used for indirect blocks.
2176 * Recalculate bytes to reflect the actual media block
2179 bytes = (hammer2_off_t)1 <<
2180 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2181 chain->bytes = bytes;
2184 case HAMMER2_BREF_TYPE_VOLUME:
2185 case HAMMER2_BREF_TYPE_FREEMAP:
2186 panic("hammer2_chain_create: called with volume type");
2188 case HAMMER2_BREF_TYPE_INDIRECT:
2189 panic("hammer2_chain_create: cannot be used to"
2190 "create indirect block");
2192 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2193 panic("hammer2_chain_create: cannot be used to"
2194 "create freemap root or node");
2196 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2197 KKASSERT(bytes == sizeof(chain->data->bmdata));
2199 case HAMMER2_BREF_TYPE_INODE:
2200 case HAMMER2_BREF_TYPE_DATA:
2203 * leave chain->data NULL, set INITIAL
2205 KKASSERT(chain->data == NULL);
2206 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2211 * Set statistics for pending updates. These will be
2212 * synchronized by the flush code.
2215 case HAMMER2_BREF_TYPE_INODE:
2216 chain->inode_count = 1;
2218 case HAMMER2_BREF_TYPE_DATA:
2219 case HAMMER2_BREF_TYPE_INDIRECT:
2220 chain->data_count = chain->bytes;
2225 * We are reattaching a previously deleted chain, possibly
2226 * under a new parent and possibly with a new key/keybits.
2227 * The chain does not have to be in a modified state. The
2228 * UPDATE flag will be set later on in this routine.
2230 * Do NOT mess with the current state of the INITIAL flag.
2232 chain->bref.key = key;
2233 chain->bref.keybits = keybits;
2234 if (chain->flags & HAMMER2_CHAIN_DELETED)
2235 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2236 KKASSERT(chain->parent == NULL);
2240 * Calculate how many entries we have in the blockref array and
2241 * determine if an indirect block is required.
2244 if (--maxloops == 0)
2245 panic("hammer2_chain_create: maxloops");
2247 switch(parent->bref.type) {
2248 case HAMMER2_BREF_TYPE_INODE:
2249 KKASSERT((parent->data->ipdata.op_flags &
2250 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2251 KKASSERT(parent->data != NULL);
2252 base = &parent->data->ipdata.u.blockset.blockref[0];
2253 count = HAMMER2_SET_COUNT;
2255 case HAMMER2_BREF_TYPE_INDIRECT:
2256 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2257 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2260 base = &parent->data->npdata[0];
2261 count = parent->bytes / sizeof(hammer2_blockref_t);
2263 case HAMMER2_BREF_TYPE_VOLUME:
2264 KKASSERT(parent->data != NULL);
2265 base = &hmp->voldata.sroot_blockset.blockref[0];
2266 count = HAMMER2_SET_COUNT;
2268 case HAMMER2_BREF_TYPE_FREEMAP:
2269 KKASSERT(parent->data != NULL);
2270 base = &hmp->voldata.freemap_blockset.blockref[0];
2271 count = HAMMER2_SET_COUNT;
2274 panic("hammer2_chain_create: unrecognized blockref type: %d",
2282 * Make sure we've counted the brefs
2284 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2285 hammer2_chain_countbrefs(parent, base, count);
2287 KKASSERT(parent->core.live_count >= 0 &&
2288 parent->core.live_count <= count);
2291 * If no free blockref could be found we must create an indirect
2292 * block and move a number of blockrefs into it. With the parent
2293 * locked we can safely lock each child in order to delete+duplicate
2294 * it without causing a deadlock.
2296 * This may return the new indirect block or the old parent depending
2297 * on where the key falls. NULL is returned on error.
2299 if (parent->core.live_count == count) {
2300 hammer2_chain_t *nparent;
2302 nparent = hammer2_chain_create_indirect(trans, parent,
2305 if (nparent == NULL) {
2307 hammer2_chain_drop(chain);
2311 if (parent != nparent) {
2312 hammer2_chain_unlock(parent);
2313 parent = *parentp = nparent;
2319 * Link the chain into its parent.
2321 if (chain->parent != NULL)
2322 panic("hammer2: hammer2_chain_create: chain already connected");
2323 KKASSERT(chain->parent == NULL);
2324 hammer2_chain_insert(parent, chain,
2325 HAMMER2_CHAIN_INSERT_SPIN |
2326 HAMMER2_CHAIN_INSERT_LIVE,
2331 * Mark the newly created chain modified. This will cause
2334 * Device buffers are not instantiated for DATA elements
2335 * as these are handled by logical buffers.
2337 * Indirect and freemap node indirect blocks are handled
2338 * by hammer2_chain_create_indirect() and not by this
2341 * Data for all other bref types is expected to be
2342 * instantiated (INODE, LEAF).
2344 switch(chain->bref.type) {
2345 case HAMMER2_BREF_TYPE_DATA:
2346 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2347 case HAMMER2_BREF_TYPE_INODE:
2348 hammer2_chain_modify(trans, chain,
2349 HAMMER2_MODIFY_OPTDATA);
2353 * Remaining types are not supported by this function.
2354 * In particular, INDIRECT and LEAF_NODE types are
2355 * handled by create_indirect().
2357 panic("hammer2_chain_create: bad type: %d",
2364 * When reconnecting a chain we must set UPDATE and
2365 * setflush so the flush recognizes that it must update
2366 * the bref in the parent.
2368 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2369 hammer2_chain_ref(chain);
2370 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2372 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2373 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2374 KKASSERT(chain->data);
2375 chain->inode_count_up +=
2376 chain->data->ipdata.inode_count;
2377 chain->data_count_up +=
2378 chain->data->ipdata.data_count;
2383 * We must setflush(parent) to ensure that it recurses through to
2384 * chain. setflush(chain) might not work because ONFLUSH is possibly
2385 * already set in the chain (so it won't recurse up to set it in the
2388 hammer2_chain_setflush(trans, parent);
2397 * Move the chain from its old parent to a new parent. The chain must have
2398 * already been deleted or already disconnected (or never associated) with
2399 * a parent. The chain is reassociated with the new parent and the deleted
2400 * flag will be cleared (no longer deleted). The chain's modification state
2403 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2404 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2405 * FULL. This typically means that the caller is creating the chain after
2406 * doing a hammer2_chain_lookup().
2408 * A non-NULL bref is typically passed when key and keybits must be overridden.
2409 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2410 * from a passed-in bref and uses the old chain's bref for everything else.
2412 * If (parent) is non-NULL then the new duplicated chain is inserted under
2415 * If (parent) is NULL then the newly duplicated chain is not inserted
2416 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2417 * passing into hammer2_chain_create() after this function returns).
2419 * WARNING! This function calls create which means it can insert indirect
2420 * blocks. This can cause other unrelated chains in the parent to
2421 * be moved to a newly inserted indirect block in addition to the
2425 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2426 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2429 hammer2_mount_t *hmp;
2430 hammer2_chain_t *parent;
2434 * WARNING! We should never resolve DATA to device buffers
2435 * (XXX allow it if the caller did?), and since
2436 * we currently do not have the logical buffer cache
2437 * buffer in-hand to fix its cached physical offset
2438 * we also force the modify code to not COW it. XXX
2441 KKASSERT(chain->parent == NULL);
2444 * Now create a duplicate of the chain structure, associating
2445 * it with the same core, making it the same size, pointing it
2446 * to the same bref (the same media block).
2449 bref = &chain->bref;
2450 bytes = (hammer2_off_t)1 <<
2451 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2454 * If parent is not NULL the duplicated chain will be entered under
2455 * the parent and the UPDATE bit set to tell flush to update
2458 * We must setflush(parent) to ensure that it recurses through to
2459 * chain. setflush(chain) might not work because ONFLUSH is possibly
2460 * already set in the chain (so it won't recurse up to set it in the
2463 * Having both chains locked is extremely important for atomicy.
2465 if (parentp && (parent = *parentp) != NULL) {
2466 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2467 KKASSERT(parent->refs > 0);
2469 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2470 bref->key, bref->keybits, bref->type,
2471 chain->bytes, flags);
2472 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2473 hammer2_chain_setflush(trans, *parentp);
2478 * Helper function for deleting chains.
2480 * The chain is removed from the live view (the RBTREE) as well as the parent's
2481 * blockmap. Both chain and its parent must be locked.
2484 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2485 hammer2_chain_t *parent, hammer2_chain_t *chain,
2488 hammer2_mount_t *hmp;
2490 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2493 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2495 * Chain is blockmapped, so there must be a parent.
2496 * Atomically remove the chain from the parent and remove
2497 * the blockmap entry.
2499 hammer2_blockref_t *base;
2502 KKASSERT(parent != NULL);
2503 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2504 hammer2_chain_modify(trans, parent,
2505 HAMMER2_MODIFY_OPTDATA);
2508 * Calculate blockmap pointer
2510 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2511 spin_lock(&parent->core.cst.spin);
2513 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2514 atomic_add_int(&parent->core.live_count, -1);
2515 ++parent->core.generation;
2516 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2517 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2518 --parent->core.chain_count;
2519 chain->parent = NULL;
2521 switch(parent->bref.type) {
2522 case HAMMER2_BREF_TYPE_INODE:
2524 * Access the inode's block array. However, there
2525 * is no block array if the inode is flagged
2526 * DIRECTDATA. The DIRECTDATA case typicaly only
2527 * occurs when a hardlink has been shifted up the
2528 * tree and the original inode gets replaced with
2529 * an OBJTYPE_HARDLINK placeholding inode.
2532 (parent->data->ipdata.op_flags &
2533 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2535 &parent->data->ipdata.u.blockset.blockref[0];
2539 count = HAMMER2_SET_COUNT;
2541 case HAMMER2_BREF_TYPE_INDIRECT:
2542 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2544 base = &parent->data->npdata[0];
2547 count = parent->bytes / sizeof(hammer2_blockref_t);
2549 case HAMMER2_BREF_TYPE_VOLUME:
2550 base = &hmp->voldata.sroot_blockset.blockref[0];
2551 count = HAMMER2_SET_COUNT;
2553 case HAMMER2_BREF_TYPE_FREEMAP:
2554 base = &parent->data->npdata[0];
2555 count = HAMMER2_SET_COUNT;
2560 panic("hammer2_flush_pass2: "
2561 "unrecognized blockref type: %d",
2566 * delete blockmapped chain from its parent.
2568 * The parent is not affected by any statistics in chain
2569 * which are pending synchronization. That is, there is
2570 * nothing to undo in the parent since they have not yet
2571 * been incorporated into the parent.
2573 * The parent is affected by statistics stored in inodes.
2574 * Those have already been synchronized, so they must be
2575 * undone. XXX split update possible w/delete in middle?
2578 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2579 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2580 KKASSERT(chain->data != NULL);
2581 parent->data_count -=
2582 chain->data->ipdata.data_count;
2583 parent->inode_count -=
2584 chain->data->ipdata.inode_count;
2587 int cache_index = -1;
2588 hammer2_base_delete(trans, parent, base, count,
2589 &cache_index, chain);
2591 spin_unlock(&parent->core.cst.spin);
2592 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2594 * Chain is not blockmapped but a parent is present.
2595 * Atomically remove the chain from the parent. There is
2596 * no blockmap entry to remove.
2598 * Because chain was associated with a parent but not
2599 * synchronized, the chain's *_count_up fields contain
2600 * inode adjustment statistics which must be undone.
2602 spin_lock(&parent->core.cst.spin);
2603 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2604 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2605 KKASSERT(chain->data != NULL);
2606 chain->data_count_up -=
2607 chain->data->ipdata.data_count;
2608 chain->inode_count_up -=
2609 chain->data->ipdata.inode_count;
2611 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2612 atomic_add_int(&parent->core.live_count, -1);
2613 ++parent->core.generation;
2614 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2615 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2616 --parent->core.chain_count;
2617 chain->parent = NULL;
2618 spin_unlock(&parent->core.cst.spin);
2621 * Chain is not blockmapped and has no parent. This
2622 * is a degenerate case.
2624 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2629 * If the deletion is permanent (i.e. the chain is not simply being
2630 * moved within the topology), adjust the freemap to indicate that
2631 * the block *might* be freeable. bulkfree must still determine
2632 * that it is actually freeable.
2634 * We no longer do this in the normal filesystem operations path
2635 * as it interferes with the bulkfree algorithm.
2637 if ((flags & HAMMER2_DELETE_PERMANENT) &&
2638 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2639 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
2640 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
2641 hammer2_freemap_adjust(trans, hmp, &chain->bref,
2642 HAMMER2_FREEMAP_DOMAYFREE);
2648 * Create an indirect block that covers one or more of the elements in the
2649 * current parent. Either returns the existing parent with no locking or
2650 * ref changes or returns the new indirect block locked and referenced
2651 * and leaving the original parent lock/ref intact as well.
2653 * If an error occurs, NULL is returned and *errorp is set to the error.
2655 * The returned chain depends on where the specified key falls.
2657 * The key/keybits for the indirect mode only needs to follow three rules:
2659 * (1) That all elements underneath it fit within its key space and
2661 * (2) That all elements outside it are outside its key space.
2663 * (3) When creating the new indirect block any elements in the current
2664 * parent that fit within the new indirect block's keyspace must be
2665 * moved into the new indirect block.
2667 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2668 * keyspace the the current parent, but lookup/iteration rules will
2669 * ensure (and must ensure) that rule (2) for all parents leading up
2670 * to the nearest inode or the root volume header is adhered to. This
2671 * is accomplished by always recursing through matching keyspaces in
2672 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2674 * The current implementation calculates the current worst-case keyspace by
2675 * iterating the current parent and then divides it into two halves, choosing
2676 * whichever half has the most elements (not necessarily the half containing
2677 * the requested key).
2679 * We can also opt to use the half with the least number of elements. This
2680 * causes lower-numbered keys (aka logical file offsets) to recurse through
2681 * fewer indirect blocks and higher-numbered keys to recurse through more.
2682 * This also has the risk of not moving enough elements to the new indirect
2683 * block and being forced to create several indirect blocks before the element
2686 * Must be called with an exclusively locked parent.
2688 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2689 hammer2_key_t *keyp, int keybits,
2690 hammer2_blockref_t *base, int count);
2691 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2692 hammer2_key_t *keyp, int keybits,
2693 hammer2_blockref_t *base, int count);
2696 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2697 hammer2_key_t create_key, int create_bits,
2698 int for_type, int *errorp)
2700 hammer2_mount_t *hmp;
2701 hammer2_blockref_t *base;
2702 hammer2_blockref_t *bref;
2703 hammer2_blockref_t bcopy;
2704 hammer2_chain_t *chain;
2705 hammer2_chain_t *ichain;
2706 hammer2_chain_t dummy;
2707 hammer2_key_t key = create_key;
2708 hammer2_key_t key_beg;
2709 hammer2_key_t key_end;
2710 hammer2_key_t key_next;
2711 int keybits = create_bits;
2718 int maxloops = 300000;
2721 * Calculate the base blockref pointer or NULL if the chain
2722 * is known to be empty. We need to calculate the array count
2723 * for RB lookups either way.
2727 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2729 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2730 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2733 switch(parent->bref.type) {
2734 case HAMMER2_BREF_TYPE_INODE:
2735 count = HAMMER2_SET_COUNT;
2737 case HAMMER2_BREF_TYPE_INDIRECT:
2738 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2739 count = parent->bytes / sizeof(hammer2_blockref_t);
2741 case HAMMER2_BREF_TYPE_VOLUME:
2742 count = HAMMER2_SET_COUNT;
2744 case HAMMER2_BREF_TYPE_FREEMAP:
2745 count = HAMMER2_SET_COUNT;
2748 panic("hammer2_chain_create_indirect: "
2749 "unrecognized blockref type: %d",
2755 switch(parent->bref.type) {
2756 case HAMMER2_BREF_TYPE_INODE:
2757 base = &parent->data->ipdata.u.blockset.blockref[0];
2758 count = HAMMER2_SET_COUNT;
2760 case HAMMER2_BREF_TYPE_INDIRECT:
2761 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2762 base = &parent->data->npdata[0];
2763 count = parent->bytes / sizeof(hammer2_blockref_t);
2765 case HAMMER2_BREF_TYPE_VOLUME:
2766 base = &hmp->voldata.sroot_blockset.blockref[0];
2767 count = HAMMER2_SET_COUNT;
2769 case HAMMER2_BREF_TYPE_FREEMAP:
2770 base = &hmp->voldata.freemap_blockset.blockref[0];
2771 count = HAMMER2_SET_COUNT;
2774 panic("hammer2_chain_create_indirect: "
2775 "unrecognized blockref type: %d",
2783 * dummy used in later chain allocation (no longer used for lookups).
2785 bzero(&dummy, sizeof(dummy));
2788 * When creating an indirect block for a freemap node or leaf
2789 * the key/keybits must be fitted to static radix levels because
2790 * particular radix levels use particular reserved blocks in the
2793 * This routine calculates the key/radix of the indirect block
2794 * we need to create, and whether it is on the high-side or the
2797 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2798 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2799 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2802 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2807 * Normalize the key for the radix being represented, keeping the
2808 * high bits and throwing away the low bits.
2810 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2813 * How big should our new indirect block be? It has to be at least
2814 * as large as its parent.
2816 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2817 nbytes = HAMMER2_IND_BYTES_MIN;
2819 nbytes = HAMMER2_IND_BYTES_MAX;
2820 if (nbytes < count * sizeof(hammer2_blockref_t))
2821 nbytes = count * sizeof(hammer2_blockref_t);
2824 * Ok, create our new indirect block
2826 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2827 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2828 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2830 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2832 dummy.bref.key = key;
2833 dummy.bref.keybits = keybits;
2834 dummy.bref.data_off = hammer2_getradix(nbytes);
2835 dummy.bref.methods = parent->bref.methods;
2837 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2838 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2839 hammer2_chain_core_alloc(trans, ichain);
2840 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2841 hammer2_chain_drop(ichain); /* excess ref from alloc */
2844 * We have to mark it modified to allocate its block, but use
2845 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2846 * it won't be acted upon by the flush code.
2848 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2851 * Iterate the original parent and move the matching brefs into
2852 * the new indirect block.
2854 * XXX handle flushes.
2857 key_end = HAMMER2_KEY_MAX;
2859 spin_lock(&parent->core.cst.spin);
2864 if (++loops > 100000) {
2865 spin_unlock(&parent->core.cst.spin);
2866 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2867 reason, parent, base, count, key_next);
2871 * NOTE: spinlock stays intact, returned chain (if not NULL)
2872 * is not referenced or locked which means that we
2873 * cannot safely check its flagged / deletion status
2876 chain = hammer2_combined_find(parent, base, count,
2877 &cache_index, &key_next,
2880 generation = parent->core.generation;
2883 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2886 * Skip keys that are not within the key/radix of the new
2887 * indirect block. They stay in the parent.
2889 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2890 (key ^ bref->key)) != 0) {
2891 goto next_key_spinlocked;
2895 * Load the new indirect block by acquiring the related
2896 * chains (potentially from media as it might not be
2897 * in-memory). Then move it to the new parent (ichain)
2898 * via DELETE-DUPLICATE.
2900 * chain is referenced but not locked. We must lock the
2901 * chain to obtain definitive DUPLICATED/DELETED state
2905 * Use chain already present in the RBTREE
2907 hammer2_chain_ref(chain);
2908 spin_unlock(&parent->core.cst.spin);
2909 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2910 HAMMER2_RESOLVE_NOREF);
2913 * Get chain for blockref element. _get returns NULL
2914 * on insertion race.
2917 spin_unlock(&parent->core.cst.spin);
2918 chain = hammer2_chain_get(parent, generation, &bcopy);
2919 if (chain == NULL) {
2921 spin_lock(&parent->core.cst.spin);
2924 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2925 kprintf("REASON 2\n");
2927 hammer2_chain_drop(chain);
2928 spin_lock(&parent->core.cst.spin);
2931 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2932 HAMMER2_RESOLVE_NOREF);
2936 * This is always live so if the chain has been deleted
2937 * we raced someone and we have to retry.
2939 * NOTE: Lookups can race delete-duplicate because
2940 * delete-duplicate does not lock the parent's core
2941 * (they just use the spinlock on the core). We must
2942 * check for races by comparing the DUPLICATED flag before
2943 * releasing the spinlock with the flag after locking the
2946 * (note reversed logic for this one)
2948 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2949 hammer2_chain_unlock(chain);
2954 * Shift the chain to the indirect block.
2956 * WARNING! No reason for us to load chain data, pass NOSTATS
2957 * to prevent delete/insert from trying to access
2958 * inode stats (and thus asserting if there is no
2959 * chain->data loaded).
2961 hammer2_chain_delete(trans, parent, chain,
2962 HAMMER2_DELETE_NOSTATS);
2963 hammer2_chain_rename(trans, NULL, &ichain, chain,
2964 HAMMER2_INSERT_NOSTATS);
2965 hammer2_chain_unlock(chain);
2966 KKASSERT(parent->refs > 0);
2969 spin_lock(&parent->core.cst.spin);
2970 next_key_spinlocked:
2971 if (--maxloops == 0)
2972 panic("hammer2_chain_create_indirect: maxloops");
2974 if (key_next == 0 || key_next > key_end)
2979 spin_unlock(&parent->core.cst.spin);
2982 * Insert the new indirect block into the parent now that we've
2983 * cleared out some entries in the parent. We calculated a good
2984 * insertion index in the loop above (ichain->index).
2986 * We don't have to set UPDATE here because we mark ichain
2987 * modified down below (so the normal modified -> flush -> set-moved
2988 * sequence applies).
2990 * The insertion shouldn't race as this is a completely new block
2991 * and the parent is locked.
2993 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2994 hammer2_chain_insert(parent, ichain,
2995 HAMMER2_CHAIN_INSERT_SPIN |
2996 HAMMER2_CHAIN_INSERT_LIVE,
3000 * Make sure flushes propogate after our manual insertion.
3002 hammer2_chain_setflush(trans, ichain);
3003 hammer2_chain_setflush(trans, parent);
3006 * Figure out what to return.
3008 if (~(((hammer2_key_t)1 << keybits) - 1) &
3009 (create_key ^ key)) {
3011 * Key being created is outside the key range,
3012 * return the original parent.
3014 hammer2_chain_unlock(ichain);
3017 * Otherwise its in the range, return the new parent.
3018 * (leave both the new and old parent locked).
3027 * Calculate the keybits and highside/lowside of the freemap node the
3028 * caller is creating.
3030 * This routine will specify the next higher-level freemap key/radix
3031 * representing the lowest-ordered set. By doing so, eventually all
3032 * low-ordered sets will be moved one level down.
3034 * We have to be careful here because the freemap reserves a limited
3035 * number of blocks for a limited number of levels. So we can't just
3036 * push indiscriminately.
3039 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3040 int keybits, hammer2_blockref_t *base, int count)
3042 hammer2_chain_t *chain;
3043 hammer2_blockref_t *bref;
3045 hammer2_key_t key_beg;
3046 hammer2_key_t key_end;
3047 hammer2_key_t key_next;
3051 int maxloops = 300000;
3059 * Calculate the range of keys in the array being careful to skip
3060 * slots which are overridden with a deletion.
3063 key_end = HAMMER2_KEY_MAX;
3065 spin_lock(&parent->core.cst.spin);
3068 if (--maxloops == 0) {
3069 panic("indkey_freemap shit %p %p:%d\n",
3070 parent, base, count);
3072 chain = hammer2_combined_find(parent, base, count,
3073 &cache_index, &key_next,
3084 * Skip deleted chains.
3086 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3087 if (key_next == 0 || key_next > key_end)
3094 * Use the full live (not deleted) element for the scan
3095 * iteration. HAMMER2 does not allow partial replacements.
3097 * XXX should be built into hammer2_combined_find().
3099 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3101 if (keybits > bref->keybits) {
3103 keybits = bref->keybits;
3104 } else if (keybits == bref->keybits && bref->key < key) {
3111 spin_unlock(&parent->core.cst.spin);
3114 * Return the keybits for a higher-level FREEMAP_NODE covering
3118 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3119 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3121 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3122 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3124 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3125 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3127 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3128 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3130 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3131 panic("hammer2_chain_indkey_freemap: level too high");
3134 panic("hammer2_chain_indkey_freemap: bad radix");
3143 * Calculate the keybits and highside/lowside of the indirect block the
3144 * caller is creating.
3147 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3148 int keybits, hammer2_blockref_t *base, int count)
3150 hammer2_blockref_t *bref;
3151 hammer2_chain_t *chain;
3152 hammer2_key_t key_beg;
3153 hammer2_key_t key_end;
3154 hammer2_key_t key_next;
3160 int maxloops = 300000;
3167 * Calculate the range of keys in the array being careful to skip
3168 * slots which are overridden with a deletion. Once the scan
3169 * completes we will cut the key range in half and shift half the
3170 * range into the new indirect block.
3173 key_end = HAMMER2_KEY_MAX;
3175 spin_lock(&parent->core.cst.spin);
3178 if (--maxloops == 0) {
3179 panic("indkey_freemap shit %p %p:%d\n",
3180 parent, base, count);
3182 chain = hammer2_combined_find(parent, base, count,
3183 &cache_index, &key_next,
3194 * NOTE: No need to check DUPLICATED here because we do
3195 * not release the spinlock.
3197 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3198 if (key_next == 0 || key_next > key_end)
3205 * Use the full live (not deleted) element for the scan
3206 * iteration. HAMMER2 does not allow partial replacements.
3208 * XXX should be built into hammer2_combined_find().
3210 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3213 * Expand our calculated key range (key, keybits) to fit
3214 * the scanned key. nkeybits represents the full range
3215 * that we will later cut in half (two halves @ nkeybits - 1).
3218 if (nkeybits < bref->keybits) {
3219 if (bref->keybits > 64) {
3220 kprintf("bad bref chain %p bref %p\n",
3224 nkeybits = bref->keybits;
3226 while (nkeybits < 64 &&
3227 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3228 (key ^ bref->key)) != 0) {
3233 * If the new key range is larger we have to determine
3234 * which side of the new key range the existing keys fall
3235 * under by checking the high bit, then collapsing the
3236 * locount into the hicount or vise-versa.
3238 if (keybits != nkeybits) {
3239 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3250 * The newly scanned key will be in the lower half or the
3251 * upper half of the (new) key range.
3253 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3262 spin_unlock(&parent->core.cst.spin);
3263 bref = NULL; /* now invalid (safety) */
3266 * Adjust keybits to represent half of the full range calculated
3267 * above (radix 63 max)
3272 * Select whichever half contains the most elements. Theoretically
3273 * we can select either side as long as it contains at least one
3274 * element (in order to ensure that a free slot is present to hold
3275 * the indirect block).
3277 if (hammer2_indirect_optimize) {
3279 * Insert node for least number of keys, this will arrange
3280 * the first few blocks of a large file or the first few
3281 * inodes in a directory with fewer indirect blocks when
3284 if (hicount < locount && hicount != 0)
3285 key |= (hammer2_key_t)1 << keybits;
3287 key &= ~(hammer2_key_t)1 << keybits;
3290 * Insert node for most number of keys, best for heavily
3293 if (hicount > locount)
3294 key |= (hammer2_key_t)1 << keybits;
3296 key &= ~(hammer2_key_t)1 << keybits;
3304 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3307 * Both parent and chain must be locked exclusively.
3309 * This function will modify the parent if the blockref requires removal
3310 * from the parent's block table.
3312 * This function is NOT recursive. Any entity already pushed into the
3313 * chain (such as an inode) may still need visibility into its contents,
3314 * as well as the ability to read and modify the contents. For example,
3315 * for an unlinked file which is still open.
3318 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3319 hammer2_chain_t *chain, int flags)
3321 KKASSERT(ccms_thread_lock_owned(&chain->core.cst));
3324 * Nothing to do if already marked.
3326 * We need the spinlock on the core whos RBTREE contains chain
3327 * to protect against races.
3329 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3330 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3331 chain->parent == parent);
3332 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3335 if (flags & HAMMER2_DELETE_PERMANENT) {
3336 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3337 hammer2_flush(trans, chain);
3339 /* XXX might not be needed */
3340 hammer2_chain_setflush(trans, chain);
3345 * Returns the index of the nearest element in the blockref array >= elm.
3346 * Returns (count) if no element could be found.
3348 * Sets *key_nextp to the next key for loop purposes but does not modify
3349 * it if the next key would be higher than the current value of *key_nextp.
3350 * Note that *key_nexp can overflow to 0, which should be tested by the
3353 * (*cache_indexp) is a heuristic and can be any value without effecting
3356 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3357 * held through the operation.
3360 hammer2_base_find(hammer2_chain_t *parent,
3361 hammer2_blockref_t *base, int count,
3362 int *cache_indexp, hammer2_key_t *key_nextp,
3363 hammer2_key_t key_beg, hammer2_key_t key_end)
3365 hammer2_blockref_t *scan;
3366 hammer2_key_t scan_end;
3371 * Require the live chain's already have their core's counted
3372 * so we can optimize operations.
3374 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3379 if (count == 0 || base == NULL)
3383 * Sequential optimization using *cache_indexp. This is the most
3386 * We can avoid trailing empty entries on live chains, otherwise
3387 * we might have to check the whole block array.
3391 limit = parent->core.live_zero;
3396 KKASSERT(i < count);
3402 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3409 * Search forwards, stop when we find a scan element which
3410 * encloses the key or until we know that there are no further
3414 if (scan->type != 0) {
3415 scan_end = scan->key +
3416 ((hammer2_key_t)1 << scan->keybits) - 1;
3417 if (scan->key > key_beg || scan_end >= key_beg)
3430 scan_end = scan->key +
3431 ((hammer2_key_t)1 << scan->keybits);
3432 if (scan_end && (*key_nextp > scan_end ||
3434 *key_nextp = scan_end;
3442 * Do a combined search and return the next match either from the blockref
3443 * array or from the in-memory chain. Sets *bresp to the returned bref in
3444 * both cases, or sets it to NULL if the search exhausted. Only returns
3445 * a non-NULL chain if the search matched from the in-memory chain.
3447 * When no in-memory chain has been found and a non-NULL bref is returned
3451 * The returned chain is not locked or referenced. Use the returned bref
3452 * to determine if the search exhausted or not. Iterate if the base find
3453 * is chosen but matches a deleted chain.
3455 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3456 * held through the operation.
3458 static hammer2_chain_t *
3459 hammer2_combined_find(hammer2_chain_t *parent,
3460 hammer2_blockref_t *base, int count,
3461 int *cache_indexp, hammer2_key_t *key_nextp,
3462 hammer2_key_t key_beg, hammer2_key_t key_end,
3463 hammer2_blockref_t **bresp)
3465 hammer2_blockref_t *bref;
3466 hammer2_chain_t *chain;
3470 * Lookup in block array and in rbtree.
3472 *key_nextp = key_end + 1;
3473 i = hammer2_base_find(parent, base, count, cache_indexp,
3474 key_nextp, key_beg, key_end);
3475 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3480 if (i == count && chain == NULL) {
3486 * Only chain matched.
3489 bref = &chain->bref;
3494 * Only blockref matched.
3496 if (chain == NULL) {
3502 * Both in-memory and blockref matched, select the nearer element.
3504 * If both are flush with the left-hand side or both are the
3505 * same distance away, select the chain. In this situation the
3506 * chain must have been loaded from the matching blockmap.
3508 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3509 chain->bref.key == base[i].key) {
3510 KKASSERT(chain->bref.key == base[i].key);
3511 bref = &chain->bref;
3516 * Select the nearer key
3518 if (chain->bref.key < base[i].key) {
3519 bref = &chain->bref;
3526 * If the bref is out of bounds we've exhausted our search.
3529 if (bref->key > key_end) {
3539 * Locate the specified block array element and delete it. The element
3542 * The spin lock on the related chain must be held.
3544 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3545 * need to be adjusted when we commit the media change.
3548 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3549 hammer2_blockref_t *base, int count,
3550 int *cache_indexp, hammer2_chain_t *chain)
3552 hammer2_blockref_t *elm = &chain->bref;
3553 hammer2_key_t key_next;
3557 * Delete element. Expect the element to exist.
3559 * XXX see caller, flush code not yet sophisticated enough to prevent
3560 * re-flushed in some cases.
3562 key_next = 0; /* max range */
3563 i = hammer2_base_find(parent, base, count, cache_indexp,
3564 &key_next, elm->key, elm->key);
3565 if (i == count || base[i].type == 0 ||
3566 base[i].key != elm->key ||
3567 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3568 base[i].keybits != elm->keybits)) {
3569 spin_unlock(&parent->core.cst.spin);
3570 panic("delete base %p element not found at %d/%d elm %p\n",
3571 base, i, count, elm);
3574 bzero(&base[i], sizeof(*base));
3577 * We can only optimize parent->core.live_zero for live chains.
3579 if (parent->core.live_zero == i + 1) {
3580 while (--i >= 0 && base[i].type == 0)
3582 parent->core.live_zero = i + 1;
3586 * Clear appropriate blockmap flags in chain.
3588 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3589 HAMMER2_CHAIN_BMAPUPD);
3593 * Insert the specified element. The block array must not already have the
3594 * element and must have space available for the insertion.
3596 * The spin lock on the related chain must be held.
3598 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3599 * need to be adjusted when we commit the media change.
3602 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3603 hammer2_blockref_t *base, int count,
3604 int *cache_indexp, hammer2_chain_t *chain)
3606 hammer2_blockref_t *elm = &chain->bref;
3607 hammer2_key_t key_next;
3616 * Insert new element. Expect the element to not already exist
3617 * unless we are replacing it.
3619 * XXX see caller, flush code not yet sophisticated enough to prevent
3620 * re-flushed in some cases.
3622 key_next = 0; /* max range */
3623 i = hammer2_base_find(parent, base, count, cache_indexp,
3624 &key_next, elm->key, elm->key);
3627 * Shortcut fill optimization, typical ordered insertion(s) may not
3630 KKASSERT(i >= 0 && i <= count);
3633 * Set appropriate blockmap flags in chain.
3635 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3638 * We can only optimize parent->core.live_zero for live chains.
3640 if (i == count && parent->core.live_zero < count) {
3641 i = parent->core.live_zero++;
3646 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3647 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3648 spin_unlock(&parent->core.cst.spin);
3649 panic("insert base %p overlapping elements at %d elm %p\n",
3654 * Try to find an empty slot before or after.
3658 while (j > 0 || k < count) {
3660 if (j >= 0 && base[j].type == 0) {
3664 bcopy(&base[j+1], &base[j],
3665 (i - j - 1) * sizeof(*base));
3671 if (k < count && base[k].type == 0) {
3672 bcopy(&base[i], &base[i+1],
3673 (k - i) * sizeof(hammer2_blockref_t));
3677 * We can only update parent->core.live_zero for live
3680 if (parent->core.live_zero <= k)
3681 parent->core.live_zero = k + 1;
3686 panic("hammer2_base_insert: no room!");
3693 for (l = 0; l < count; ++l) {
3695 key_next = base[l].key +
3696 ((hammer2_key_t)1 << base[l].keybits) - 1;
3700 while (++l < count) {
3702 if (base[l].key <= key_next)
3703 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3704 key_next = base[l].key +
3705 ((hammer2_key_t)1 << base[l].keybits) - 1;
3715 * Sort the blockref array for the chain. Used by the flush code to
3716 * sort the blockref[] array.
3718 * The chain must be exclusively locked AND spin-locked.
3720 typedef hammer2_blockref_t *hammer2_blockref_p;
3724 hammer2_base_sort_callback(const void *v1, const void *v2)
3726 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3727 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3730 * Make sure empty elements are placed at the end of the array
3732 if (bref1->type == 0) {
3733 if (bref2->type == 0)
3736 } else if (bref2->type == 0) {
3743 if (bref1->key < bref2->key)
3745 if (bref1->key > bref2->key)
3751 hammer2_base_sort(hammer2_chain_t *chain)
3753 hammer2_blockref_t *base;
3756 switch(chain->bref.type) {
3757 case HAMMER2_BREF_TYPE_INODE:
3759 * Special shortcut for embedded data returns the inode
3760 * itself. Callers must detect this condition and access
3761 * the embedded data (the strategy code does this for us).
3763 * This is only applicable to regular files and softlinks.
3765 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3767 base = &chain->data->ipdata.u.blockset.blockref[0];
3768 count = HAMMER2_SET_COUNT;
3770 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3771 case HAMMER2_BREF_TYPE_INDIRECT:
3773 * Optimize indirect blocks in the INITIAL state to avoid
3776 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3777 base = &chain->data->npdata[0];
3778 count = chain->bytes / sizeof(hammer2_blockref_t);
3780 case HAMMER2_BREF_TYPE_VOLUME:
3781 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3782 count = HAMMER2_SET_COUNT;
3784 case HAMMER2_BREF_TYPE_FREEMAP:
3785 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3786 count = HAMMER2_SET_COUNT;
3789 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3791 base = NULL; /* safety */
3792 count = 0; /* safety */
3794 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3800 * Chain memory management
3803 hammer2_chain_wait(hammer2_chain_t *chain)
3805 tsleep(chain, 0, "chnflw", 1);
3808 const hammer2_media_data_t *
3809 hammer2_chain_rdata(hammer2_chain_t *chain)
3811 KKASSERT(chain->data != NULL);
3812 return (chain->data);
3815 hammer2_media_data_t *
3816 hammer2_chain_wdata(hammer2_chain_t *chain)
3818 KKASSERT(chain->data != NULL);
3819 return (chain->data);
3823 * Set the check data for a chain. This can be a heavy-weight operation
3824 * and typically only runs on-flush. For file data check data is calculated
3825 * when the logical buffers are flushed.
3828 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3830 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3832 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3833 case HAMMER2_CHECK_NONE:
3835 case HAMMER2_CHECK_DISABLED:
3837 case HAMMER2_CHECK_ISCSI32:
3838 chain->bref.check.iscsi32.value =
3839 hammer2_icrc32(bdata, chain->bytes);
3841 case HAMMER2_CHECK_CRC64:
3842 chain->bref.check.crc64.value = 0;
3845 case HAMMER2_CHECK_SHA192:
3847 SHA256_CTX hash_ctx;
3849 uint8_t digest[SHA256_DIGEST_LENGTH];
3850 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3853 SHA256_Init(&hash_ctx);
3854 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3855 SHA256_Final(u.digest, &hash_ctx);
3856 u.digest64[2] ^= u.digest64[3];
3858 chain->bref.check.sha192.data,
3859 sizeof(chain->bref.check.sha192.data));
3862 case HAMMER2_CHECK_FREEMAP:
3863 chain->bref.check.freemap.icrc32 =
3864 hammer2_icrc32(bdata, chain->bytes);
3867 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3868 chain->bref.methods);
3874 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3878 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3881 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3882 case HAMMER2_CHECK_NONE:
3885 case HAMMER2_CHECK_DISABLED:
3888 case HAMMER2_CHECK_ISCSI32:
3889 r = (chain->bref.check.iscsi32.value ==
3890 hammer2_icrc32(bdata, chain->bytes));
3892 case HAMMER2_CHECK_CRC64:
3893 r = (chain->bref.check.crc64.value == 0);
3896 case HAMMER2_CHECK_SHA192:
3898 SHA256_CTX hash_ctx;
3900 uint8_t digest[SHA256_DIGEST_LENGTH];
3901 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3904 SHA256_Init(&hash_ctx);
3905 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3906 SHA256_Final(u.digest, &hash_ctx);
3907 u.digest64[2] ^= u.digest64[3];
3909 chain->bref.check.sha192.data,
3910 sizeof(chain->bref.check.sha192.data)) == 0) {
3917 case HAMMER2_CHECK_FREEMAP:
3918 r = (chain->bref.check.freemap.icrc32 ==
3919 hammer2_icrc32(bdata, chain->bytes));
3921 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3922 chain->bref.check.freemap.icrc32,
3923 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3925 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3926 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3931 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3932 chain->bref.methods);