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 hammer2_spin_sh(&chain->core.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 hammer2_spin_sh(&parent->core.spin);
146 hammer2_spin_unsh(&chain->core.spin);
149 hammer2_spin_unsh(&chain->core.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 hammer2_mtx_init(&core->lock, "h2chain");
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 hammer2_spin_ex(&parent->core.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 hammer2_spin_unex(&parent->core.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 core 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 hammer2_spin_ex(&chain->core.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 hammer2_spin_unex(&chain->core.spin);
392 chain = NULL; /* success */
394 hammer2_spin_unex(&chain->core.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 hammer2_spin_ex(&parent->core.spin);
419 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
420 /* 1->0 transition failed */
421 hammer2_spin_unex(&parent->core.spin);
422 hammer2_spin_unex(&chain->core.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 hammer2_spin_unex(&parent->core.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 hammer2_spin_unex(&chain->core.spin);
460 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
461 chain->core.chain_count == 0);
464 * All spin locks are gone, finish freeing stuff.
466 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
467 HAMMER2_CHAIN_MODIFIED)) == 0);
468 hammer2_chain_drop_data(chain, 1);
470 KKASSERT(chain->dio == NULL);
473 * Once chain resources are gone we can use the now dead chain
474 * structure to placehold what might otherwise require a recursive
475 * drop, because we have potentially two things to drop and can only
476 * return one directly.
478 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
479 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
481 kfree(chain, hmp->mchain);
485 * Possible chaining loop when parent re-drop needed.
491 * On either last lock release or last drop
494 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
496 /*hammer2_mount_t *hmp = chain->hmp;*/
498 switch(chain->bref.type) {
499 case HAMMER2_BREF_TYPE_VOLUME:
500 case HAMMER2_BREF_TYPE_FREEMAP:
505 KKASSERT(chain->data == NULL);
511 * Ref and lock a chain element, acquiring its data with I/O if necessary,
512 * and specify how you would like the data to be resolved.
514 * Returns 0 on success or an error code if the data could not be acquired.
515 * The chain element is locked on return regardless of whether an error
518 * The lock is allowed to recurse, multiple locking ops will aggregate
519 * the requested resolve types. Once data is assigned it will not be
520 * removed until the last unlock.
522 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
523 * (typically used to avoid device/logical buffer
526 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
527 * the INITIAL-create state (indirect blocks only).
529 * Do not resolve data elements for DATA chains.
530 * (typically used to avoid device/logical buffer
533 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
535 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
536 * it will be locked exclusive.
538 * NOTE: Embedded elements (volume header, inodes) are always resolved
541 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
542 * element will instantiate and zero its buffer, and flush it on
545 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
546 * so as not to instantiate a device buffer, which could alias against
547 * a logical file buffer. However, if ALWAYS is specified the
548 * device buffer will be instantiated anyway.
550 * WARNING! If data must be fetched a shared lock will temporarily be
551 * upgraded to exclusive. However, a deadlock can occur if
552 * the caller owns more than one shared lock.
555 hammer2_chain_lock(hammer2_chain_t *chain, int how)
557 hammer2_mount_t *hmp;
558 hammer2_blockref_t *bref;
559 hammer2_mtx_state_t ostate;
564 * Ref and lock the element. Recursive locks are allowed.
566 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
567 hammer2_chain_ref(chain);
568 atomic_add_int(&chain->lockcnt, 1);
571 KKASSERT(hmp != NULL);
574 * Get the appropriate lock.
576 if (how & HAMMER2_RESOLVE_SHARED)
577 hammer2_mtx_sh(&chain->core.lock);
579 hammer2_mtx_ex(&chain->core.lock);
582 * If we already have a valid data pointer no further action is
589 * Do we have to resolve the data?
591 switch(how & HAMMER2_RESOLVE_MASK) {
592 case HAMMER2_RESOLVE_NEVER:
594 case HAMMER2_RESOLVE_MAYBE:
595 if (chain->flags & HAMMER2_CHAIN_INITIAL)
597 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
600 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
602 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
606 case HAMMER2_RESOLVE_ALWAYS:
611 * Upgrade to an exclusive lock so we can safely manipulate the
612 * buffer cache. If another thread got to it before us we
615 ostate = hammer2_mtx_upgrade(&chain->core.lock);
617 hammer2_mtx_downgrade(&chain->core.lock, ostate);
622 * We must resolve to a device buffer, either by issuing I/O or
623 * by creating a zero-fill element. We do not mark the buffer
624 * dirty when creating a zero-fill element (the hammer2_chain_modify()
625 * API must still be used to do that).
627 * The device buffer is variable-sized in powers of 2 down
628 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
629 * chunk always contains buffers of the same size. (XXX)
631 * The minimum physical IO size may be larger than the variable
637 * The getblk() optimization can only be used on newly created
638 * elements if the physical block size matches the request.
640 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
641 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
644 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
646 hammer2_adjreadcounter(&chain->bref, chain->bytes);
650 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
651 (intmax_t)bref->data_off, error);
652 hammer2_io_bqrelse(&chain->dio);
653 hammer2_mtx_downgrade(&chain->core.lock, ostate);
659 * No need for this, always require that hammer2_chain_modify()
660 * be called before any modifying operations, which ensures that
661 * the underlying dio is dirty.
663 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
664 !hammer2_io_isdirty(chain->dio)) {
665 hammer2_io_setdirty(chain->dio);
670 * Clear INITIAL. In this case we used io_new() and the buffer has
671 * been zero'd and marked dirty.
673 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
674 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
675 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
676 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
677 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
679 * check data not currently synchronized due to
680 * modification. XXX assumes data stays in the buffer
681 * cache, which might not be true (need biodep on flush
682 * to calculate crc? or simple crc?).
685 if (hammer2_chain_testcheck(chain, bdata) == 0) {
686 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL %08x (flags=%08x)\n",
688 chain->bref.data_off,
691 hammer2_icrc32(bdata, chain->bytes),
697 * Setup the data pointer, either pointing it to an embedded data
698 * structure and copying the data from the buffer, or pointing it
701 * The buffer is not retained when copying to an embedded data
702 * structure in order to avoid potential deadlocks or recursions
703 * on the same physical buffer.
705 switch (bref->type) {
706 case HAMMER2_BREF_TYPE_VOLUME:
707 case HAMMER2_BREF_TYPE_FREEMAP:
709 * Copy data from bp to embedded buffer
711 panic("hammer2_chain_lock: called on unresolved volume header");
713 case HAMMER2_BREF_TYPE_INODE:
714 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
715 case HAMMER2_BREF_TYPE_INDIRECT:
716 case HAMMER2_BREF_TYPE_DATA:
717 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
720 * Point data at the device buffer and leave dio intact.
722 chain->data = (void *)bdata;
725 hammer2_mtx_downgrade(&chain->core.lock, ostate);
730 * Unlock and deref a chain element.
732 * On the last lock release any non-embedded data (chain->dio) will be
736 hammer2_chain_unlock(hammer2_chain_t *chain)
738 hammer2_mtx_state_t ostate;
743 * If multiple locks are present (or being attempted) on this
744 * particular chain we can just unlock, drop refs, and return.
746 * Otherwise fall-through on the 1->0 transition.
749 lockcnt = chain->lockcnt;
750 KKASSERT(lockcnt > 0);
753 if (atomic_cmpset_int(&chain->lockcnt,
754 lockcnt, lockcnt - 1)) {
755 hammer2_mtx_unlock(&chain->core.lock);
756 hammer2_chain_drop(chain);
760 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
767 * On the 1->0 transition we upgrade the core lock (if necessary)
768 * to exclusive for terminal processing. If after upgrading we find
769 * that lockcnt is non-zero, another thread is racing us and will
770 * handle the unload for us later on, so just cleanup and return
771 * leaving the data/io intact
773 * Otherwise if lockcnt is still 0 it is possible for it to become
774 * non-zero and race, but since we hold the core->lock exclusively
775 * all that will happen is that the chain will be reloaded after we
778 ostate = hammer2_mtx_upgrade(&chain->core.lock);
779 if (chain->lockcnt) {
780 hammer2_mtx_unlock(&chain->core.lock);
781 hammer2_chain_drop(chain);
786 * Shortcut the case if the data is embedded or not resolved.
788 * Do NOT NULL out chain->data (e.g. inode data), it might be
791 if (chain->dio == NULL) {
792 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
793 hammer2_chain_drop_data(chain, 0);
794 hammer2_mtx_unlock(&chain->core.lock);
795 hammer2_chain_drop(chain);
802 if (hammer2_io_isdirty(chain->dio) == 0) {
804 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
805 switch(chain->bref.type) {
806 case HAMMER2_BREF_TYPE_DATA:
807 counterp = &hammer2_ioa_file_write;
809 case HAMMER2_BREF_TYPE_INODE:
810 counterp = &hammer2_ioa_meta_write;
812 case HAMMER2_BREF_TYPE_INDIRECT:
813 counterp = &hammer2_ioa_indr_write;
815 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
816 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
817 counterp = &hammer2_ioa_fmap_write;
820 counterp = &hammer2_ioa_volu_write;
823 *counterp += chain->bytes;
825 switch(chain->bref.type) {
826 case HAMMER2_BREF_TYPE_DATA:
827 counterp = &hammer2_iod_file_write;
829 case HAMMER2_BREF_TYPE_INODE:
830 counterp = &hammer2_iod_meta_write;
832 case HAMMER2_BREF_TYPE_INDIRECT:
833 counterp = &hammer2_iod_indr_write;
835 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
836 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
837 counterp = &hammer2_iod_fmap_write;
840 counterp = &hammer2_iod_volu_write;
843 *counterp += chain->bytes;
849 * If a device buffer was used for data be sure to destroy the
850 * buffer when we are done to avoid aliases (XXX what about the
851 * underlying VM pages?).
853 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
856 * NOTE: The isdirty check tracks whether we have to bdwrite() the
857 * buffer or not. The buffer might already be dirty. The
858 * flag is re-set when chain_modify() is called, even if
859 * MODIFIED is already set, allowing the OS to retire the
860 * buffer independent of a hammer2 flush.
863 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
864 hammer2_io_isdirty(chain->dio)) {
865 hammer2_io_bawrite(&chain->dio);
867 hammer2_io_bqrelse(&chain->dio);
869 hammer2_mtx_unlock(&chain->core.lock);
870 hammer2_chain_drop(chain);
874 * This counts the number of live blockrefs in a block array and
875 * also calculates the point at which all remaining blockrefs are empty.
876 * This routine can only be called on a live chain (DUPLICATED flag not set).
878 * NOTE: Flag is not set until after the count is complete, allowing
879 * callers to test the flag without holding the spinlock.
881 * NOTE: If base is NULL the related chain is still in the INITIAL
882 * state and there are no blockrefs to count.
884 * NOTE: live_count may already have some counts accumulated due to
885 * creation and deletion and could even be initially negative.
888 hammer2_chain_countbrefs(hammer2_chain_t *chain,
889 hammer2_blockref_t *base, int count)
891 hammer2_spin_ex(&chain->core.spin);
892 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
894 while (--count >= 0) {
895 if (base[count].type)
898 chain->core.live_zero = count + 1;
900 if (base[count].type)
901 atomic_add_int(&chain->core.live_count,
906 chain->core.live_zero = 0;
908 /* else do not modify live_count */
909 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
911 hammer2_spin_unex(&chain->core.spin);
915 * Resize the chain's physical storage allocation in-place. This function does
916 * not adjust the data pointer and must be followed by (typically) a
917 * hammer2_chain_modify() call to copy any old data over and adjust the
920 * Chains can be resized smaller without reallocating the storage. Resizing
921 * larger will reallocate the storage. Excess or prior storage is reclaimed
922 * asynchronously at a later time.
924 * Must be passed an exclusively locked parent and chain.
926 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
927 * to avoid instantiating a device buffer that conflicts with the vnode data
928 * buffer. However, because H2 can compress or encrypt data, the chain may
929 * have a dio assigned to it in those situations, and they do not conflict.
931 * XXX return error if cannot resize.
934 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
935 hammer2_chain_t *parent, hammer2_chain_t *chain,
936 int nradix, int flags)
938 hammer2_mount_t *hmp;
945 * Only data and indirect blocks can be resized for now.
946 * (The volu root, inodes, and freemap elements use a fixed size).
948 KKASSERT(chain != &hmp->vchain);
949 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
950 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
953 * Nothing to do if the element is already the proper size
955 obytes = chain->bytes;
956 nbytes = 1U << nradix;
957 if (obytes == nbytes)
959 chain->data_count += (ssize_t)(nbytes - obytes);
962 * Make sure the old data is instantiated so we can copy it. If this
963 * is a data block, the device data may be superfluous since the data
964 * might be in a logical block, but compressed or encrypted data is
967 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
969 hammer2_chain_modify(trans, chain, 0);
972 * Relocate the block, even if making it smaller (because different
973 * block sizes may be in different regions).
975 * (data blocks only, we aren't copying the storage here).
977 hammer2_freemap_alloc(trans, chain, nbytes);
978 chain->bytes = nbytes;
979 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
982 * We don't want the followup chain_modify() to try to copy data
983 * from the old (wrong-sized) buffer. It won't know how much to
984 * copy. This case should only occur during writes when the
985 * originator already has the data to write in-hand.
988 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
989 hammer2_io_brelse(&chain->dio);
995 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
997 hammer2_blockref_t obref;
998 hammer2_mount_t *hmp;
1006 obref = chain->bref;
1009 * Data is not optional for freemap chains (we must always be sure
1010 * to copy the data on COW storage allocations).
1012 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1013 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1014 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1015 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1019 * Data must be resolved if already assigned unless explicitly
1020 * flagged otherwise.
1022 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1023 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1024 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1025 hammer2_chain_unlock(chain);
1029 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1030 * that the chain has been modified. Set UPDATE to ensure that
1031 * the blockref is updated in the parent.
1033 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1034 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1035 hammer2_chain_ref(chain);
1036 hammer2_pfs_memory_inc(chain->pmp);
1041 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1042 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1043 hammer2_chain_ref(chain);
1047 * The modification or re-modification requires an allocation and
1050 * We normally always allocate new storage here. If storage exists
1051 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1053 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1054 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1055 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1057 hammer2_freemap_alloc(trans, chain, chain->bytes);
1058 /* XXX failed allocation */
1063 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1064 * requires updating as well as to tell the delete code that the
1065 * chain's blockref might not exactly match (in terms of physical size
1066 * or block offset) the one in the parent's blocktable. The base key
1067 * of course will still match.
1069 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1070 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1073 * Short-cut data blocks which the caller does not need an actual
1074 * data reference to (aka OPTDATA), as long as the chain does not
1075 * already have a data pointer to the data. This generally means
1076 * that the modifications are being done via the logical buffer cache.
1077 * The INITIAL flag relates only to the device data buffer and thus
1078 * remains unchange in this situation.
1080 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1081 (flags & HAMMER2_MODIFY_OPTDATA) &&
1082 chain->data == NULL) {
1087 * Clearing the INITIAL flag (for indirect blocks) indicates that
1088 * we've processed the uninitialized storage allocation.
1090 * If this flag is already clear we are likely in a copy-on-write
1091 * situation but we have to be sure NOT to bzero the storage if
1092 * no data is present.
1094 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1095 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1102 * Instantiate data buffer and possibly execute COW operation
1104 switch(chain->bref.type) {
1105 case HAMMER2_BREF_TYPE_VOLUME:
1106 case HAMMER2_BREF_TYPE_FREEMAP:
1108 * The data is embedded, no copy-on-write operation is
1111 KKASSERT(chain->dio == NULL);
1113 case HAMMER2_BREF_TYPE_INODE:
1114 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1115 case HAMMER2_BREF_TYPE_DATA:
1116 case HAMMER2_BREF_TYPE_INDIRECT:
1117 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1119 * Perform the copy-on-write operation
1121 * zero-fill or copy-on-write depending on whether
1122 * chain->data exists or not and set the dirty state for
1123 * the new buffer. hammer2_io_new() will handle the
1126 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1129 error = hammer2_io_new(hmp, chain->bref.data_off,
1130 chain->bytes, &dio);
1132 error = hammer2_io_bread(hmp, chain->bref.data_off,
1133 chain->bytes, &dio);
1135 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1136 KKASSERT(error == 0);
1138 bdata = hammer2_io_data(dio, chain->bref.data_off);
1141 KKASSERT(chain->dio != NULL);
1142 if (chain->data != (void *)bdata) {
1143 bcopy(chain->data, bdata, chain->bytes);
1145 } else if (wasinitial == 0) {
1147 * We have a problem. We were asked to COW but
1148 * we don't have any data to COW with!
1150 panic("hammer2_chain_modify: having a COW %p\n",
1155 * Retire the old buffer, replace with the new. Dirty or
1156 * redirty the new buffer.
1158 * WARNING! The system buffer cache may have already flushed
1159 * the buffer, so we must be sure to [re]dirty it
1160 * for further modification.
1163 hammer2_io_brelse(&chain->dio);
1164 chain->data = (void *)bdata;
1166 hammer2_io_setdirty(dio); /* modified by bcopy above */
1169 panic("hammer2_chain_modify: illegal non-embedded type %d",
1176 * setflush on parent indicating that the parent must recurse down
1177 * to us. Do not call on chain itself which might already have it
1181 hammer2_chain_setflush(trans, chain->parent);
1185 * Adjust the freemap bitmap to indicate that the related blocks
1186 * MIGHT be freeable. Bulkfree must still determine that the blocks
1187 * are actually freeable.
1189 * We no longer do this in the normal filesystem operations path
1190 * as it interferes with the bulkfree algorithm.
1192 if (obref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
1193 obref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
1194 (obref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1195 hammer2_freemap_adjust(trans, hmp,
1196 &obref, HAMMER2_FREEMAP_DOMAYFREE);
1202 * Volume header data locks
1205 hammer2_voldata_lock(hammer2_mount_t *hmp)
1207 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1211 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1213 lockmgr(&hmp->vollk, LK_RELEASE);
1217 hammer2_voldata_modify(hammer2_mount_t *hmp)
1219 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1220 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1221 hammer2_chain_ref(&hmp->vchain);
1222 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1227 * This function returns the chain at the nearest key within the specified
1228 * range. The returned chain will be referenced but not locked.
1230 * This function will recurse through chain->rbtree as necessary and will
1231 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1232 * the iteration value is less than the current value of *key_nextp.
1234 * The caller should use (*key_nextp) to calculate the actual range of
1235 * the returned element, which will be (key_beg to *key_nextp - 1), because
1236 * there might be another element which is superior to the returned element
1239 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1240 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1241 * it will wind up being (key_end + 1).
1243 * WARNING! Must be called with child's spinlock held. Spinlock remains
1244 * held through the operation.
1246 struct hammer2_chain_find_info {
1247 hammer2_chain_t *best;
1248 hammer2_key_t key_beg;
1249 hammer2_key_t key_end;
1250 hammer2_key_t key_next;
1253 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1254 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1258 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1259 hammer2_key_t key_beg, hammer2_key_t key_end)
1261 struct hammer2_chain_find_info info;
1264 info.key_beg = key_beg;
1265 info.key_end = key_end;
1266 info.key_next = *key_nextp;
1268 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1269 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1271 *key_nextp = info.key_next;
1273 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1274 parent, key_beg, key_end, *key_nextp);
1282 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1284 struct hammer2_chain_find_info *info = data;
1285 hammer2_key_t child_beg;
1286 hammer2_key_t child_end;
1288 child_beg = child->bref.key;
1289 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1291 if (child_end < info->key_beg)
1293 if (child_beg > info->key_end)
1300 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1302 struct hammer2_chain_find_info *info = data;
1303 hammer2_chain_t *best;
1304 hammer2_key_t child_end;
1307 * WARNING! Do not discard DUPLICATED chains, it is possible that
1308 * we are catching an insertion half-way done. If a
1309 * duplicated chain turns out to be the best choice the
1310 * caller will re-check its flags after locking it.
1312 * WARNING! Layerq is scanned forwards, exact matches should keep
1313 * the existing info->best.
1315 if ((best = info->best) == NULL) {
1317 * No previous best. Assign best
1320 } else if (best->bref.key <= info->key_beg &&
1321 child->bref.key <= info->key_beg) {
1326 /*info->best = child;*/
1327 } else if (child->bref.key < best->bref.key) {
1329 * Child has a nearer key and best is not flush with key_beg.
1330 * Set best to child. Truncate key_next to the old best key.
1333 if (info->key_next > best->bref.key || info->key_next == 0)
1334 info->key_next = best->bref.key;
1335 } else if (child->bref.key == best->bref.key) {
1337 * If our current best is flush with the child then this
1338 * is an illegal overlap.
1340 * key_next will automatically be limited to the smaller of
1341 * the two end-points.
1347 * Keep the current best but truncate key_next to the child's
1350 * key_next will also automatically be limited to the smaller
1351 * of the two end-points (probably not necessary for this case
1352 * but we do it anyway).
1354 if (info->key_next > child->bref.key || info->key_next == 0)
1355 info->key_next = child->bref.key;
1359 * Always truncate key_next based on child's end-of-range.
1361 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1362 if (child_end && (info->key_next > child_end || info->key_next == 0))
1363 info->key_next = child_end;
1369 * Retrieve the specified chain from a media blockref, creating the
1370 * in-memory chain structure which reflects it.
1372 * To handle insertion races pass the INSERT_RACE flag along with the
1373 * generation number of the core. NULL will be returned if the generation
1374 * number changes before we have a chance to insert the chain. Insert
1375 * races can occur because the parent might be held shared.
1377 * Caller must hold the parent locked shared or exclusive since we may
1378 * need the parent's bref array to find our block.
1380 * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1384 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1385 hammer2_blockref_t *bref)
1387 hammer2_mount_t *hmp = parent->hmp;
1388 hammer2_chain_t *chain;
1392 * Allocate a chain structure representing the existing media
1393 * entry. Resulting chain has one ref and is not locked.
1395 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1396 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1398 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1399 hammer2_chain_core_alloc(NULL, chain);
1400 /* ref'd chain returned */
1403 * Flag that the chain is in the parent's blockmap so delete/flush
1404 * knows what to do with it.
1406 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1409 * Link the chain into its parent. A spinlock is required to safely
1410 * access the RBTREE, and it is possible to collide with another
1411 * hammer2_chain_get() operation because the caller might only hold
1412 * a shared lock on the parent.
1414 KKASSERT(parent->refs > 0);
1415 error = hammer2_chain_insert(parent, chain,
1416 HAMMER2_CHAIN_INSERT_SPIN |
1417 HAMMER2_CHAIN_INSERT_RACE,
1420 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1421 kprintf("chain %p get race\n", chain);
1422 hammer2_chain_drop(chain);
1425 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1429 * Return our new chain referenced but not locked, or NULL if
1436 * Lookup initialization/completion API
1439 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1441 if (flags & HAMMER2_LOOKUP_SHARED) {
1442 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1443 HAMMER2_RESOLVE_SHARED);
1445 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1451 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1454 hammer2_chain_unlock(parent);
1459 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1461 hammer2_chain_t *oparent;
1462 hammer2_chain_t *nparent;
1465 * Be careful of order, oparent must be unlocked before nparent
1466 * is locked below to avoid a deadlock.
1469 hammer2_spin_ex(&oparent->core.spin);
1470 nparent = oparent->parent;
1471 hammer2_chain_ref(nparent);
1472 hammer2_spin_unex(&oparent->core.spin);
1474 hammer2_chain_unlock(oparent);
1478 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1485 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1486 * (*parentp) typically points to an inode but can also point to a related
1487 * indirect block and this function will recurse upwards and find the inode
1490 * (*parentp) must be exclusively locked and referenced and can be an inode
1491 * or an existing indirect block within the inode.
1493 * On return (*parentp) will be modified to point at the deepest parent chain
1494 * element encountered during the search, as a helper for an insertion or
1495 * deletion. The new (*parentp) will be locked and referenced and the old
1496 * will be unlocked and dereferenced (no change if they are both the same).
1498 * The matching chain will be returned exclusively locked. If NOLOCK is
1499 * requested the chain will be returned only referenced.
1501 * NULL is returned if no match was found, but (*parentp) will still
1502 * potentially be adjusted.
1504 * On return (*key_nextp) will point to an iterative value for key_beg.
1505 * (If NULL is returned (*key_nextp) is set to key_end).
1507 * This function will also recurse up the chain if the key is not within the
1508 * current parent's range. (*parentp) can never be set to NULL. An iteration
1509 * can simply allow (*parentp) to float inside the loop.
1511 * NOTE! chain->data is not always resolved. By default it will not be
1512 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1513 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1514 * BREF_TYPE_DATA as the device buffer can alias the logical file
1518 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1519 hammer2_key_t key_beg, hammer2_key_t key_end,
1520 int *cache_indexp, int flags, int *ddflagp)
1522 hammer2_mount_t *hmp;
1523 hammer2_chain_t *parent;
1524 hammer2_chain_t *chain;
1525 hammer2_blockref_t *base;
1526 hammer2_blockref_t *bref;
1527 hammer2_blockref_t bcopy;
1528 hammer2_key_t scan_beg;
1529 hammer2_key_t scan_end;
1531 int how_always = HAMMER2_RESOLVE_ALWAYS;
1532 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1535 int maxloops = 300000;
1538 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1539 how_maybe = how_always;
1540 how = HAMMER2_RESOLVE_ALWAYS;
1541 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1542 how = HAMMER2_RESOLVE_NEVER;
1544 how = HAMMER2_RESOLVE_MAYBE;
1546 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1547 how_maybe |= HAMMER2_RESOLVE_SHARED;
1548 how_always |= HAMMER2_RESOLVE_SHARED;
1549 how |= HAMMER2_RESOLVE_SHARED;
1553 * Recurse (*parentp) upward if necessary until the parent completely
1554 * encloses the key range or we hit the inode.
1556 * This function handles races against the flusher doing a delete-
1557 * duplicate above us and re-homes the parent to the duplicate in
1558 * that case, otherwise we'd wind up recursing down a stale chain.
1563 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1564 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1565 scan_beg = parent->bref.key;
1566 scan_end = scan_beg +
1567 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1568 if (key_beg >= scan_beg && key_end <= scan_end)
1570 parent = hammer2_chain_getparent(parentp, how_maybe);
1574 if (--maxloops == 0)
1575 panic("hammer2_chain_lookup: maxloops");
1577 * Locate the blockref array. Currently we do a fully associative
1578 * search through the array.
1580 switch(parent->bref.type) {
1581 case HAMMER2_BREF_TYPE_INODE:
1583 * Special shortcut for embedded data returns the inode
1584 * itself. Callers must detect this condition and access
1585 * the embedded data (the strategy code does this for us).
1587 * This is only applicable to regular files and softlinks.
1589 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1590 if (flags & HAMMER2_LOOKUP_NOLOCK)
1591 hammer2_chain_ref(parent);
1593 hammer2_chain_lock(parent, how_always);
1594 *key_nextp = key_end + 1;
1598 base = &parent->data->ipdata.u.blockset.blockref[0];
1599 count = HAMMER2_SET_COUNT;
1601 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1602 case HAMMER2_BREF_TYPE_INDIRECT:
1604 * Handle MATCHIND on the parent
1606 if (flags & HAMMER2_LOOKUP_MATCHIND) {
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 hammer2_chain_lock(chain, how_maybe);
1613 *key_nextp = scan_end + 1;
1618 * Optimize indirect blocks in the INITIAL state to avoid
1621 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1624 if (parent->data == NULL)
1625 panic("parent->data is NULL");
1626 base = &parent->data->npdata[0];
1628 count = parent->bytes / sizeof(hammer2_blockref_t);
1630 case HAMMER2_BREF_TYPE_VOLUME:
1631 base = &hmp->voldata.sroot_blockset.blockref[0];
1632 count = HAMMER2_SET_COUNT;
1634 case HAMMER2_BREF_TYPE_FREEMAP:
1635 base = &hmp->voldata.freemap_blockset.blockref[0];
1636 count = HAMMER2_SET_COUNT;
1639 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1641 base = NULL; /* safety */
1642 count = 0; /* safety */
1646 * Merged scan to find next candidate.
1648 * hammer2_base_*() functions require the parent->core.live_* fields
1649 * to be synchronized.
1651 * We need to hold the spinlock to access the block array and RB tree
1652 * and to interlock chain creation.
1654 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1655 hammer2_chain_countbrefs(parent, base, count);
1660 hammer2_spin_ex(&parent->core.spin);
1661 chain = hammer2_combined_find(parent, base, count,
1662 cache_indexp, key_nextp,
1665 generation = parent->core.generation;
1668 * Exhausted parent chain, iterate.
1671 hammer2_spin_unex(&parent->core.spin);
1672 if (key_beg == key_end) /* short cut single-key case */
1676 * Stop if we reached the end of the iteration.
1678 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1679 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1684 * Calculate next key, stop if we reached the end of the
1685 * iteration, otherwise go up one level and loop.
1687 key_beg = parent->bref.key +
1688 ((hammer2_key_t)1 << parent->bref.keybits);
1689 if (key_beg == 0 || key_beg > key_end)
1691 parent = hammer2_chain_getparent(parentp, how_maybe);
1696 * Selected from blockref or in-memory chain.
1698 if (chain == NULL) {
1700 hammer2_spin_unex(&parent->core.spin);
1701 chain = hammer2_chain_get(parent, generation,
1703 if (chain == NULL) {
1704 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1705 parent, key_beg, key_end);
1708 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1709 hammer2_chain_drop(chain);
1713 hammer2_chain_ref(chain);
1714 hammer2_spin_unex(&parent->core.spin);
1718 * chain is referenced but not locked. We must lock the chain
1719 * to obtain definitive DUPLICATED/DELETED state
1721 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1722 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1723 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1725 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1729 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1731 * NOTE: Chain's key range is not relevant as there might be
1732 * one-offs within the range that are not deleted.
1734 * NOTE: Lookups can race delete-duplicate because
1735 * delete-duplicate does not lock the parent's core
1736 * (they just use the spinlock on the core). We must
1737 * check for races by comparing the DUPLICATED flag before
1738 * releasing the spinlock with the flag after locking the
1741 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1742 hammer2_chain_unlock(chain);
1743 key_beg = *key_nextp;
1744 if (key_beg == 0 || key_beg > key_end)
1750 * If the chain element is an indirect block it becomes the new
1751 * parent and we loop on it. We must maintain our top-down locks
1752 * to prevent the flusher from interfering (i.e. doing a
1753 * delete-duplicate and leaving us recursing down a deleted chain).
1755 * The parent always has to be locked with at least RESOLVE_MAYBE
1756 * so we can access its data. It might need a fixup if the caller
1757 * passed incompatible flags. Be careful not to cause a deadlock
1758 * as a data-load requires an exclusive lock.
1760 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1761 * range is within the requested key range we return the indirect
1762 * block and do NOT loop. This is usually only used to acquire
1765 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1766 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1767 hammer2_chain_unlock(parent);
1768 *parentp = parent = chain;
1773 * All done, return the chain
1779 * After having issued a lookup we can iterate all matching keys.
1781 * If chain is non-NULL we continue the iteration from just after it's index.
1783 * If chain is NULL we assume the parent was exhausted and continue the
1784 * iteration at the next parent.
1786 * parent must be locked on entry and remains locked throughout. chain's
1787 * lock status must match flags. Chain is always at least referenced.
1789 * WARNING! The MATCHIND flag does not apply to this function.
1792 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1793 hammer2_key_t *key_nextp,
1794 hammer2_key_t key_beg, hammer2_key_t key_end,
1795 int *cache_indexp, int flags)
1797 hammer2_chain_t *parent;
1802 * Calculate locking flags for upward recursion.
1804 how_maybe = HAMMER2_RESOLVE_MAYBE;
1805 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1806 how_maybe |= HAMMER2_RESOLVE_SHARED;
1811 * Calculate the next index and recalculate the parent if necessary.
1814 key_beg = chain->bref.key +
1815 ((hammer2_key_t)1 << chain->bref.keybits);
1816 if (flags & HAMMER2_LOOKUP_NOLOCK)
1817 hammer2_chain_drop(chain);
1819 hammer2_chain_unlock(chain);
1822 * Any scan where the lookup returned degenerate data embedded
1823 * in the inode has an invalid index and must terminate.
1825 if (chain == parent)
1827 if (key_beg == 0 || key_beg > key_end)
1830 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1831 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1833 * We reached the end of the iteration.
1838 * Continue iteration with next parent unless the current
1839 * parent covers the range.
1841 key_beg = parent->bref.key +
1842 ((hammer2_key_t)1 << parent->bref.keybits);
1843 if (key_beg == 0 || key_beg > key_end)
1845 parent = hammer2_chain_getparent(parentp, how_maybe);
1851 return (hammer2_chain_lookup(parentp, key_nextp,
1853 cache_indexp, flags, &ddflag));
1857 * The raw scan function is similar to lookup/next but does not seek to a key.
1858 * Blockrefs are iterated via first_chain = (parent, NULL) and
1859 * next_chain = (parent, chain).
1861 * The passed-in parent must be locked and its data resolved. The returned
1862 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1863 * under parent and then iterate with the passed-in chain (which this
1864 * function will unlock).
1867 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1868 int *cache_indexp, int flags)
1870 hammer2_mount_t *hmp;
1871 hammer2_blockref_t *base;
1872 hammer2_blockref_t *bref;
1873 hammer2_blockref_t bcopy;
1875 hammer2_key_t next_key;
1877 int how_always = HAMMER2_RESOLVE_ALWAYS;
1878 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1881 int maxloops = 300000;
1886 * Scan flags borrowed from lookup
1888 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1889 how_maybe = how_always;
1890 how = HAMMER2_RESOLVE_ALWAYS;
1891 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1892 how = HAMMER2_RESOLVE_NEVER;
1894 how = HAMMER2_RESOLVE_MAYBE;
1896 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1897 how_maybe |= HAMMER2_RESOLVE_SHARED;
1898 how_always |= HAMMER2_RESOLVE_SHARED;
1899 how |= HAMMER2_RESOLVE_SHARED;
1903 * Calculate key to locate first/next element, unlocking the previous
1904 * element as we go. Be careful, the key calculation can overflow.
1907 key = chain->bref.key +
1908 ((hammer2_key_t)1 << chain->bref.keybits);
1909 hammer2_chain_unlock(chain);
1918 if (--maxloops == 0)
1919 panic("hammer2_chain_scan: maxloops");
1921 * Locate the blockref array. Currently we do a fully associative
1922 * search through the array.
1924 switch(parent->bref.type) {
1925 case HAMMER2_BREF_TYPE_INODE:
1927 * An inode with embedded data has no sub-chains.
1929 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1931 base = &parent->data->ipdata.u.blockset.blockref[0];
1932 count = HAMMER2_SET_COUNT;
1934 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1935 case HAMMER2_BREF_TYPE_INDIRECT:
1937 * Optimize indirect blocks in the INITIAL state to avoid
1940 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1943 if (parent->data == NULL)
1944 panic("parent->data is NULL");
1945 base = &parent->data->npdata[0];
1947 count = parent->bytes / sizeof(hammer2_blockref_t);
1949 case HAMMER2_BREF_TYPE_VOLUME:
1950 base = &hmp->voldata.sroot_blockset.blockref[0];
1951 count = HAMMER2_SET_COUNT;
1953 case HAMMER2_BREF_TYPE_FREEMAP:
1954 base = &hmp->voldata.freemap_blockset.blockref[0];
1955 count = HAMMER2_SET_COUNT;
1958 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1960 base = NULL; /* safety */
1961 count = 0; /* safety */
1965 * Merged scan to find next candidate.
1967 * hammer2_base_*() functions require the parent->core.live_* fields
1968 * to be synchronized.
1970 * We need to hold the spinlock to access the block array and RB tree
1971 * and to interlock chain creation.
1973 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1974 hammer2_chain_countbrefs(parent, base, count);
1977 hammer2_spin_ex(&parent->core.spin);
1978 chain = hammer2_combined_find(parent, base, count,
1979 cache_indexp, &next_key,
1980 key, HAMMER2_KEY_MAX,
1982 generation = parent->core.generation;
1985 * Exhausted parent chain, we're done.
1988 hammer2_spin_unex(&parent->core.spin);
1989 KKASSERT(chain == NULL);
1994 * Selected from blockref or in-memory chain.
1996 if (chain == NULL) {
1998 hammer2_spin_unex(&parent->core.spin);
1999 chain = hammer2_chain_get(parent, generation, &bcopy);
2000 if (chain == NULL) {
2001 kprintf("retry scan parent %p keys %016jx\n",
2005 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2006 hammer2_chain_drop(chain);
2011 hammer2_chain_ref(chain);
2012 hammer2_spin_unex(&parent->core.spin);
2016 * chain is referenced but not locked. We must lock the chain
2017 * to obtain definitive DUPLICATED/DELETED state
2019 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2022 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2024 * NOTE: chain's key range is not relevant as there might be
2025 * one-offs within the range that are not deleted.
2027 * NOTE: XXX this could create problems with scans used in
2028 * situations other than mount-time recovery.
2030 * NOTE: Lookups can race delete-duplicate because
2031 * delete-duplicate does not lock the parent's core
2032 * (they just use the spinlock on the core). We must
2033 * check for races by comparing the DUPLICATED flag before
2034 * releasing the spinlock with the flag after locking the
2037 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2038 hammer2_chain_unlock(chain);
2049 * All done, return the chain or NULL
2055 * Create and return a new hammer2 system memory structure of the specified
2056 * key, type and size and insert it under (*parentp). This is a full
2057 * insertion, based on the supplied key/keybits, and may involve creating
2058 * indirect blocks and moving other chains around via delete/duplicate.
2060 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2061 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2062 * FULL. This typically means that the caller is creating the chain after
2063 * doing a hammer2_chain_lookup().
2065 * (*parentp) must be exclusive locked and may be replaced on return
2066 * depending on how much work the function had to do.
2068 * (*chainp) usually starts out NULL and returns the newly created chain,
2069 * but if the caller desires the caller may allocate a disconnected chain
2070 * and pass it in instead.
2072 * This function should NOT be used to insert INDIRECT blocks. It is
2073 * typically used to create/insert inodes and data blocks.
2075 * Caller must pass-in an exclusively locked parent the new chain is to
2076 * be inserted under, and optionally pass-in a disconnected, exclusively
2077 * locked chain to insert (else we create a new chain). The function will
2078 * adjust (*parentp) as necessary, create or connect the chain, and
2079 * return an exclusively locked chain in *chainp.
2082 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2083 hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2084 hammer2_key_t key, int keybits, int type, size_t bytes,
2087 hammer2_mount_t *hmp;
2088 hammer2_chain_t *chain;
2089 hammer2_chain_t *parent;
2090 hammer2_blockref_t *base;
2091 hammer2_blockref_t dummy;
2095 int maxloops = 300000;
2098 * Topology may be crossing a PFS boundary.
2101 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2105 if (chain == NULL) {
2107 * First allocate media space and construct the dummy bref,
2108 * then allocate the in-memory chain structure. Set the
2109 * INITIAL flag for fresh chains which do not have embedded
2112 bzero(&dummy, sizeof(dummy));
2115 dummy.keybits = keybits;
2116 dummy.data_off = hammer2_getradix(bytes);
2117 dummy.methods = parent->bref.methods;
2118 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2119 hammer2_chain_core_alloc(trans, chain);
2122 * Lock the chain manually, chain_lock will load the chain
2123 * which we do NOT want to do. (note: chain->refs is set
2124 * to 1 by chain_alloc() for us, but lockcnt is not).
2127 hammer2_mtx_ex(&chain->core.lock);
2131 * We do NOT set INITIAL here (yet). INITIAL is only
2132 * used for indirect blocks.
2134 * Recalculate bytes to reflect the actual media block
2137 bytes = (hammer2_off_t)1 <<
2138 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2139 chain->bytes = bytes;
2142 case HAMMER2_BREF_TYPE_VOLUME:
2143 case HAMMER2_BREF_TYPE_FREEMAP:
2144 panic("hammer2_chain_create: called with volume type");
2146 case HAMMER2_BREF_TYPE_INDIRECT:
2147 panic("hammer2_chain_create: cannot be used to"
2148 "create indirect block");
2150 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2151 panic("hammer2_chain_create: cannot be used to"
2152 "create freemap root or node");
2154 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2155 KKASSERT(bytes == sizeof(chain->data->bmdata));
2157 case HAMMER2_BREF_TYPE_INODE:
2158 case HAMMER2_BREF_TYPE_DATA:
2161 * leave chain->data NULL, set INITIAL
2163 KKASSERT(chain->data == NULL);
2164 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2169 * Set statistics for pending updates. These will be
2170 * synchronized by the flush code.
2173 case HAMMER2_BREF_TYPE_INODE:
2174 chain->inode_count = 1;
2176 case HAMMER2_BREF_TYPE_DATA:
2177 case HAMMER2_BREF_TYPE_INDIRECT:
2178 chain->data_count = chain->bytes;
2183 * We are reattaching a previously deleted chain, possibly
2184 * under a new parent and possibly with a new key/keybits.
2185 * The chain does not have to be in a modified state. The
2186 * UPDATE flag will be set later on in this routine.
2188 * Do NOT mess with the current state of the INITIAL flag.
2190 chain->bref.key = key;
2191 chain->bref.keybits = keybits;
2192 if (chain->flags & HAMMER2_CHAIN_DELETED)
2193 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2194 KKASSERT(chain->parent == NULL);
2198 * Calculate how many entries we have in the blockref array and
2199 * determine if an indirect block is required.
2202 if (--maxloops == 0)
2203 panic("hammer2_chain_create: maxloops");
2205 switch(parent->bref.type) {
2206 case HAMMER2_BREF_TYPE_INODE:
2207 KKASSERT((parent->data->ipdata.op_flags &
2208 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2209 KKASSERT(parent->data != NULL);
2210 base = &parent->data->ipdata.u.blockset.blockref[0];
2211 count = HAMMER2_SET_COUNT;
2213 case HAMMER2_BREF_TYPE_INDIRECT:
2214 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2215 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2218 base = &parent->data->npdata[0];
2219 count = parent->bytes / sizeof(hammer2_blockref_t);
2221 case HAMMER2_BREF_TYPE_VOLUME:
2222 KKASSERT(parent->data != NULL);
2223 base = &hmp->voldata.sroot_blockset.blockref[0];
2224 count = HAMMER2_SET_COUNT;
2226 case HAMMER2_BREF_TYPE_FREEMAP:
2227 KKASSERT(parent->data != NULL);
2228 base = &hmp->voldata.freemap_blockset.blockref[0];
2229 count = HAMMER2_SET_COUNT;
2232 panic("hammer2_chain_create: unrecognized blockref type: %d",
2240 * Make sure we've counted the brefs
2242 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2243 hammer2_chain_countbrefs(parent, base, count);
2245 KKASSERT(parent->core.live_count >= 0 &&
2246 parent->core.live_count <= count);
2249 * If no free blockref could be found we must create an indirect
2250 * block and move a number of blockrefs into it. With the parent
2251 * locked we can safely lock each child in order to delete+duplicate
2252 * it without causing a deadlock.
2254 * This may return the new indirect block or the old parent depending
2255 * on where the key falls. NULL is returned on error.
2257 if (parent->core.live_count == count) {
2258 hammer2_chain_t *nparent;
2260 nparent = hammer2_chain_create_indirect(trans, parent,
2263 if (nparent == NULL) {
2265 hammer2_chain_drop(chain);
2269 if (parent != nparent) {
2270 hammer2_chain_unlock(parent);
2271 parent = *parentp = nparent;
2277 * Link the chain into its parent.
2279 if (chain->parent != NULL)
2280 panic("hammer2: hammer2_chain_create: chain already connected");
2281 KKASSERT(chain->parent == NULL);
2282 hammer2_chain_insert(parent, chain,
2283 HAMMER2_CHAIN_INSERT_SPIN |
2284 HAMMER2_CHAIN_INSERT_LIVE,
2289 * Mark the newly created chain modified. This will cause
2292 * Device buffers are not instantiated for DATA elements
2293 * as these are handled by logical buffers.
2295 * Indirect and freemap node indirect blocks are handled
2296 * by hammer2_chain_create_indirect() and not by this
2299 * Data for all other bref types is expected to be
2300 * instantiated (INODE, LEAF).
2302 switch(chain->bref.type) {
2303 case HAMMER2_BREF_TYPE_DATA:
2304 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2305 case HAMMER2_BREF_TYPE_INODE:
2306 hammer2_chain_modify(trans, chain,
2307 HAMMER2_MODIFY_OPTDATA);
2311 * Remaining types are not supported by this function.
2312 * In particular, INDIRECT and LEAF_NODE types are
2313 * handled by create_indirect().
2315 panic("hammer2_chain_create: bad type: %d",
2322 * When reconnecting a chain we must set UPDATE and
2323 * setflush so the flush recognizes that it must update
2324 * the bref in the parent.
2326 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2327 hammer2_chain_ref(chain);
2328 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2330 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2331 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2332 KKASSERT(chain->data);
2333 chain->inode_count_up +=
2334 chain->data->ipdata.inode_count;
2335 chain->data_count_up +=
2336 chain->data->ipdata.data_count;
2341 * We must setflush(parent) to ensure that it recurses through to
2342 * chain. setflush(chain) might not work because ONFLUSH is possibly
2343 * already set in the chain (so it won't recurse up to set it in the
2346 hammer2_chain_setflush(trans, parent);
2355 * Move the chain from its old parent to a new parent. The chain must have
2356 * already been deleted or already disconnected (or never associated) with
2357 * a parent. The chain is reassociated with the new parent and the deleted
2358 * flag will be cleared (no longer deleted). The chain's modification state
2361 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2362 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2363 * FULL. This typically means that the caller is creating the chain after
2364 * doing a hammer2_chain_lookup().
2366 * A non-NULL bref is typically passed when key and keybits must be overridden.
2367 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2368 * from a passed-in bref and uses the old chain's bref for everything else.
2370 * If (parent) is non-NULL then the new duplicated chain is inserted under
2373 * If (parent) is NULL then the newly duplicated chain is not inserted
2374 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2375 * passing into hammer2_chain_create() after this function returns).
2377 * WARNING! This function calls create which means it can insert indirect
2378 * blocks. This can cause other unrelated chains in the parent to
2379 * be moved to a newly inserted indirect block in addition to the
2383 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2384 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2387 hammer2_mount_t *hmp;
2388 hammer2_chain_t *parent;
2392 * WARNING! We should never resolve DATA to device buffers
2393 * (XXX allow it if the caller did?), and since
2394 * we currently do not have the logical buffer cache
2395 * buffer in-hand to fix its cached physical offset
2396 * we also force the modify code to not COW it. XXX
2399 KKASSERT(chain->parent == NULL);
2402 * Now create a duplicate of the chain structure, associating
2403 * it with the same core, making it the same size, pointing it
2404 * to the same bref (the same media block).
2407 bref = &chain->bref;
2408 bytes = (hammer2_off_t)1 <<
2409 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2412 * If parent is not NULL the duplicated chain will be entered under
2413 * the parent and the UPDATE bit set to tell flush to update
2416 * We must setflush(parent) to ensure that it recurses through to
2417 * chain. setflush(chain) might not work because ONFLUSH is possibly
2418 * already set in the chain (so it won't recurse up to set it in the
2421 * Having both chains locked is extremely important for atomicy.
2423 if (parentp && (parent = *parentp) != NULL) {
2424 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2425 KKASSERT(parent->refs > 0);
2427 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2428 bref->key, bref->keybits, bref->type,
2429 chain->bytes, flags);
2430 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2431 hammer2_chain_setflush(trans, *parentp);
2436 * Helper function for deleting chains.
2438 * The chain is removed from the live view (the RBTREE) as well as the parent's
2439 * blockmap. Both chain and its parent must be locked.
2442 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2443 hammer2_chain_t *parent, hammer2_chain_t *chain,
2446 hammer2_mount_t *hmp;
2448 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2451 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2453 * Chain is blockmapped, so there must be a parent.
2454 * Atomically remove the chain from the parent and remove
2455 * the blockmap entry.
2457 hammer2_blockref_t *base;
2460 KKASSERT(parent != NULL);
2461 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2462 hammer2_chain_modify(trans, parent,
2463 HAMMER2_MODIFY_OPTDATA);
2466 * Calculate blockmap pointer
2468 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2469 hammer2_spin_ex(&parent->core.spin);
2471 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2472 atomic_add_int(&parent->core.live_count, -1);
2473 ++parent->core.generation;
2474 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2475 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2476 --parent->core.chain_count;
2477 chain->parent = NULL;
2479 switch(parent->bref.type) {
2480 case HAMMER2_BREF_TYPE_INODE:
2482 * Access the inode's block array. However, there
2483 * is no block array if the inode is flagged
2484 * DIRECTDATA. The DIRECTDATA case typicaly only
2485 * occurs when a hardlink has been shifted up the
2486 * tree and the original inode gets replaced with
2487 * an OBJTYPE_HARDLINK placeholding inode.
2490 (parent->data->ipdata.op_flags &
2491 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2493 &parent->data->ipdata.u.blockset.blockref[0];
2497 count = HAMMER2_SET_COUNT;
2499 case HAMMER2_BREF_TYPE_INDIRECT:
2500 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2502 base = &parent->data->npdata[0];
2505 count = parent->bytes / sizeof(hammer2_blockref_t);
2507 case HAMMER2_BREF_TYPE_VOLUME:
2508 base = &hmp->voldata.sroot_blockset.blockref[0];
2509 count = HAMMER2_SET_COUNT;
2511 case HAMMER2_BREF_TYPE_FREEMAP:
2512 base = &parent->data->npdata[0];
2513 count = HAMMER2_SET_COUNT;
2518 panic("hammer2_flush_pass2: "
2519 "unrecognized blockref type: %d",
2524 * delete blockmapped chain from its parent.
2526 * The parent is not affected by any statistics in chain
2527 * which are pending synchronization. That is, there is
2528 * nothing to undo in the parent since they have not yet
2529 * been incorporated into the parent.
2531 * The parent is affected by statistics stored in inodes.
2532 * Those have already been synchronized, so they must be
2533 * undone. XXX split update possible w/delete in middle?
2536 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2537 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2538 KKASSERT(chain->data != NULL);
2539 parent->data_count -=
2540 chain->data->ipdata.data_count;
2541 parent->inode_count -=
2542 chain->data->ipdata.inode_count;
2545 int cache_index = -1;
2546 hammer2_base_delete(trans, parent, base, count,
2547 &cache_index, chain);
2549 hammer2_spin_unex(&parent->core.spin);
2550 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2552 * Chain is not blockmapped but a parent is present.
2553 * Atomically remove the chain from the parent. There is
2554 * no blockmap entry to remove.
2556 * Because chain was associated with a parent but not
2557 * synchronized, the chain's *_count_up fields contain
2558 * inode adjustment statistics which must be undone.
2560 hammer2_spin_ex(&parent->core.spin);
2561 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2562 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2563 KKASSERT(chain->data != NULL);
2564 chain->data_count_up -=
2565 chain->data->ipdata.data_count;
2566 chain->inode_count_up -=
2567 chain->data->ipdata.inode_count;
2569 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2570 atomic_add_int(&parent->core.live_count, -1);
2571 ++parent->core.generation;
2572 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2573 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2574 --parent->core.chain_count;
2575 chain->parent = NULL;
2576 hammer2_spin_unex(&parent->core.spin);
2579 * Chain is not blockmapped and has no parent. This
2580 * is a degenerate case.
2582 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2587 * If the deletion is permanent (i.e. the chain is not simply being
2588 * moved within the topology), adjust the freemap to indicate that
2589 * the block *might* be freeable. bulkfree must still determine
2590 * that it is actually freeable.
2592 * We no longer do this in the normal filesystem operations path
2593 * as it interferes with the bulkfree algorithm.
2595 if ((flags & HAMMER2_DELETE_PERMANENT) &&
2596 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2597 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
2598 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
2599 hammer2_freemap_adjust(trans, hmp, &chain->bref,
2600 HAMMER2_FREEMAP_DOMAYFREE);
2606 * Create an indirect block that covers one or more of the elements in the
2607 * current parent. Either returns the existing parent with no locking or
2608 * ref changes or returns the new indirect block locked and referenced
2609 * and leaving the original parent lock/ref intact as well.
2611 * If an error occurs, NULL is returned and *errorp is set to the error.
2613 * The returned chain depends on where the specified key falls.
2615 * The key/keybits for the indirect mode only needs to follow three rules:
2617 * (1) That all elements underneath it fit within its key space and
2619 * (2) That all elements outside it are outside its key space.
2621 * (3) When creating the new indirect block any elements in the current
2622 * parent that fit within the new indirect block's keyspace must be
2623 * moved into the new indirect block.
2625 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2626 * keyspace the the current parent, but lookup/iteration rules will
2627 * ensure (and must ensure) that rule (2) for all parents leading up
2628 * to the nearest inode or the root volume header is adhered to. This
2629 * is accomplished by always recursing through matching keyspaces in
2630 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2632 * The current implementation calculates the current worst-case keyspace by
2633 * iterating the current parent and then divides it into two halves, choosing
2634 * whichever half has the most elements (not necessarily the half containing
2635 * the requested key).
2637 * We can also opt to use the half with the least number of elements. This
2638 * causes lower-numbered keys (aka logical file offsets) to recurse through
2639 * fewer indirect blocks and higher-numbered keys to recurse through more.
2640 * This also has the risk of not moving enough elements to the new indirect
2641 * block and being forced to create several indirect blocks before the element
2644 * Must be called with an exclusively locked parent.
2646 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2647 hammer2_key_t *keyp, int keybits,
2648 hammer2_blockref_t *base, int count);
2649 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2650 hammer2_key_t *keyp, int keybits,
2651 hammer2_blockref_t *base, int count);
2654 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2655 hammer2_key_t create_key, int create_bits,
2656 int for_type, int *errorp)
2658 hammer2_mount_t *hmp;
2659 hammer2_blockref_t *base;
2660 hammer2_blockref_t *bref;
2661 hammer2_blockref_t bcopy;
2662 hammer2_chain_t *chain;
2663 hammer2_chain_t *ichain;
2664 hammer2_chain_t dummy;
2665 hammer2_key_t key = create_key;
2666 hammer2_key_t key_beg;
2667 hammer2_key_t key_end;
2668 hammer2_key_t key_next;
2669 int keybits = create_bits;
2676 int maxloops = 300000;
2679 * Calculate the base blockref pointer or NULL if the chain
2680 * is known to be empty. We need to calculate the array count
2681 * for RB lookups either way.
2685 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2687 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2688 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2691 switch(parent->bref.type) {
2692 case HAMMER2_BREF_TYPE_INODE:
2693 count = HAMMER2_SET_COUNT;
2695 case HAMMER2_BREF_TYPE_INDIRECT:
2696 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2697 count = parent->bytes / sizeof(hammer2_blockref_t);
2699 case HAMMER2_BREF_TYPE_VOLUME:
2700 count = HAMMER2_SET_COUNT;
2702 case HAMMER2_BREF_TYPE_FREEMAP:
2703 count = HAMMER2_SET_COUNT;
2706 panic("hammer2_chain_create_indirect: "
2707 "unrecognized blockref type: %d",
2713 switch(parent->bref.type) {
2714 case HAMMER2_BREF_TYPE_INODE:
2715 base = &parent->data->ipdata.u.blockset.blockref[0];
2716 count = HAMMER2_SET_COUNT;
2718 case HAMMER2_BREF_TYPE_INDIRECT:
2719 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2720 base = &parent->data->npdata[0];
2721 count = parent->bytes / sizeof(hammer2_blockref_t);
2723 case HAMMER2_BREF_TYPE_VOLUME:
2724 base = &hmp->voldata.sroot_blockset.blockref[0];
2725 count = HAMMER2_SET_COUNT;
2727 case HAMMER2_BREF_TYPE_FREEMAP:
2728 base = &hmp->voldata.freemap_blockset.blockref[0];
2729 count = HAMMER2_SET_COUNT;
2732 panic("hammer2_chain_create_indirect: "
2733 "unrecognized blockref type: %d",
2741 * dummy used in later chain allocation (no longer used for lookups).
2743 bzero(&dummy, sizeof(dummy));
2746 * When creating an indirect block for a freemap node or leaf
2747 * the key/keybits must be fitted to static radix levels because
2748 * particular radix levels use particular reserved blocks in the
2751 * This routine calculates the key/radix of the indirect block
2752 * we need to create, and whether it is on the high-side or the
2755 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2756 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2757 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2760 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2765 * Normalize the key for the radix being represented, keeping the
2766 * high bits and throwing away the low bits.
2768 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2771 * How big should our new indirect block be? It has to be at least
2772 * as large as its parent.
2774 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2775 nbytes = HAMMER2_IND_BYTES_MIN;
2777 nbytes = HAMMER2_IND_BYTES_MAX;
2778 if (nbytes < count * sizeof(hammer2_blockref_t))
2779 nbytes = count * sizeof(hammer2_blockref_t);
2782 * Ok, create our new indirect block
2784 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2785 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2786 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2788 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2790 dummy.bref.key = key;
2791 dummy.bref.keybits = keybits;
2792 dummy.bref.data_off = hammer2_getradix(nbytes);
2793 dummy.bref.methods = parent->bref.methods;
2795 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2796 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2797 hammer2_chain_core_alloc(trans, ichain);
2798 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2799 hammer2_chain_drop(ichain); /* excess ref from alloc */
2802 * We have to mark it modified to allocate its block, but use
2803 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2804 * it won't be acted upon by the flush code.
2806 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2809 * Iterate the original parent and move the matching brefs into
2810 * the new indirect block.
2812 * XXX handle flushes.
2815 key_end = HAMMER2_KEY_MAX;
2817 hammer2_spin_ex(&parent->core.spin);
2822 if (++loops > 100000) {
2823 hammer2_spin_unex(&parent->core.spin);
2824 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2825 reason, parent, base, count, key_next);
2829 * NOTE: spinlock stays intact, returned chain (if not NULL)
2830 * is not referenced or locked which means that we
2831 * cannot safely check its flagged / deletion status
2834 chain = hammer2_combined_find(parent, base, count,
2835 &cache_index, &key_next,
2838 generation = parent->core.generation;
2841 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2844 * Skip keys that are not within the key/radix of the new
2845 * indirect block. They stay in the parent.
2847 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2848 (key ^ bref->key)) != 0) {
2849 goto next_key_spinlocked;
2853 * Load the new indirect block by acquiring the related
2854 * chains (potentially from media as it might not be
2855 * in-memory). Then move it to the new parent (ichain)
2856 * via DELETE-DUPLICATE.
2858 * chain is referenced but not locked. We must lock the
2859 * chain to obtain definitive DUPLICATED/DELETED state
2863 * Use chain already present in the RBTREE
2865 hammer2_chain_ref(chain);
2866 hammer2_spin_unex(&parent->core.spin);
2867 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2868 HAMMER2_RESOLVE_NOREF);
2871 * Get chain for blockref element. _get returns NULL
2872 * on insertion race.
2875 hammer2_spin_unex(&parent->core.spin);
2876 chain = hammer2_chain_get(parent, generation, &bcopy);
2877 if (chain == NULL) {
2879 hammer2_spin_ex(&parent->core.spin);
2882 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2883 kprintf("REASON 2\n");
2885 hammer2_chain_drop(chain);
2886 hammer2_spin_ex(&parent->core.spin);
2889 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2890 HAMMER2_RESOLVE_NOREF);
2894 * This is always live so if the chain has been deleted
2895 * we raced someone and we have to retry.
2897 * NOTE: Lookups can race delete-duplicate because
2898 * delete-duplicate does not lock the parent's core
2899 * (they just use the spinlock on the core). We must
2900 * check for races by comparing the DUPLICATED flag before
2901 * releasing the spinlock with the flag after locking the
2904 * (note reversed logic for this one)
2906 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2907 hammer2_chain_unlock(chain);
2912 * Shift the chain to the indirect block.
2914 * WARNING! No reason for us to load chain data, pass NOSTATS
2915 * to prevent delete/insert from trying to access
2916 * inode stats (and thus asserting if there is no
2917 * chain->data loaded).
2919 hammer2_chain_delete(trans, parent, chain,
2920 HAMMER2_DELETE_NOSTATS);
2921 hammer2_chain_rename(trans, NULL, &ichain, chain,
2922 HAMMER2_INSERT_NOSTATS);
2923 hammer2_chain_unlock(chain);
2924 KKASSERT(parent->refs > 0);
2927 hammer2_spin_ex(&parent->core.spin);
2928 next_key_spinlocked:
2929 if (--maxloops == 0)
2930 panic("hammer2_chain_create_indirect: maxloops");
2932 if (key_next == 0 || key_next > key_end)
2937 hammer2_spin_unex(&parent->core.spin);
2940 * Insert the new indirect block into the parent now that we've
2941 * cleared out some entries in the parent. We calculated a good
2942 * insertion index in the loop above (ichain->index).
2944 * We don't have to set UPDATE here because we mark ichain
2945 * modified down below (so the normal modified -> flush -> set-moved
2946 * sequence applies).
2948 * The insertion shouldn't race as this is a completely new block
2949 * and the parent is locked.
2951 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2952 hammer2_chain_insert(parent, ichain,
2953 HAMMER2_CHAIN_INSERT_SPIN |
2954 HAMMER2_CHAIN_INSERT_LIVE,
2958 * Make sure flushes propogate after our manual insertion.
2960 hammer2_chain_setflush(trans, ichain);
2961 hammer2_chain_setflush(trans, parent);
2964 * Figure out what to return.
2966 if (~(((hammer2_key_t)1 << keybits) - 1) &
2967 (create_key ^ key)) {
2969 * Key being created is outside the key range,
2970 * return the original parent.
2972 hammer2_chain_unlock(ichain);
2975 * Otherwise its in the range, return the new parent.
2976 * (leave both the new and old parent locked).
2985 * Calculate the keybits and highside/lowside of the freemap node the
2986 * caller is creating.
2988 * This routine will specify the next higher-level freemap key/radix
2989 * representing the lowest-ordered set. By doing so, eventually all
2990 * low-ordered sets will be moved one level down.
2992 * We have to be careful here because the freemap reserves a limited
2993 * number of blocks for a limited number of levels. So we can't just
2994 * push indiscriminately.
2997 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2998 int keybits, hammer2_blockref_t *base, int count)
3000 hammer2_chain_t *chain;
3001 hammer2_blockref_t *bref;
3003 hammer2_key_t key_beg;
3004 hammer2_key_t key_end;
3005 hammer2_key_t key_next;
3009 int maxloops = 300000;
3017 * Calculate the range of keys in the array being careful to skip
3018 * slots which are overridden with a deletion.
3021 key_end = HAMMER2_KEY_MAX;
3023 hammer2_spin_ex(&parent->core.spin);
3026 if (--maxloops == 0) {
3027 panic("indkey_freemap shit %p %p:%d\n",
3028 parent, base, count);
3030 chain = hammer2_combined_find(parent, base, count,
3031 &cache_index, &key_next,
3042 * Skip deleted chains.
3044 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3045 if (key_next == 0 || key_next > key_end)
3052 * Use the full live (not deleted) element for the scan
3053 * iteration. HAMMER2 does not allow partial replacements.
3055 * XXX should be built into hammer2_combined_find().
3057 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3059 if (keybits > bref->keybits) {
3061 keybits = bref->keybits;
3062 } else if (keybits == bref->keybits && bref->key < key) {
3069 hammer2_spin_unex(&parent->core.spin);
3072 * Return the keybits for a higher-level FREEMAP_NODE covering
3076 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3077 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3079 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3080 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3082 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3083 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3085 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3086 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3088 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3089 panic("hammer2_chain_indkey_freemap: level too high");
3092 panic("hammer2_chain_indkey_freemap: bad radix");
3101 * Calculate the keybits and highside/lowside of the indirect block the
3102 * caller is creating.
3105 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3106 int keybits, hammer2_blockref_t *base, int count)
3108 hammer2_blockref_t *bref;
3109 hammer2_chain_t *chain;
3110 hammer2_key_t key_beg;
3111 hammer2_key_t key_end;
3112 hammer2_key_t key_next;
3118 int maxloops = 300000;
3125 * Calculate the range of keys in the array being careful to skip
3126 * slots which are overridden with a deletion. Once the scan
3127 * completes we will cut the key range in half and shift half the
3128 * range into the new indirect block.
3131 key_end = HAMMER2_KEY_MAX;
3133 hammer2_spin_ex(&parent->core.spin);
3136 if (--maxloops == 0) {
3137 panic("indkey_freemap shit %p %p:%d\n",
3138 parent, base, count);
3140 chain = hammer2_combined_find(parent, base, count,
3141 &cache_index, &key_next,
3152 * NOTE: No need to check DUPLICATED here because we do
3153 * not release the spinlock.
3155 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3156 if (key_next == 0 || key_next > key_end)
3163 * Use the full live (not deleted) element for the scan
3164 * iteration. HAMMER2 does not allow partial replacements.
3166 * XXX should be built into hammer2_combined_find().
3168 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3171 * Expand our calculated key range (key, keybits) to fit
3172 * the scanned key. nkeybits represents the full range
3173 * that we will later cut in half (two halves @ nkeybits - 1).
3176 if (nkeybits < bref->keybits) {
3177 if (bref->keybits > 64) {
3178 kprintf("bad bref chain %p bref %p\n",
3182 nkeybits = bref->keybits;
3184 while (nkeybits < 64 &&
3185 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3186 (key ^ bref->key)) != 0) {
3191 * If the new key range is larger we have to determine
3192 * which side of the new key range the existing keys fall
3193 * under by checking the high bit, then collapsing the
3194 * locount into the hicount or vise-versa.
3196 if (keybits != nkeybits) {
3197 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3208 * The newly scanned key will be in the lower half or the
3209 * upper half of the (new) key range.
3211 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3220 hammer2_spin_unex(&parent->core.spin);
3221 bref = NULL; /* now invalid (safety) */
3224 * Adjust keybits to represent half of the full range calculated
3225 * above (radix 63 max)
3230 * Select whichever half contains the most elements. Theoretically
3231 * we can select either side as long as it contains at least one
3232 * element (in order to ensure that a free slot is present to hold
3233 * the indirect block).
3235 if (hammer2_indirect_optimize) {
3237 * Insert node for least number of keys, this will arrange
3238 * the first few blocks of a large file or the first few
3239 * inodes in a directory with fewer indirect blocks when
3242 if (hicount < locount && hicount != 0)
3243 key |= (hammer2_key_t)1 << keybits;
3245 key &= ~(hammer2_key_t)1 << keybits;
3248 * Insert node for most number of keys, best for heavily
3251 if (hicount > locount)
3252 key |= (hammer2_key_t)1 << keybits;
3254 key &= ~(hammer2_key_t)1 << keybits;
3262 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3265 * Both parent and chain must be locked exclusively.
3267 * This function will modify the parent if the blockref requires removal
3268 * from the parent's block table.
3270 * This function is NOT recursive. Any entity already pushed into the
3271 * chain (such as an inode) may still need visibility into its contents,
3272 * as well as the ability to read and modify the contents. For example,
3273 * for an unlinked file which is still open.
3276 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3277 hammer2_chain_t *chain, int flags)
3279 KKASSERT(hammer2_mtx_owned(&chain->core.lock));
3282 * Nothing to do if already marked.
3284 * We need the spinlock on the core whos RBTREE contains chain
3285 * to protect against races.
3287 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3288 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3289 chain->parent == parent);
3290 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3293 if (flags & HAMMER2_DELETE_PERMANENT) {
3294 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3295 hammer2_flush(trans, chain);
3297 /* XXX might not be needed */
3298 hammer2_chain_setflush(trans, chain);
3303 * Returns the index of the nearest element in the blockref array >= elm.
3304 * Returns (count) if no element could be found.
3306 * Sets *key_nextp to the next key for loop purposes but does not modify
3307 * it if the next key would be higher than the current value of *key_nextp.
3308 * Note that *key_nexp can overflow to 0, which should be tested by the
3311 * (*cache_indexp) is a heuristic and can be any value without effecting
3314 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3315 * held through the operation.
3318 hammer2_base_find(hammer2_chain_t *parent,
3319 hammer2_blockref_t *base, int count,
3320 int *cache_indexp, hammer2_key_t *key_nextp,
3321 hammer2_key_t key_beg, hammer2_key_t key_end)
3323 hammer2_blockref_t *scan;
3324 hammer2_key_t scan_end;
3329 * Require the live chain's already have their core's counted
3330 * so we can optimize operations.
3332 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3337 if (count == 0 || base == NULL)
3341 * Sequential optimization using *cache_indexp. This is the most
3344 * We can avoid trailing empty entries on live chains, otherwise
3345 * we might have to check the whole block array.
3349 limit = parent->core.live_zero;
3354 KKASSERT(i < count);
3360 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3367 * Search forwards, stop when we find a scan element which
3368 * encloses the key or until we know that there are no further
3372 if (scan->type != 0) {
3373 scan_end = scan->key +
3374 ((hammer2_key_t)1 << scan->keybits) - 1;
3375 if (scan->key > key_beg || scan_end >= key_beg)
3388 scan_end = scan->key +
3389 ((hammer2_key_t)1 << scan->keybits);
3390 if (scan_end && (*key_nextp > scan_end ||
3392 *key_nextp = scan_end;
3400 * Do a combined search and return the next match either from the blockref
3401 * array or from the in-memory chain. Sets *bresp to the returned bref in
3402 * both cases, or sets it to NULL if the search exhausted. Only returns
3403 * a non-NULL chain if the search matched from the in-memory chain.
3405 * When no in-memory chain has been found and a non-NULL bref is returned
3409 * The returned chain is not locked or referenced. Use the returned bref
3410 * to determine if the search exhausted or not. Iterate if the base find
3411 * is chosen but matches a deleted chain.
3413 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3414 * held through the operation.
3416 static hammer2_chain_t *
3417 hammer2_combined_find(hammer2_chain_t *parent,
3418 hammer2_blockref_t *base, int count,
3419 int *cache_indexp, hammer2_key_t *key_nextp,
3420 hammer2_key_t key_beg, hammer2_key_t key_end,
3421 hammer2_blockref_t **bresp)
3423 hammer2_blockref_t *bref;
3424 hammer2_chain_t *chain;
3428 * Lookup in block array and in rbtree.
3430 *key_nextp = key_end + 1;
3431 i = hammer2_base_find(parent, base, count, cache_indexp,
3432 key_nextp, key_beg, key_end);
3433 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3438 if (i == count && chain == NULL) {
3444 * Only chain matched.
3447 bref = &chain->bref;
3452 * Only blockref matched.
3454 if (chain == NULL) {
3460 * Both in-memory and blockref matched, select the nearer element.
3462 * If both are flush with the left-hand side or both are the
3463 * same distance away, select the chain. In this situation the
3464 * chain must have been loaded from the matching blockmap.
3466 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3467 chain->bref.key == base[i].key) {
3468 KKASSERT(chain->bref.key == base[i].key);
3469 bref = &chain->bref;
3474 * Select the nearer key
3476 if (chain->bref.key < base[i].key) {
3477 bref = &chain->bref;
3484 * If the bref is out of bounds we've exhausted our search.
3487 if (bref->key > key_end) {
3497 * Locate the specified block array element and delete it. The element
3500 * The spin lock on the related chain must be held.
3502 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3503 * need to be adjusted when we commit the media change.
3506 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3507 hammer2_blockref_t *base, int count,
3508 int *cache_indexp, hammer2_chain_t *chain)
3510 hammer2_blockref_t *elm = &chain->bref;
3511 hammer2_key_t key_next;
3515 * Delete element. Expect the element to exist.
3517 * XXX see caller, flush code not yet sophisticated enough to prevent
3518 * re-flushed in some cases.
3520 key_next = 0; /* max range */
3521 i = hammer2_base_find(parent, base, count, cache_indexp,
3522 &key_next, elm->key, elm->key);
3523 if (i == count || base[i].type == 0 ||
3524 base[i].key != elm->key ||
3525 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3526 base[i].keybits != elm->keybits)) {
3527 hammer2_spin_unex(&parent->core.spin);
3528 panic("delete base %p element not found at %d/%d elm %p\n",
3529 base, i, count, elm);
3532 bzero(&base[i], sizeof(*base));
3535 * We can only optimize parent->core.live_zero for live chains.
3537 if (parent->core.live_zero == i + 1) {
3538 while (--i >= 0 && base[i].type == 0)
3540 parent->core.live_zero = i + 1;
3544 * Clear appropriate blockmap flags in chain.
3546 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3547 HAMMER2_CHAIN_BMAPUPD);
3551 * Insert the specified element. The block array must not already have the
3552 * element and must have space available for the insertion.
3554 * The spin lock on the related chain must be held.
3556 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3557 * need to be adjusted when we commit the media change.
3560 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3561 hammer2_blockref_t *base, int count,
3562 int *cache_indexp, hammer2_chain_t *chain)
3564 hammer2_blockref_t *elm = &chain->bref;
3565 hammer2_key_t key_next;
3574 * Insert new element. Expect the element to not already exist
3575 * unless we are replacing it.
3577 * XXX see caller, flush code not yet sophisticated enough to prevent
3578 * re-flushed in some cases.
3580 key_next = 0; /* max range */
3581 i = hammer2_base_find(parent, base, count, cache_indexp,
3582 &key_next, elm->key, elm->key);
3585 * Shortcut fill optimization, typical ordered insertion(s) may not
3588 KKASSERT(i >= 0 && i <= count);
3591 * Set appropriate blockmap flags in chain.
3593 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3596 * We can only optimize parent->core.live_zero for live chains.
3598 if (i == count && parent->core.live_zero < count) {
3599 i = parent->core.live_zero++;
3604 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3605 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3606 hammer2_spin_unex(&parent->core.spin);
3607 panic("insert base %p overlapping elements at %d elm %p\n",
3612 * Try to find an empty slot before or after.
3616 while (j > 0 || k < count) {
3618 if (j >= 0 && base[j].type == 0) {
3622 bcopy(&base[j+1], &base[j],
3623 (i - j - 1) * sizeof(*base));
3629 if (k < count && base[k].type == 0) {
3630 bcopy(&base[i], &base[i+1],
3631 (k - i) * sizeof(hammer2_blockref_t));
3635 * We can only update parent->core.live_zero for live
3638 if (parent->core.live_zero <= k)
3639 parent->core.live_zero = k + 1;
3644 panic("hammer2_base_insert: no room!");
3651 for (l = 0; l < count; ++l) {
3653 key_next = base[l].key +
3654 ((hammer2_key_t)1 << base[l].keybits) - 1;
3658 while (++l < count) {
3660 if (base[l].key <= key_next)
3661 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3662 key_next = base[l].key +
3663 ((hammer2_key_t)1 << base[l].keybits) - 1;
3673 * Sort the blockref array for the chain. Used by the flush code to
3674 * sort the blockref[] array.
3676 * The chain must be exclusively locked AND spin-locked.
3678 typedef hammer2_blockref_t *hammer2_blockref_p;
3682 hammer2_base_sort_callback(const void *v1, const void *v2)
3684 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3685 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3688 * Make sure empty elements are placed at the end of the array
3690 if (bref1->type == 0) {
3691 if (bref2->type == 0)
3694 } else if (bref2->type == 0) {
3701 if (bref1->key < bref2->key)
3703 if (bref1->key > bref2->key)
3709 hammer2_base_sort(hammer2_chain_t *chain)
3711 hammer2_blockref_t *base;
3714 switch(chain->bref.type) {
3715 case HAMMER2_BREF_TYPE_INODE:
3717 * Special shortcut for embedded data returns the inode
3718 * itself. Callers must detect this condition and access
3719 * the embedded data (the strategy code does this for us).
3721 * This is only applicable to regular files and softlinks.
3723 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3725 base = &chain->data->ipdata.u.blockset.blockref[0];
3726 count = HAMMER2_SET_COUNT;
3728 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3729 case HAMMER2_BREF_TYPE_INDIRECT:
3731 * Optimize indirect blocks in the INITIAL state to avoid
3734 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3735 base = &chain->data->npdata[0];
3736 count = chain->bytes / sizeof(hammer2_blockref_t);
3738 case HAMMER2_BREF_TYPE_VOLUME:
3739 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3740 count = HAMMER2_SET_COUNT;
3742 case HAMMER2_BREF_TYPE_FREEMAP:
3743 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3744 count = HAMMER2_SET_COUNT;
3747 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3749 base = NULL; /* safety */
3750 count = 0; /* safety */
3752 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3758 * Chain memory management
3761 hammer2_chain_wait(hammer2_chain_t *chain)
3763 tsleep(chain, 0, "chnflw", 1);
3766 const hammer2_media_data_t *
3767 hammer2_chain_rdata(hammer2_chain_t *chain)
3769 KKASSERT(chain->data != NULL);
3770 return (chain->data);
3773 hammer2_media_data_t *
3774 hammer2_chain_wdata(hammer2_chain_t *chain)
3776 KKASSERT(chain->data != NULL);
3777 return (chain->data);
3781 * Set the check data for a chain. This can be a heavy-weight operation
3782 * and typically only runs on-flush. For file data check data is calculated
3783 * when the logical buffers are flushed.
3786 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3788 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3790 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3791 case HAMMER2_CHECK_NONE:
3793 case HAMMER2_CHECK_DISABLED:
3795 case HAMMER2_CHECK_ISCSI32:
3796 chain->bref.check.iscsi32.value =
3797 hammer2_icrc32(bdata, chain->bytes);
3799 case HAMMER2_CHECK_CRC64:
3800 chain->bref.check.crc64.value = 0;
3803 case HAMMER2_CHECK_SHA192:
3805 SHA256_CTX hash_ctx;
3807 uint8_t digest[SHA256_DIGEST_LENGTH];
3808 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3811 SHA256_Init(&hash_ctx);
3812 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3813 SHA256_Final(u.digest, &hash_ctx);
3814 u.digest64[2] ^= u.digest64[3];
3816 chain->bref.check.sha192.data,
3817 sizeof(chain->bref.check.sha192.data));
3820 case HAMMER2_CHECK_FREEMAP:
3821 chain->bref.check.freemap.icrc32 =
3822 hammer2_icrc32(bdata, chain->bytes);
3825 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3826 chain->bref.methods);
3832 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3836 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3839 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3840 case HAMMER2_CHECK_NONE:
3843 case HAMMER2_CHECK_DISABLED:
3846 case HAMMER2_CHECK_ISCSI32:
3847 r = (chain->bref.check.iscsi32.value ==
3848 hammer2_icrc32(bdata, chain->bytes));
3850 case HAMMER2_CHECK_CRC64:
3851 r = (chain->bref.check.crc64.value == 0);
3854 case HAMMER2_CHECK_SHA192:
3856 SHA256_CTX hash_ctx;
3858 uint8_t digest[SHA256_DIGEST_LENGTH];
3859 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3862 SHA256_Init(&hash_ctx);
3863 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3864 SHA256_Final(u.digest, &hash_ctx);
3865 u.digest64[2] ^= u.digest64[3];
3867 chain->bref.check.sha192.data,
3868 sizeof(chain->bref.check.sha192.data)) == 0) {
3875 case HAMMER2_CHECK_FREEMAP:
3876 r = (chain->bref.check.freemap.icrc32 ==
3877 hammer2_icrc32(bdata, chain->bytes));
3879 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3880 chain->bref.check.freemap.icrc32,
3881 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3883 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3884 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3889 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3890 chain->bref.methods);