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_dev_t *hmp, hammer2_pfs_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.
203 if (pmp == hmp->spmp)
209 chain->bytes = bytes;
211 chain->flags = HAMMER2_CHAIN_ALLOCATED;
214 * Set the PFS boundary flag if this chain represents a PFS root.
216 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
217 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
223 * Associate an existing core with the chain or allocate a new core.
225 * The core is not locked. No additional refs on the chain are made.
226 * (trans) must not be NULL if (core) is not NULL.
228 * When chains are delete-duplicated during flushes we insert nchain on
229 * the ownerq after ochain instead of at the end in order to give the
230 * drop code visibility in the correct order, otherwise drops can be missed.
233 hammer2_chain_core_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain)
235 hammer2_chain_core_t *core = &chain->core;
238 * Fresh core under nchain (no multi-homing of ochain's
241 RB_INIT(&core->rbtree); /* live chains */
242 hammer2_mtx_init(&core->lock, "h2chain");
246 * Add a reference to a chain element, preventing its destruction.
248 * (can be called with spinlock held)
251 hammer2_chain_ref(hammer2_chain_t *chain)
253 atomic_add_int(&chain->refs, 1);
257 * Insert the chain in the core rbtree.
259 * Normal insertions are placed in the live rbtree. Insertion of a deleted
260 * chain is a special case used by the flush code that is placed on the
261 * unstaged deleted list to avoid confusing the live view.
263 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
264 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
265 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
269 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
270 int flags, int generation)
272 hammer2_chain_t *xchain;
275 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
276 hammer2_spin_ex(&parent->core.spin);
279 * Interlocked by spinlock, check for race
281 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
282 parent->core.generation != generation) {
290 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
291 KASSERT(xchain == NULL,
292 ("hammer2_chain_insert: collision %p %p", chain, xchain));
293 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
294 chain->parent = parent;
295 ++parent->core.chain_count;
296 ++parent->core.generation; /* XXX incs for _get() too, XXX */
299 * We have to keep track of the effective live-view blockref count
300 * so the create code knows when to push an indirect block.
302 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
303 atomic_add_int(&parent->core.live_count, 1);
305 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
306 hammer2_spin_unex(&parent->core.spin);
311 * Drop the caller's reference to the chain. When the ref count drops to
312 * zero this function will try to disassociate the chain from its parent and
313 * deallocate it, then recursely drop the parent using the implied ref
314 * from the chain's chain->parent.
316 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
319 hammer2_chain_drop(hammer2_chain_t *chain)
324 if (hammer2_debug & 0x200000)
327 if (chain->flags & HAMMER2_CHAIN_UPDATE)
329 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
331 KKASSERT(chain->refs > need);
339 chain = hammer2_chain_lastdrop(chain);
341 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
343 /* retry the same chain */
349 * Safe handling of the 1->0 transition on chain. Returns a chain for
350 * recursive drop or NULL, possibly returning the same chain if the atomic
353 * Whem two chains need to be recursively dropped we use the chain
354 * we would otherwise free to placehold the additional chain. It's a bit
355 * convoluted but we can't just recurse without potentially blowing out
358 * The chain cannot be freed if it has a non-empty core (children) or
359 * it is not at the head of ownerq.
361 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
365 hammer2_chain_lastdrop(hammer2_chain_t *chain)
369 hammer2_chain_t *parent;
370 hammer2_chain_t *rdrop;
373 * Spinlock the core and check to see if it is empty. If it is
374 * not empty we leave chain intact with refs == 0. The elements
375 * in core->rbtree are associated with other chains contemporary
376 * with ours but not with our chain directly.
378 hammer2_spin_ex(&chain->core.spin);
381 * We can't free non-stale chains with children until we are
382 * able to free the children because there might be a flush
383 * dependency. Flushes of stale children (which should also
384 * have their deleted flag set) short-cut recursive flush
385 * dependencies and can be freed here. Any flushes which run
386 * through stale children due to the flush synchronization
387 * point should have a FLUSH_* bit set in the chain and not
388 * reach lastdrop at this time.
390 * NOTE: We return (chain) on failure to retry.
392 if (chain->core.chain_count) {
393 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
394 hammer2_spin_unex(&chain->core.spin);
395 chain = NULL; /* success */
397 hammer2_spin_unex(&chain->core.spin);
401 /* no chains left under us */
404 * chain->core has no children left so no accessors can get to our
405 * chain from there. Now we have to lock the parent core to interlock
406 * remaining possible accessors that might bump chain's refs before
407 * we can safely drop chain's refs with intent to free the chain.
410 pmp = chain->pmp; /* can be NULL */
414 * Spinlock the parent and try to drop the last ref on chain.
415 * On success remove chain from its parent, otherwise return NULL.
417 * (normal core locks are top-down recursive but we define core
418 * spinlocks as bottom-up recursive, so this is safe).
420 if ((parent = chain->parent) != NULL) {
421 hammer2_spin_ex(&parent->core.spin);
422 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
423 /* 1->0 transition failed */
424 hammer2_spin_unex(&parent->core.spin);
425 hammer2_spin_unex(&chain->core.spin);
426 return(chain); /* retry */
430 * 1->0 transition successful, remove chain from its
433 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
434 RB_REMOVE(hammer2_chain_tree,
435 &parent->core.rbtree, chain);
436 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
437 --parent->core.chain_count;
438 chain->parent = NULL;
442 * If our chain was the last chain in the parent's core the
443 * core is now empty and its parent might have to be
444 * re-dropped if it has 0 refs.
446 if (parent->core.chain_count == 0) {
448 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
452 hammer2_spin_unex(&parent->core.spin);
453 parent = NULL; /* safety */
457 * Successful 1->0 transition and the chain can be destroyed now.
459 * We still have the core spinlock, and core's chain_count is 0.
460 * Any parent spinlock is gone.
462 hammer2_spin_unex(&chain->core.spin);
463 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
464 chain->core.chain_count == 0);
467 * All spin locks are gone, finish freeing stuff.
469 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
470 HAMMER2_CHAIN_MODIFIED)) == 0);
471 hammer2_chain_drop_data(chain, 1);
473 KKASSERT(chain->dio == NULL);
476 * Once chain resources are gone we can use the now dead chain
477 * structure to placehold what might otherwise require a recursive
478 * drop, because we have potentially two things to drop and can only
479 * return one directly.
481 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
482 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
484 kfree(chain, hmp->mchain);
488 * Possible chaining loop when parent re-drop needed.
494 * On either last lock release or last drop
497 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
499 /*hammer2_dev_t *hmp = chain->hmp;*/
501 switch(chain->bref.type) {
502 case HAMMER2_BREF_TYPE_VOLUME:
503 case HAMMER2_BREF_TYPE_FREEMAP:
508 KKASSERT(chain->data == NULL);
514 * Ref and lock a chain element, acquiring its data with I/O if necessary,
515 * and specify how you would like the data to be resolved.
517 * Returns 0 on success or an error code if the data could not be acquired.
518 * The chain element is locked on return regardless of whether an error
521 * The lock is allowed to recurse, multiple locking ops will aggregate
522 * the requested resolve types. Once data is assigned it will not be
523 * removed until the last unlock.
525 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
526 * (typically used to avoid device/logical buffer
529 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
530 * the INITIAL-create state (indirect blocks only).
532 * Do not resolve data elements for DATA chains.
533 * (typically used to avoid device/logical buffer
536 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
538 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
539 * it will be locked exclusive.
541 * NOTE: Embedded elements (volume header, inodes) are always resolved
544 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
545 * element will instantiate and zero its buffer, and flush it on
548 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
549 * so as not to instantiate a device buffer, which could alias against
550 * a logical file buffer. However, if ALWAYS is specified the
551 * device buffer will be instantiated anyway.
553 * WARNING! If data must be fetched a shared lock will temporarily be
554 * upgraded to exclusive. However, a deadlock can occur if
555 * the caller owns more than one shared lock.
558 hammer2_chain_lock(hammer2_chain_t *chain, int how)
561 hammer2_blockref_t *bref;
562 hammer2_mtx_state_t ostate;
567 * Ref and lock the element. Recursive locks are allowed.
569 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
570 hammer2_chain_ref(chain);
571 atomic_add_int(&chain->lockcnt, 1);
574 KKASSERT(hmp != NULL);
577 * Get the appropriate lock.
579 if (how & HAMMER2_RESOLVE_SHARED)
580 hammer2_mtx_sh(&chain->core.lock);
582 hammer2_mtx_ex(&chain->core.lock);
585 * If we already have a valid data pointer no further action is
592 * Do we have to resolve the data?
594 switch(how & HAMMER2_RESOLVE_MASK) {
595 case HAMMER2_RESOLVE_NEVER:
597 case HAMMER2_RESOLVE_MAYBE:
598 if (chain->flags & HAMMER2_CHAIN_INITIAL)
600 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
603 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
605 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
609 case HAMMER2_RESOLVE_ALWAYS:
614 * Upgrade to an exclusive lock so we can safely manipulate the
615 * buffer cache. If another thread got to it before us we
618 ostate = hammer2_mtx_upgrade(&chain->core.lock);
620 hammer2_mtx_downgrade(&chain->core.lock, ostate);
625 * We must resolve to a device buffer, either by issuing I/O or
626 * by creating a zero-fill element. We do not mark the buffer
627 * dirty when creating a zero-fill element (the hammer2_chain_modify()
628 * API must still be used to do that).
630 * The device buffer is variable-sized in powers of 2 down
631 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
632 * chunk always contains buffers of the same size. (XXX)
634 * The minimum physical IO size may be larger than the variable
640 * The getblk() optimization can only be used on newly created
641 * elements if the physical block size matches the request.
643 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
644 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
647 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
649 hammer2_adjreadcounter(&chain->bref, chain->bytes);
653 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
654 (intmax_t)bref->data_off, error);
655 hammer2_io_bqrelse(&chain->dio);
656 hammer2_mtx_downgrade(&chain->core.lock, ostate);
662 * No need for this, always require that hammer2_chain_modify()
663 * be called before any modifying operations, which ensures that
664 * the underlying dio is dirty.
666 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
667 !hammer2_io_isdirty(chain->dio)) {
668 hammer2_io_setdirty(chain->dio);
673 * Clear INITIAL. In this case we used io_new() and the buffer has
674 * been zero'd and marked dirty.
676 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
677 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
678 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
679 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
680 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
682 * check data not currently synchronized due to
683 * modification. XXX assumes data stays in the buffer
684 * cache, which might not be true (need biodep on flush
685 * to calculate crc? or simple crc?).
688 if (hammer2_chain_testcheck(chain, bdata) == 0) {
689 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL %08x (flags=%08x)\n",
691 chain->bref.data_off,
694 hammer2_icrc32(bdata, chain->bytes),
700 * Setup the data pointer, either pointing it to an embedded data
701 * structure and copying the data from the buffer, or pointing it
704 * The buffer is not retained when copying to an embedded data
705 * structure in order to avoid potential deadlocks or recursions
706 * on the same physical buffer.
708 switch (bref->type) {
709 case HAMMER2_BREF_TYPE_VOLUME:
710 case HAMMER2_BREF_TYPE_FREEMAP:
712 * Copy data from bp to embedded buffer
714 panic("hammer2_chain_lock: called on unresolved volume header");
716 case HAMMER2_BREF_TYPE_INODE:
717 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
718 case HAMMER2_BREF_TYPE_INDIRECT:
719 case HAMMER2_BREF_TYPE_DATA:
720 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
723 * Point data at the device buffer and leave dio intact.
725 chain->data = (void *)bdata;
728 hammer2_mtx_downgrade(&chain->core.lock, ostate);
733 * Unlock and deref a chain element.
735 * On the last lock release any non-embedded data (chain->dio) will be
739 hammer2_chain_unlock(hammer2_chain_t *chain)
741 hammer2_mtx_state_t ostate;
746 * If multiple locks are present (or being attempted) on this
747 * particular chain we can just unlock, drop refs, and return.
749 * Otherwise fall-through on the 1->0 transition.
752 lockcnt = chain->lockcnt;
753 KKASSERT(lockcnt > 0);
756 if (atomic_cmpset_int(&chain->lockcnt,
757 lockcnt, lockcnt - 1)) {
758 hammer2_mtx_unlock(&chain->core.lock);
759 hammer2_chain_drop(chain);
763 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
770 * On the 1->0 transition we upgrade the core lock (if necessary)
771 * to exclusive for terminal processing. If after upgrading we find
772 * that lockcnt is non-zero, another thread is racing us and will
773 * handle the unload for us later on, so just cleanup and return
774 * leaving the data/io intact
776 * Otherwise if lockcnt is still 0 it is possible for it to become
777 * non-zero and race, but since we hold the core->lock exclusively
778 * all that will happen is that the chain will be reloaded after we
781 ostate = hammer2_mtx_upgrade(&chain->core.lock);
782 if (chain->lockcnt) {
783 hammer2_mtx_unlock(&chain->core.lock);
784 hammer2_chain_drop(chain);
789 * Shortcut the case if the data is embedded or not resolved.
791 * Do NOT NULL out chain->data (e.g. inode data), it might be
794 if (chain->dio == NULL) {
795 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
796 hammer2_chain_drop_data(chain, 0);
797 hammer2_mtx_unlock(&chain->core.lock);
798 hammer2_chain_drop(chain);
805 if (hammer2_io_isdirty(chain->dio) == 0) {
807 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
808 switch(chain->bref.type) {
809 case HAMMER2_BREF_TYPE_DATA:
810 counterp = &hammer2_ioa_file_write;
812 case HAMMER2_BREF_TYPE_INODE:
813 counterp = &hammer2_ioa_meta_write;
815 case HAMMER2_BREF_TYPE_INDIRECT:
816 counterp = &hammer2_ioa_indr_write;
818 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
819 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
820 counterp = &hammer2_ioa_fmap_write;
823 counterp = &hammer2_ioa_volu_write;
826 *counterp += chain->bytes;
828 switch(chain->bref.type) {
829 case HAMMER2_BREF_TYPE_DATA:
830 counterp = &hammer2_iod_file_write;
832 case HAMMER2_BREF_TYPE_INODE:
833 counterp = &hammer2_iod_meta_write;
835 case HAMMER2_BREF_TYPE_INDIRECT:
836 counterp = &hammer2_iod_indr_write;
838 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
839 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
840 counterp = &hammer2_iod_fmap_write;
843 counterp = &hammer2_iod_volu_write;
846 *counterp += chain->bytes;
852 * If a device buffer was used for data be sure to destroy the
853 * buffer when we are done to avoid aliases (XXX what about the
854 * underlying VM pages?).
856 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
859 * NOTE: The isdirty check tracks whether we have to bdwrite() the
860 * buffer or not. The buffer might already be dirty. The
861 * flag is re-set when chain_modify() is called, even if
862 * MODIFIED is already set, allowing the OS to retire the
863 * buffer independent of a hammer2 flush.
866 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
867 hammer2_io_isdirty(chain->dio)) {
868 hammer2_io_bawrite(&chain->dio);
870 hammer2_io_bqrelse(&chain->dio);
872 hammer2_mtx_unlock(&chain->core.lock);
873 hammer2_chain_drop(chain);
877 * This counts the number of live blockrefs in a block array and
878 * also calculates the point at which all remaining blockrefs are empty.
879 * This routine can only be called on a live chain (DUPLICATED flag not set).
881 * NOTE: Flag is not set until after the count is complete, allowing
882 * callers to test the flag without holding the spinlock.
884 * NOTE: If base is NULL the related chain is still in the INITIAL
885 * state and there are no blockrefs to count.
887 * NOTE: live_count may already have some counts accumulated due to
888 * creation and deletion and could even be initially negative.
891 hammer2_chain_countbrefs(hammer2_chain_t *chain,
892 hammer2_blockref_t *base, int count)
894 hammer2_spin_ex(&chain->core.spin);
895 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
897 while (--count >= 0) {
898 if (base[count].type)
901 chain->core.live_zero = count + 1;
903 if (base[count].type)
904 atomic_add_int(&chain->core.live_count,
909 chain->core.live_zero = 0;
911 /* else do not modify live_count */
912 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
914 hammer2_spin_unex(&chain->core.spin);
918 * Resize the chain's physical storage allocation in-place. This function does
919 * not adjust the data pointer and must be followed by (typically) a
920 * hammer2_chain_modify() call to copy any old data over and adjust the
923 * Chains can be resized smaller without reallocating the storage. Resizing
924 * larger will reallocate the storage. Excess or prior storage is reclaimed
925 * asynchronously at a later time.
927 * Must be passed an exclusively locked parent and chain.
929 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
930 * to avoid instantiating a device buffer that conflicts with the vnode data
931 * buffer. However, because H2 can compress or encrypt data, the chain may
932 * have a dio assigned to it in those situations, and they do not conflict.
934 * XXX return error if cannot resize.
937 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
938 hammer2_chain_t *parent, hammer2_chain_t *chain,
939 int nradix, int flags)
948 * Only data and indirect blocks can be resized for now.
949 * (The volu root, inodes, and freemap elements use a fixed size).
951 KKASSERT(chain != &hmp->vchain);
952 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
953 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
956 * Nothing to do if the element is already the proper size
958 obytes = chain->bytes;
959 nbytes = 1U << nradix;
960 if (obytes == nbytes)
962 chain->data_count += (ssize_t)(nbytes - obytes);
965 * Make sure the old data is instantiated so we can copy it. If this
966 * is a data block, the device data may be superfluous since the data
967 * might be in a logical block, but compressed or encrypted data is
970 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
972 hammer2_chain_modify(trans, chain, 0);
975 * Relocate the block, even if making it smaller (because different
976 * block sizes may be in different regions).
978 * (data blocks only, we aren't copying the storage here).
980 hammer2_freemap_alloc(trans, chain, nbytes);
981 chain->bytes = nbytes;
982 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
985 * We don't want the followup chain_modify() to try to copy data
986 * from the old (wrong-sized) buffer. It won't know how much to
987 * copy. This case should only occur during writes when the
988 * originator already has the data to write in-hand.
991 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
992 hammer2_io_brelse(&chain->dio);
998 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1000 hammer2_blockref_t obref;
1009 obref = chain->bref;
1012 * Data is not optional for freemap chains (we must always be sure
1013 * to copy the data on COW storage allocations).
1015 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1016 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1017 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1018 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1022 * Data must be resolved if already assigned unless explicitly
1023 * flagged otherwise.
1025 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1026 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1027 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1028 hammer2_chain_unlock(chain);
1032 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1033 * that the chain has been modified. Set UPDATE to ensure that
1034 * the blockref is updated in the parent.
1036 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1037 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1038 hammer2_chain_ref(chain);
1039 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1044 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1045 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1046 hammer2_chain_ref(chain);
1050 * The modification or re-modification requires an allocation and
1053 * We normally always allocate new storage here. If storage exists
1054 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1056 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1057 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1058 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1060 hammer2_freemap_alloc(trans, chain, chain->bytes);
1061 /* XXX failed allocation */
1066 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1067 * requires updating as well as to tell the delete code that the
1068 * chain's blockref might not exactly match (in terms of physical size
1069 * or block offset) the one in the parent's blocktable. The base key
1070 * of course will still match.
1072 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1073 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1076 * Short-cut data blocks which the caller does not need an actual
1077 * data reference to (aka OPTDATA), as long as the chain does not
1078 * already have a data pointer to the data. This generally means
1079 * that the modifications are being done via the logical buffer cache.
1080 * The INITIAL flag relates only to the device data buffer and thus
1081 * remains unchange in this situation.
1083 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1084 (flags & HAMMER2_MODIFY_OPTDATA) &&
1085 chain->data == NULL) {
1090 * Clearing the INITIAL flag (for indirect blocks) indicates that
1091 * we've processed the uninitialized storage allocation.
1093 * If this flag is already clear we are likely in a copy-on-write
1094 * situation but we have to be sure NOT to bzero the storage if
1095 * no data is present.
1097 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1098 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1105 * Instantiate data buffer and possibly execute COW operation
1107 switch(chain->bref.type) {
1108 case HAMMER2_BREF_TYPE_VOLUME:
1109 case HAMMER2_BREF_TYPE_FREEMAP:
1111 * The data is embedded, no copy-on-write operation is
1114 KKASSERT(chain->dio == NULL);
1116 case HAMMER2_BREF_TYPE_INODE:
1117 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1118 case HAMMER2_BREF_TYPE_DATA:
1119 case HAMMER2_BREF_TYPE_INDIRECT:
1120 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1122 * Perform the copy-on-write operation
1124 * zero-fill or copy-on-write depending on whether
1125 * chain->data exists or not and set the dirty state for
1126 * the new buffer. hammer2_io_new() will handle the
1129 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1132 error = hammer2_io_new(hmp, chain->bref.data_off,
1133 chain->bytes, &dio);
1135 error = hammer2_io_bread(hmp, chain->bref.data_off,
1136 chain->bytes, &dio);
1138 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1139 KKASSERT(error == 0);
1141 bdata = hammer2_io_data(dio, chain->bref.data_off);
1144 KKASSERT(chain->dio != NULL);
1145 if (chain->data != (void *)bdata) {
1146 bcopy(chain->data, bdata, chain->bytes);
1148 } else if (wasinitial == 0) {
1150 * We have a problem. We were asked to COW but
1151 * we don't have any data to COW with!
1153 panic("hammer2_chain_modify: having a COW %p\n",
1158 * Retire the old buffer, replace with the new. Dirty or
1159 * redirty the new buffer.
1161 * WARNING! The system buffer cache may have already flushed
1162 * the buffer, so we must be sure to [re]dirty it
1163 * for further modification.
1166 hammer2_io_brelse(&chain->dio);
1167 chain->data = (void *)bdata;
1169 hammer2_io_setdirty(dio); /* modified by bcopy above */
1172 panic("hammer2_chain_modify: illegal non-embedded type %d",
1179 * setflush on parent indicating that the parent must recurse down
1180 * to us. Do not call on chain itself which might already have it
1184 hammer2_chain_setflush(trans, chain->parent);
1188 * Volume header data locks
1191 hammer2_voldata_lock(hammer2_dev_t *hmp)
1193 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1197 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1199 lockmgr(&hmp->vollk, LK_RELEASE);
1203 hammer2_voldata_modify(hammer2_dev_t *hmp)
1205 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1206 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1207 hammer2_chain_ref(&hmp->vchain);
1208 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1213 * This function returns the chain at the nearest key within the specified
1214 * range. The returned chain will be referenced but not locked.
1216 * This function will recurse through chain->rbtree as necessary and will
1217 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1218 * the iteration value is less than the current value of *key_nextp.
1220 * The caller should use (*key_nextp) to calculate the actual range of
1221 * the returned element, which will be (key_beg to *key_nextp - 1), because
1222 * there might be another element which is superior to the returned element
1225 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1226 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1227 * it will wind up being (key_end + 1).
1229 * WARNING! Must be called with child's spinlock held. Spinlock remains
1230 * held through the operation.
1232 struct hammer2_chain_find_info {
1233 hammer2_chain_t *best;
1234 hammer2_key_t key_beg;
1235 hammer2_key_t key_end;
1236 hammer2_key_t key_next;
1239 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1240 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1244 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1245 hammer2_key_t key_beg, hammer2_key_t key_end)
1247 struct hammer2_chain_find_info info;
1250 info.key_beg = key_beg;
1251 info.key_end = key_end;
1252 info.key_next = *key_nextp;
1254 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1255 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1257 *key_nextp = info.key_next;
1259 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1260 parent, key_beg, key_end, *key_nextp);
1268 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1270 struct hammer2_chain_find_info *info = data;
1271 hammer2_key_t child_beg;
1272 hammer2_key_t child_end;
1274 child_beg = child->bref.key;
1275 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1277 if (child_end < info->key_beg)
1279 if (child_beg > info->key_end)
1286 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1288 struct hammer2_chain_find_info *info = data;
1289 hammer2_chain_t *best;
1290 hammer2_key_t child_end;
1293 * WARNING! Do not discard DUPLICATED chains, it is possible that
1294 * we are catching an insertion half-way done. If a
1295 * duplicated chain turns out to be the best choice the
1296 * caller will re-check its flags after locking it.
1298 * WARNING! Layerq is scanned forwards, exact matches should keep
1299 * the existing info->best.
1301 if ((best = info->best) == NULL) {
1303 * No previous best. Assign best
1306 } else if (best->bref.key <= info->key_beg &&
1307 child->bref.key <= info->key_beg) {
1312 /*info->best = child;*/
1313 } else if (child->bref.key < best->bref.key) {
1315 * Child has a nearer key and best is not flush with key_beg.
1316 * Set best to child. Truncate key_next to the old best key.
1319 if (info->key_next > best->bref.key || info->key_next == 0)
1320 info->key_next = best->bref.key;
1321 } else if (child->bref.key == best->bref.key) {
1323 * If our current best is flush with the child then this
1324 * is an illegal overlap.
1326 * key_next will automatically be limited to the smaller of
1327 * the two end-points.
1333 * Keep the current best but truncate key_next to the child's
1336 * key_next will also automatically be limited to the smaller
1337 * of the two end-points (probably not necessary for this case
1338 * but we do it anyway).
1340 if (info->key_next > child->bref.key || info->key_next == 0)
1341 info->key_next = child->bref.key;
1345 * Always truncate key_next based on child's end-of-range.
1347 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1348 if (child_end && (info->key_next > child_end || info->key_next == 0))
1349 info->key_next = child_end;
1355 * Retrieve the specified chain from a media blockref, creating the
1356 * in-memory chain structure which reflects it.
1358 * To handle insertion races pass the INSERT_RACE flag along with the
1359 * generation number of the core. NULL will be returned if the generation
1360 * number changes before we have a chance to insert the chain. Insert
1361 * races can occur because the parent might be held shared.
1363 * Caller must hold the parent locked shared or exclusive since we may
1364 * need the parent's bref array to find our block.
1366 * WARNING! chain->pmp is always set to NULL for any chain representing
1367 * part of the super-root topology.
1370 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1371 hammer2_blockref_t *bref)
1373 hammer2_dev_t *hmp = parent->hmp;
1374 hammer2_chain_t *chain;
1378 * Allocate a chain structure representing the existing media
1379 * entry. Resulting chain has one ref and is not locked.
1381 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1382 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1384 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1385 hammer2_chain_core_alloc(NULL, chain);
1386 /* ref'd chain returned */
1389 * Flag that the chain is in the parent's blockmap so delete/flush
1390 * knows what to do with it.
1392 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1395 * Link the chain into its parent. A spinlock is required to safely
1396 * access the RBTREE, and it is possible to collide with another
1397 * hammer2_chain_get() operation because the caller might only hold
1398 * a shared lock on the parent.
1400 KKASSERT(parent->refs > 0);
1401 error = hammer2_chain_insert(parent, chain,
1402 HAMMER2_CHAIN_INSERT_SPIN |
1403 HAMMER2_CHAIN_INSERT_RACE,
1406 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1407 kprintf("chain %p get race\n", chain);
1408 hammer2_chain_drop(chain);
1411 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1415 * Return our new chain referenced but not locked, or NULL if
1422 * Lookup initialization/completion API
1425 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1427 if (flags & HAMMER2_LOOKUP_SHARED) {
1428 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1429 HAMMER2_RESOLVE_SHARED);
1431 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1437 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1440 hammer2_chain_unlock(parent);
1445 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1447 hammer2_chain_t *oparent;
1448 hammer2_chain_t *nparent;
1451 * Be careful of order, oparent must be unlocked before nparent
1452 * is locked below to avoid a deadlock.
1455 hammer2_spin_ex(&oparent->core.spin);
1456 nparent = oparent->parent;
1457 hammer2_chain_ref(nparent);
1458 hammer2_spin_unex(&oparent->core.spin);
1460 hammer2_chain_unlock(oparent);
1464 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1471 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1472 * (*parentp) typically points to an inode but can also point to a related
1473 * indirect block and this function will recurse upwards and find the inode
1476 * (*parentp) must be exclusively locked and referenced and can be an inode
1477 * or an existing indirect block within the inode.
1479 * On return (*parentp) will be modified to point at the deepest parent chain
1480 * element encountered during the search, as a helper for an insertion or
1481 * deletion. The new (*parentp) will be locked and referenced and the old
1482 * will be unlocked and dereferenced (no change if they are both the same).
1484 * The matching chain will be returned exclusively locked. If NOLOCK is
1485 * requested the chain will be returned only referenced.
1487 * NULL is returned if no match was found, but (*parentp) will still
1488 * potentially be adjusted.
1490 * On return (*key_nextp) will point to an iterative value for key_beg.
1491 * (If NULL is returned (*key_nextp) is set to key_end).
1493 * This function will also recurse up the chain if the key is not within the
1494 * current parent's range. (*parentp) can never be set to NULL. An iteration
1495 * can simply allow (*parentp) to float inside the loop.
1497 * NOTE! chain->data is not always resolved. By default it will not be
1498 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1499 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1500 * BREF_TYPE_DATA as the device buffer can alias the logical file
1504 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1505 hammer2_key_t key_beg, hammer2_key_t key_end,
1506 int *cache_indexp, int flags)
1509 hammer2_chain_t *parent;
1510 hammer2_chain_t *chain;
1511 hammer2_blockref_t *base;
1512 hammer2_blockref_t *bref;
1513 hammer2_blockref_t bcopy;
1514 hammer2_key_t scan_beg;
1515 hammer2_key_t scan_end;
1517 int how_always = HAMMER2_RESOLVE_ALWAYS;
1518 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1521 int maxloops = 300000;
1523 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1524 how_maybe = how_always;
1525 how = HAMMER2_RESOLVE_ALWAYS;
1526 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1527 how = HAMMER2_RESOLVE_NEVER;
1529 how = HAMMER2_RESOLVE_MAYBE;
1531 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1532 how_maybe |= HAMMER2_RESOLVE_SHARED;
1533 how_always |= HAMMER2_RESOLVE_SHARED;
1534 how |= HAMMER2_RESOLVE_SHARED;
1538 * Recurse (*parentp) upward if necessary until the parent completely
1539 * encloses the key range or we hit the inode.
1541 * This function handles races against the flusher doing a delete-
1542 * duplicate above us and re-homes the parent to the duplicate in
1543 * that case, otherwise we'd wind up recursing down a stale chain.
1548 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1549 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1550 scan_beg = parent->bref.key;
1551 scan_end = scan_beg +
1552 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1553 if (key_beg >= scan_beg && key_end <= scan_end)
1555 parent = hammer2_chain_getparent(parentp, how_maybe);
1559 if (--maxloops == 0)
1560 panic("hammer2_chain_lookup: maxloops");
1562 * Locate the blockref array. Currently we do a fully associative
1563 * search through the array.
1565 switch(parent->bref.type) {
1566 case HAMMER2_BREF_TYPE_INODE:
1568 * Special shortcut for embedded data returns the inode
1569 * itself. Callers must detect this condition and access
1570 * the embedded data (the strategy code does this for us).
1572 * This is only applicable to regular files and softlinks.
1574 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1575 if (flags & HAMMER2_LOOKUP_NOLOCK)
1576 hammer2_chain_ref(parent);
1578 hammer2_chain_lock(parent, how_always);
1579 *key_nextp = key_end + 1;
1582 base = &parent->data->ipdata.u.blockset.blockref[0];
1583 count = HAMMER2_SET_COUNT;
1585 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1586 case HAMMER2_BREF_TYPE_INDIRECT:
1588 * Handle MATCHIND on the parent
1590 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1591 scan_beg = parent->bref.key;
1592 scan_end = scan_beg +
1593 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1594 if (key_beg == scan_beg && key_end == scan_end) {
1596 hammer2_chain_lock(chain, how_maybe);
1597 *key_nextp = scan_end + 1;
1602 * Optimize indirect blocks in the INITIAL state to avoid
1605 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1608 if (parent->data == NULL)
1609 panic("parent->data is NULL");
1610 base = &parent->data->npdata[0];
1612 count = parent->bytes / sizeof(hammer2_blockref_t);
1614 case HAMMER2_BREF_TYPE_VOLUME:
1615 base = &hmp->voldata.sroot_blockset.blockref[0];
1616 count = HAMMER2_SET_COUNT;
1618 case HAMMER2_BREF_TYPE_FREEMAP:
1619 base = &hmp->voldata.freemap_blockset.blockref[0];
1620 count = HAMMER2_SET_COUNT;
1623 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1625 base = NULL; /* safety */
1626 count = 0; /* safety */
1630 * Merged scan to find next candidate.
1632 * hammer2_base_*() functions require the parent->core.live_* fields
1633 * to be synchronized.
1635 * We need to hold the spinlock to access the block array and RB tree
1636 * and to interlock chain creation.
1638 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1639 hammer2_chain_countbrefs(parent, base, count);
1644 hammer2_spin_ex(&parent->core.spin);
1645 chain = hammer2_combined_find(parent, base, count,
1646 cache_indexp, key_nextp,
1649 generation = parent->core.generation;
1652 * Exhausted parent chain, iterate.
1655 hammer2_spin_unex(&parent->core.spin);
1656 if (key_beg == key_end) /* short cut single-key case */
1660 * Stop if we reached the end of the iteration.
1662 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1663 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1668 * Calculate next key, stop if we reached the end of the
1669 * iteration, otherwise go up one level and loop.
1671 key_beg = parent->bref.key +
1672 ((hammer2_key_t)1 << parent->bref.keybits);
1673 if (key_beg == 0 || key_beg > key_end)
1675 parent = hammer2_chain_getparent(parentp, how_maybe);
1680 * Selected from blockref or in-memory chain.
1682 if (chain == NULL) {
1684 hammer2_spin_unex(&parent->core.spin);
1685 chain = hammer2_chain_get(parent, generation,
1687 if (chain == NULL) {
1688 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1689 parent, key_beg, key_end);
1692 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1693 hammer2_chain_drop(chain);
1697 hammer2_chain_ref(chain);
1698 hammer2_spin_unex(&parent->core.spin);
1702 * chain is referenced but not locked. We must lock the chain
1703 * to obtain definitive DUPLICATED/DELETED state
1705 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1706 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1707 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1709 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1713 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1715 * NOTE: Chain's key range is not relevant as there might be
1716 * one-offs within the range that are not deleted.
1718 * NOTE: Lookups can race delete-duplicate because
1719 * delete-duplicate does not lock the parent's core
1720 * (they just use the spinlock on the core). We must
1721 * check for races by comparing the DUPLICATED flag before
1722 * releasing the spinlock with the flag after locking the
1725 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1726 hammer2_chain_unlock(chain);
1727 key_beg = *key_nextp;
1728 if (key_beg == 0 || key_beg > key_end)
1734 * If the chain element is an indirect block it becomes the new
1735 * parent and we loop on it. We must maintain our top-down locks
1736 * to prevent the flusher from interfering (i.e. doing a
1737 * delete-duplicate and leaving us recursing down a deleted chain).
1739 * The parent always has to be locked with at least RESOLVE_MAYBE
1740 * so we can access its data. It might need a fixup if the caller
1741 * passed incompatible flags. Be careful not to cause a deadlock
1742 * as a data-load requires an exclusive lock.
1744 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1745 * range is within the requested key range we return the indirect
1746 * block and do NOT loop. This is usually only used to acquire
1749 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1750 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1751 hammer2_chain_unlock(parent);
1752 *parentp = parent = chain;
1757 * All done, return the chain
1763 * After having issued a lookup we can iterate all matching keys.
1765 * If chain is non-NULL we continue the iteration from just after it's index.
1767 * If chain is NULL we assume the parent was exhausted and continue the
1768 * iteration at the next parent.
1770 * parent must be locked on entry and remains locked throughout. chain's
1771 * lock status must match flags. Chain is always at least referenced.
1773 * WARNING! The MATCHIND flag does not apply to this function.
1776 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1777 hammer2_key_t *key_nextp,
1778 hammer2_key_t key_beg, hammer2_key_t key_end,
1779 int *cache_indexp, int flags)
1781 hammer2_chain_t *parent;
1785 * Calculate locking flags for upward recursion.
1787 how_maybe = HAMMER2_RESOLVE_MAYBE;
1788 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1789 how_maybe |= HAMMER2_RESOLVE_SHARED;
1794 * Calculate the next index and recalculate the parent if necessary.
1797 key_beg = chain->bref.key +
1798 ((hammer2_key_t)1 << chain->bref.keybits);
1799 if (flags & HAMMER2_LOOKUP_NOLOCK)
1800 hammer2_chain_drop(chain);
1802 hammer2_chain_unlock(chain);
1805 * Any scan where the lookup returned degenerate data embedded
1806 * in the inode has an invalid index and must terminate.
1808 if (chain == parent)
1810 if (key_beg == 0 || key_beg > key_end)
1813 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1814 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1816 * We reached the end of the iteration.
1821 * Continue iteration with next parent unless the current
1822 * parent covers the range.
1824 key_beg = parent->bref.key +
1825 ((hammer2_key_t)1 << parent->bref.keybits);
1826 if (key_beg == 0 || key_beg > key_end)
1828 parent = hammer2_chain_getparent(parentp, how_maybe);
1834 return (hammer2_chain_lookup(parentp, key_nextp,
1836 cache_indexp, flags));
1840 * The raw scan function is similar to lookup/next but does not seek to a key.
1841 * Blockrefs are iterated via first_chain = (parent, NULL) and
1842 * next_chain = (parent, chain).
1844 * The passed-in parent must be locked and its data resolved. The returned
1845 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1846 * under parent and then iterate with the passed-in chain (which this
1847 * function will unlock).
1850 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1851 int *cache_indexp, int flags)
1854 hammer2_blockref_t *base;
1855 hammer2_blockref_t *bref;
1856 hammer2_blockref_t bcopy;
1858 hammer2_key_t next_key;
1860 int how_always = HAMMER2_RESOLVE_ALWAYS;
1861 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1864 int maxloops = 300000;
1869 * Scan flags borrowed from lookup
1871 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1872 how_maybe = how_always;
1873 how = HAMMER2_RESOLVE_ALWAYS;
1874 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1875 how = HAMMER2_RESOLVE_NEVER;
1877 how = HAMMER2_RESOLVE_MAYBE;
1879 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1880 how_maybe |= HAMMER2_RESOLVE_SHARED;
1881 how_always |= HAMMER2_RESOLVE_SHARED;
1882 how |= HAMMER2_RESOLVE_SHARED;
1886 * Calculate key to locate first/next element, unlocking the previous
1887 * element as we go. Be careful, the key calculation can overflow.
1890 key = chain->bref.key +
1891 ((hammer2_key_t)1 << chain->bref.keybits);
1892 hammer2_chain_unlock(chain);
1901 if (--maxloops == 0)
1902 panic("hammer2_chain_scan: maxloops");
1904 * Locate the blockref array. Currently we do a fully associative
1905 * search through the array.
1907 switch(parent->bref.type) {
1908 case HAMMER2_BREF_TYPE_INODE:
1910 * An inode with embedded data has no sub-chains.
1912 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1914 base = &parent->data->ipdata.u.blockset.blockref[0];
1915 count = HAMMER2_SET_COUNT;
1917 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1918 case HAMMER2_BREF_TYPE_INDIRECT:
1920 * Optimize indirect blocks in the INITIAL state to avoid
1923 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1926 if (parent->data == NULL)
1927 panic("parent->data is NULL");
1928 base = &parent->data->npdata[0];
1930 count = parent->bytes / sizeof(hammer2_blockref_t);
1932 case HAMMER2_BREF_TYPE_VOLUME:
1933 base = &hmp->voldata.sroot_blockset.blockref[0];
1934 count = HAMMER2_SET_COUNT;
1936 case HAMMER2_BREF_TYPE_FREEMAP:
1937 base = &hmp->voldata.freemap_blockset.blockref[0];
1938 count = HAMMER2_SET_COUNT;
1941 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1943 base = NULL; /* safety */
1944 count = 0; /* safety */
1948 * Merged scan to find next candidate.
1950 * hammer2_base_*() functions require the parent->core.live_* fields
1951 * to be synchronized.
1953 * We need to hold the spinlock to access the block array and RB tree
1954 * and to interlock chain creation.
1956 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1957 hammer2_chain_countbrefs(parent, base, count);
1960 hammer2_spin_ex(&parent->core.spin);
1961 chain = hammer2_combined_find(parent, base, count,
1962 cache_indexp, &next_key,
1963 key, HAMMER2_KEY_MAX,
1965 generation = parent->core.generation;
1968 * Exhausted parent chain, we're done.
1971 hammer2_spin_unex(&parent->core.spin);
1972 KKASSERT(chain == NULL);
1977 * Selected from blockref or in-memory chain.
1979 if (chain == NULL) {
1981 hammer2_spin_unex(&parent->core.spin);
1982 chain = hammer2_chain_get(parent, generation, &bcopy);
1983 if (chain == NULL) {
1984 kprintf("retry scan parent %p keys %016jx\n",
1988 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1989 hammer2_chain_drop(chain);
1994 hammer2_chain_ref(chain);
1995 hammer2_spin_unex(&parent->core.spin);
1999 * chain is referenced but not locked. We must lock the chain
2000 * to obtain definitive DUPLICATED/DELETED state
2002 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2005 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2007 * NOTE: chain's key range is not relevant as there might be
2008 * one-offs within the range that are not deleted.
2010 * NOTE: XXX this could create problems with scans used in
2011 * situations other than mount-time recovery.
2013 * NOTE: Lookups can race delete-duplicate because
2014 * delete-duplicate does not lock the parent's core
2015 * (they just use the spinlock on the core). We must
2016 * check for races by comparing the DUPLICATED flag before
2017 * releasing the spinlock with the flag after locking the
2020 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2021 hammer2_chain_unlock(chain);
2032 * All done, return the chain or NULL
2038 * Create and return a new hammer2 system memory structure of the specified
2039 * key, type and size and insert it under (*parentp). This is a full
2040 * insertion, based on the supplied key/keybits, and may involve creating
2041 * indirect blocks and moving other chains around via delete/duplicate.
2043 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2044 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2045 * FULL. This typically means that the caller is creating the chain after
2046 * doing a hammer2_chain_lookup().
2048 * (*parentp) must be exclusive locked and may be replaced on return
2049 * depending on how much work the function had to do.
2051 * (*chainp) usually starts out NULL and returns the newly created chain,
2052 * but if the caller desires the caller may allocate a disconnected chain
2053 * and pass it in instead.
2055 * This function should NOT be used to insert INDIRECT blocks. It is
2056 * typically used to create/insert inodes and data blocks.
2058 * Caller must pass-in an exclusively locked parent the new chain is to
2059 * be inserted under, and optionally pass-in a disconnected, exclusively
2060 * locked chain to insert (else we create a new chain). The function will
2061 * adjust (*parentp) as necessary, create or connect the chain, and
2062 * return an exclusively locked chain in *chainp.
2064 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2065 * and will be reassigned.
2068 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2069 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2070 hammer2_key_t key, int keybits, int type, size_t bytes,
2074 hammer2_chain_t *chain;
2075 hammer2_chain_t *parent;
2076 hammer2_blockref_t *base;
2077 hammer2_blockref_t dummy;
2081 int maxloops = 300000;
2084 * Topology may be crossing a PFS boundary.
2087 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2091 if (chain == NULL) {
2093 * First allocate media space and construct the dummy bref,
2094 * then allocate the in-memory chain structure. Set the
2095 * INITIAL flag for fresh chains which do not have embedded
2098 bzero(&dummy, sizeof(dummy));
2101 dummy.keybits = keybits;
2102 dummy.data_off = hammer2_getradix(bytes);
2103 dummy.methods = parent->bref.methods;
2104 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2105 hammer2_chain_core_alloc(trans, chain);
2108 * Lock the chain manually, chain_lock will load the chain
2109 * which we do NOT want to do. (note: chain->refs is set
2110 * to 1 by chain_alloc() for us, but lockcnt is not).
2113 hammer2_mtx_ex(&chain->core.lock);
2117 * We do NOT set INITIAL here (yet). INITIAL is only
2118 * used for indirect blocks.
2120 * Recalculate bytes to reflect the actual media block
2123 bytes = (hammer2_off_t)1 <<
2124 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2125 chain->bytes = bytes;
2128 case HAMMER2_BREF_TYPE_VOLUME:
2129 case HAMMER2_BREF_TYPE_FREEMAP:
2130 panic("hammer2_chain_create: called with volume type");
2132 case HAMMER2_BREF_TYPE_INDIRECT:
2133 panic("hammer2_chain_create: cannot be used to"
2134 "create indirect block");
2136 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2137 panic("hammer2_chain_create: cannot be used to"
2138 "create freemap root or node");
2140 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2141 KKASSERT(bytes == sizeof(chain->data->bmdata));
2143 case HAMMER2_BREF_TYPE_INODE:
2144 case HAMMER2_BREF_TYPE_DATA:
2147 * leave chain->data NULL, set INITIAL
2149 KKASSERT(chain->data == NULL);
2150 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2155 * Set statistics for pending updates. These will be
2156 * synchronized by the flush code.
2159 case HAMMER2_BREF_TYPE_INODE:
2160 chain->inode_count = 1;
2162 case HAMMER2_BREF_TYPE_DATA:
2163 case HAMMER2_BREF_TYPE_INDIRECT:
2164 chain->data_count = chain->bytes;
2169 * We are reattaching a previously deleted chain, possibly
2170 * under a new parent and possibly with a new key/keybits.
2171 * The chain does not have to be in a modified state. The
2172 * UPDATE flag will be set later on in this routine.
2174 * Do NOT mess with the current state of the INITIAL flag.
2176 chain->bref.key = key;
2177 chain->bref.keybits = keybits;
2178 if (chain->flags & HAMMER2_CHAIN_DELETED)
2179 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2180 KKASSERT(chain->parent == NULL);
2182 if (flags & HAMMER2_INSERT_PFSROOT)
2183 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2185 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2188 * Calculate how many entries we have in the blockref array and
2189 * determine if an indirect block is required.
2192 if (--maxloops == 0)
2193 panic("hammer2_chain_create: maxloops");
2195 switch(parent->bref.type) {
2196 case HAMMER2_BREF_TYPE_INODE:
2197 KKASSERT((parent->data->ipdata.op_flags &
2198 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2199 KKASSERT(parent->data != NULL);
2200 base = &parent->data->ipdata.u.blockset.blockref[0];
2201 count = HAMMER2_SET_COUNT;
2203 case HAMMER2_BREF_TYPE_INDIRECT:
2204 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2205 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2208 base = &parent->data->npdata[0];
2209 count = parent->bytes / sizeof(hammer2_blockref_t);
2211 case HAMMER2_BREF_TYPE_VOLUME:
2212 KKASSERT(parent->data != NULL);
2213 base = &hmp->voldata.sroot_blockset.blockref[0];
2214 count = HAMMER2_SET_COUNT;
2216 case HAMMER2_BREF_TYPE_FREEMAP:
2217 KKASSERT(parent->data != NULL);
2218 base = &hmp->voldata.freemap_blockset.blockref[0];
2219 count = HAMMER2_SET_COUNT;
2222 panic("hammer2_chain_create: unrecognized blockref type: %d",
2230 * Make sure we've counted the brefs
2232 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2233 hammer2_chain_countbrefs(parent, base, count);
2235 KKASSERT(parent->core.live_count >= 0 &&
2236 parent->core.live_count <= count);
2239 * If no free blockref could be found we must create an indirect
2240 * block and move a number of blockrefs into it. With the parent
2241 * locked we can safely lock each child in order to delete+duplicate
2242 * it without causing a deadlock.
2244 * This may return the new indirect block or the old parent depending
2245 * on where the key falls. NULL is returned on error.
2247 if (parent->core.live_count == count) {
2248 hammer2_chain_t *nparent;
2250 nparent = hammer2_chain_create_indirect(trans, parent,
2253 if (nparent == NULL) {
2255 hammer2_chain_drop(chain);
2259 if (parent != nparent) {
2260 hammer2_chain_unlock(parent);
2261 parent = *parentp = nparent;
2267 * Link the chain into its parent.
2269 if (chain->parent != NULL)
2270 panic("hammer2: hammer2_chain_create: chain already connected");
2271 KKASSERT(chain->parent == NULL);
2272 hammer2_chain_insert(parent, chain,
2273 HAMMER2_CHAIN_INSERT_SPIN |
2274 HAMMER2_CHAIN_INSERT_LIVE,
2279 * Mark the newly created chain modified. This will cause
2282 * Device buffers are not instantiated for DATA elements
2283 * as these are handled by logical buffers.
2285 * Indirect and freemap node indirect blocks are handled
2286 * by hammer2_chain_create_indirect() and not by this
2289 * Data for all other bref types is expected to be
2290 * instantiated (INODE, LEAF).
2292 switch(chain->bref.type) {
2293 case HAMMER2_BREF_TYPE_DATA:
2294 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2295 case HAMMER2_BREF_TYPE_INODE:
2296 hammer2_chain_modify(trans, chain,
2297 HAMMER2_MODIFY_OPTDATA);
2301 * Remaining types are not supported by this function.
2302 * In particular, INDIRECT and LEAF_NODE types are
2303 * handled by create_indirect().
2305 panic("hammer2_chain_create: bad type: %d",
2312 * When reconnecting a chain we must set UPDATE and
2313 * setflush so the flush recognizes that it must update
2314 * the bref in the parent.
2316 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2317 hammer2_chain_ref(chain);
2318 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2320 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2321 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2322 KKASSERT(chain->data);
2323 chain->inode_count_up +=
2324 chain->data->ipdata.inode_count;
2325 chain->data_count_up +=
2326 chain->data->ipdata.data_count;
2331 * We must setflush(parent) to ensure that it recurses through to
2332 * chain. setflush(chain) might not work because ONFLUSH is possibly
2333 * already set in the chain (so it won't recurse up to set it in the
2336 hammer2_chain_setflush(trans, parent);
2345 * Move the chain from its old parent to a new parent. The chain must have
2346 * already been deleted or already disconnected (or never associated) with
2347 * a parent. The chain is reassociated with the new parent and the deleted
2348 * flag will be cleared (no longer deleted). The chain's modification state
2351 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2352 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2353 * FULL. This typically means that the caller is creating the chain after
2354 * doing a hammer2_chain_lookup().
2356 * A non-NULL bref is typically passed when key and keybits must be overridden.
2357 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2358 * from a passed-in bref and uses the old chain's bref for everything else.
2360 * If (parent) is non-NULL then the new duplicated chain is inserted under
2363 * If (parent) is NULL then the newly duplicated chain is not inserted
2364 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2365 * passing into hammer2_chain_create() after this function returns).
2367 * WARNING! This function calls create which means it can insert indirect
2368 * blocks. This can cause other unrelated chains in the parent to
2369 * be moved to a newly inserted indirect block in addition to the
2373 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2374 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2378 hammer2_chain_t *parent;
2382 * WARNING! We should never resolve DATA to device buffers
2383 * (XXX allow it if the caller did?), and since
2384 * we currently do not have the logical buffer cache
2385 * buffer in-hand to fix its cached physical offset
2386 * we also force the modify code to not COW it. XXX
2389 KKASSERT(chain->parent == NULL);
2392 * Now create a duplicate of the chain structure, associating
2393 * it with the same core, making it the same size, pointing it
2394 * to the same bref (the same media block).
2397 bref = &chain->bref;
2398 bytes = (hammer2_off_t)1 <<
2399 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2402 * If parent is not NULL the duplicated chain will be entered under
2403 * the parent and the UPDATE bit set to tell flush to update
2406 * We must setflush(parent) to ensure that it recurses through to
2407 * chain. setflush(chain) might not work because ONFLUSH is possibly
2408 * already set in the chain (so it won't recurse up to set it in the
2411 * Having both chains locked is extremely important for atomicy.
2413 if (parentp && (parent = *parentp) != NULL) {
2414 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2415 KKASSERT(parent->refs > 0);
2417 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2418 bref->key, bref->keybits, bref->type,
2419 chain->bytes, flags);
2420 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2421 hammer2_chain_setflush(trans, *parentp);
2426 * Helper function for deleting chains.
2428 * The chain is removed from the live view (the RBTREE) as well as the parent's
2429 * blockmap. Both chain and its parent must be locked.
2432 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2433 hammer2_chain_t *parent, hammer2_chain_t *chain,
2438 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2441 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2443 * Chain is blockmapped, so there must be a parent.
2444 * Atomically remove the chain from the parent and remove
2445 * the blockmap entry.
2447 hammer2_blockref_t *base;
2450 KKASSERT(parent != NULL);
2451 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2452 hammer2_chain_modify(trans, parent,
2453 HAMMER2_MODIFY_OPTDATA);
2456 * Calculate blockmap pointer
2458 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2459 hammer2_spin_ex(&parent->core.spin);
2461 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2462 atomic_add_int(&parent->core.live_count, -1);
2463 ++parent->core.generation;
2464 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2465 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2466 --parent->core.chain_count;
2467 chain->parent = NULL;
2469 switch(parent->bref.type) {
2470 case HAMMER2_BREF_TYPE_INODE:
2472 * Access the inode's block array. However, there
2473 * is no block array if the inode is flagged
2474 * DIRECTDATA. The DIRECTDATA case typicaly only
2475 * occurs when a hardlink has been shifted up the
2476 * tree and the original inode gets replaced with
2477 * an OBJTYPE_HARDLINK placeholding inode.
2480 (parent->data->ipdata.op_flags &
2481 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2483 &parent->data->ipdata.u.blockset.blockref[0];
2487 count = HAMMER2_SET_COUNT;
2489 case HAMMER2_BREF_TYPE_INDIRECT:
2490 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2492 base = &parent->data->npdata[0];
2495 count = parent->bytes / sizeof(hammer2_blockref_t);
2497 case HAMMER2_BREF_TYPE_VOLUME:
2498 base = &hmp->voldata.sroot_blockset.blockref[0];
2499 count = HAMMER2_SET_COUNT;
2501 case HAMMER2_BREF_TYPE_FREEMAP:
2502 base = &parent->data->npdata[0];
2503 count = HAMMER2_SET_COUNT;
2508 panic("hammer2_flush_pass2: "
2509 "unrecognized blockref type: %d",
2514 * delete blockmapped chain from its parent.
2516 * The parent is not affected by any statistics in chain
2517 * which are pending synchronization. That is, there is
2518 * nothing to undo in the parent since they have not yet
2519 * been incorporated into the parent.
2521 * The parent is affected by statistics stored in inodes.
2522 * Those have already been synchronized, so they must be
2523 * undone. XXX split update possible w/delete in middle?
2526 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2527 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2528 KKASSERT(chain->data != NULL);
2529 parent->data_count -=
2530 chain->data->ipdata.data_count;
2531 parent->inode_count -=
2532 chain->data->ipdata.inode_count;
2535 int cache_index = -1;
2536 hammer2_base_delete(trans, parent, base, count,
2537 &cache_index, chain);
2539 hammer2_spin_unex(&parent->core.spin);
2540 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2542 * Chain is not blockmapped but a parent is present.
2543 * Atomically remove the chain from the parent. There is
2544 * no blockmap entry to remove.
2546 * Because chain was associated with a parent but not
2547 * synchronized, the chain's *_count_up fields contain
2548 * inode adjustment statistics which must be undone.
2550 hammer2_spin_ex(&parent->core.spin);
2551 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2552 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2553 KKASSERT(chain->data != NULL);
2554 chain->data_count_up -=
2555 chain->data->ipdata.data_count;
2556 chain->inode_count_up -=
2557 chain->data->ipdata.inode_count;
2559 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2560 atomic_add_int(&parent->core.live_count, -1);
2561 ++parent->core.generation;
2562 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2563 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2564 --parent->core.chain_count;
2565 chain->parent = NULL;
2566 hammer2_spin_unex(&parent->core.spin);
2569 * Chain is not blockmapped and has no parent. This
2570 * is a degenerate case.
2572 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2577 * If the deletion is permanent (i.e. the chain is not simply being
2578 * moved within the topology), adjust the freemap to indicate that
2579 * the block *might* be freeable. bulkfree must still determine
2580 * that it is actually freeable.
2582 * We no longer do this in the normal filesystem operations path
2583 * as it interferes with the bulkfree algorithm.
2585 if ((flags & HAMMER2_DELETE_PERMANENT) &&
2586 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2587 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
2588 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
2589 hammer2_freemap_adjust(trans, hmp, &chain->bref,
2590 HAMMER2_FREEMAP_DOMAYFREE);
2596 * Create an indirect block that covers one or more of the elements in the
2597 * current parent. Either returns the existing parent with no locking or
2598 * ref changes or returns the new indirect block locked and referenced
2599 * and leaving the original parent lock/ref intact as well.
2601 * If an error occurs, NULL is returned and *errorp is set to the error.
2603 * The returned chain depends on where the specified key falls.
2605 * The key/keybits for the indirect mode only needs to follow three rules:
2607 * (1) That all elements underneath it fit within its key space and
2609 * (2) That all elements outside it are outside its key space.
2611 * (3) When creating the new indirect block any elements in the current
2612 * parent that fit within the new indirect block's keyspace must be
2613 * moved into the new indirect block.
2615 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2616 * keyspace the the current parent, but lookup/iteration rules will
2617 * ensure (and must ensure) that rule (2) for all parents leading up
2618 * to the nearest inode or the root volume header is adhered to. This
2619 * is accomplished by always recursing through matching keyspaces in
2620 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2622 * The current implementation calculates the current worst-case keyspace by
2623 * iterating the current parent and then divides it into two halves, choosing
2624 * whichever half has the most elements (not necessarily the half containing
2625 * the requested key).
2627 * We can also opt to use the half with the least number of elements. This
2628 * causes lower-numbered keys (aka logical file offsets) to recurse through
2629 * fewer indirect blocks and higher-numbered keys to recurse through more.
2630 * This also has the risk of not moving enough elements to the new indirect
2631 * block and being forced to create several indirect blocks before the element
2634 * Must be called with an exclusively locked parent.
2636 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2637 hammer2_key_t *keyp, int keybits,
2638 hammer2_blockref_t *base, int count);
2639 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2640 hammer2_key_t *keyp, int keybits,
2641 hammer2_blockref_t *base, int count);
2644 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2645 hammer2_key_t create_key, int create_bits,
2646 int for_type, int *errorp)
2649 hammer2_blockref_t *base;
2650 hammer2_blockref_t *bref;
2651 hammer2_blockref_t bcopy;
2652 hammer2_chain_t *chain;
2653 hammer2_chain_t *ichain;
2654 hammer2_chain_t dummy;
2655 hammer2_key_t key = create_key;
2656 hammer2_key_t key_beg;
2657 hammer2_key_t key_end;
2658 hammer2_key_t key_next;
2659 int keybits = create_bits;
2666 int maxloops = 300000;
2669 * Calculate the base blockref pointer or NULL if the chain
2670 * is known to be empty. We need to calculate the array count
2671 * for RB lookups either way.
2675 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2677 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2678 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2681 switch(parent->bref.type) {
2682 case HAMMER2_BREF_TYPE_INODE:
2683 count = HAMMER2_SET_COUNT;
2685 case HAMMER2_BREF_TYPE_INDIRECT:
2686 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2687 count = parent->bytes / sizeof(hammer2_blockref_t);
2689 case HAMMER2_BREF_TYPE_VOLUME:
2690 count = HAMMER2_SET_COUNT;
2692 case HAMMER2_BREF_TYPE_FREEMAP:
2693 count = HAMMER2_SET_COUNT;
2696 panic("hammer2_chain_create_indirect: "
2697 "unrecognized blockref type: %d",
2703 switch(parent->bref.type) {
2704 case HAMMER2_BREF_TYPE_INODE:
2705 base = &parent->data->ipdata.u.blockset.blockref[0];
2706 count = HAMMER2_SET_COUNT;
2708 case HAMMER2_BREF_TYPE_INDIRECT:
2709 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2710 base = &parent->data->npdata[0];
2711 count = parent->bytes / sizeof(hammer2_blockref_t);
2713 case HAMMER2_BREF_TYPE_VOLUME:
2714 base = &hmp->voldata.sroot_blockset.blockref[0];
2715 count = HAMMER2_SET_COUNT;
2717 case HAMMER2_BREF_TYPE_FREEMAP:
2718 base = &hmp->voldata.freemap_blockset.blockref[0];
2719 count = HAMMER2_SET_COUNT;
2722 panic("hammer2_chain_create_indirect: "
2723 "unrecognized blockref type: %d",
2731 * dummy used in later chain allocation (no longer used for lookups).
2733 bzero(&dummy, sizeof(dummy));
2736 * When creating an indirect block for a freemap node or leaf
2737 * the key/keybits must be fitted to static radix levels because
2738 * particular radix levels use particular reserved blocks in the
2741 * This routine calculates the key/radix of the indirect block
2742 * we need to create, and whether it is on the high-side or the
2745 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2746 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2747 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2750 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2755 * Normalize the key for the radix being represented, keeping the
2756 * high bits and throwing away the low bits.
2758 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2761 * How big should our new indirect block be? It has to be at least
2762 * as large as its parent.
2764 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2765 nbytes = HAMMER2_IND_BYTES_MIN;
2767 nbytes = HAMMER2_IND_BYTES_MAX;
2768 if (nbytes < count * sizeof(hammer2_blockref_t))
2769 nbytes = count * sizeof(hammer2_blockref_t);
2772 * Ok, create our new indirect block
2774 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2775 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2776 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2778 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2780 dummy.bref.key = key;
2781 dummy.bref.keybits = keybits;
2782 dummy.bref.data_off = hammer2_getradix(nbytes);
2783 dummy.bref.methods = parent->bref.methods;
2785 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2786 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2787 hammer2_chain_core_alloc(trans, ichain);
2788 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2789 hammer2_chain_drop(ichain); /* excess ref from alloc */
2792 * We have to mark it modified to allocate its block, but use
2793 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2794 * it won't be acted upon by the flush code.
2796 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2799 * Iterate the original parent and move the matching brefs into
2800 * the new indirect block.
2802 * XXX handle flushes.
2805 key_end = HAMMER2_KEY_MAX;
2807 hammer2_spin_ex(&parent->core.spin);
2812 if (++loops > 100000) {
2813 hammer2_spin_unex(&parent->core.spin);
2814 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2815 reason, parent, base, count, key_next);
2819 * NOTE: spinlock stays intact, returned chain (if not NULL)
2820 * is not referenced or locked which means that we
2821 * cannot safely check its flagged / deletion status
2824 chain = hammer2_combined_find(parent, base, count,
2825 &cache_index, &key_next,
2828 generation = parent->core.generation;
2831 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2834 * Skip keys that are not within the key/radix of the new
2835 * indirect block. They stay in the parent.
2837 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2838 (key ^ bref->key)) != 0) {
2839 goto next_key_spinlocked;
2843 * Load the new indirect block by acquiring the related
2844 * chains (potentially from media as it might not be
2845 * in-memory). Then move it to the new parent (ichain)
2846 * via DELETE-DUPLICATE.
2848 * chain is referenced but not locked. We must lock the
2849 * chain to obtain definitive DUPLICATED/DELETED state
2853 * Use chain already present in the RBTREE
2855 hammer2_chain_ref(chain);
2856 hammer2_spin_unex(&parent->core.spin);
2857 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2858 HAMMER2_RESOLVE_NOREF);
2861 * Get chain for blockref element. _get returns NULL
2862 * on insertion race.
2865 hammer2_spin_unex(&parent->core.spin);
2866 chain = hammer2_chain_get(parent, generation, &bcopy);
2867 if (chain == NULL) {
2869 hammer2_spin_ex(&parent->core.spin);
2872 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2873 kprintf("REASON 2\n");
2875 hammer2_chain_drop(chain);
2876 hammer2_spin_ex(&parent->core.spin);
2879 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2880 HAMMER2_RESOLVE_NOREF);
2884 * This is always live so if the chain has been deleted
2885 * we raced someone and we have to retry.
2887 * NOTE: Lookups can race delete-duplicate because
2888 * delete-duplicate does not lock the parent's core
2889 * (they just use the spinlock on the core). We must
2890 * check for races by comparing the DUPLICATED flag before
2891 * releasing the spinlock with the flag after locking the
2894 * (note reversed logic for this one)
2896 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2897 hammer2_chain_unlock(chain);
2902 * Shift the chain to the indirect block.
2904 * WARNING! No reason for us to load chain data, pass NOSTATS
2905 * to prevent delete/insert from trying to access
2906 * inode stats (and thus asserting if there is no
2907 * chain->data loaded).
2909 hammer2_chain_delete(trans, parent, chain,
2910 HAMMER2_DELETE_NOSTATS);
2911 hammer2_chain_rename(trans, NULL, &ichain, chain,
2912 HAMMER2_INSERT_NOSTATS);
2913 hammer2_chain_unlock(chain);
2914 KKASSERT(parent->refs > 0);
2917 hammer2_spin_ex(&parent->core.spin);
2918 next_key_spinlocked:
2919 if (--maxloops == 0)
2920 panic("hammer2_chain_create_indirect: maxloops");
2922 if (key_next == 0 || key_next > key_end)
2927 hammer2_spin_unex(&parent->core.spin);
2930 * Insert the new indirect block into the parent now that we've
2931 * cleared out some entries in the parent. We calculated a good
2932 * insertion index in the loop above (ichain->index).
2934 * We don't have to set UPDATE here because we mark ichain
2935 * modified down below (so the normal modified -> flush -> set-moved
2936 * sequence applies).
2938 * The insertion shouldn't race as this is a completely new block
2939 * and the parent is locked.
2941 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2942 hammer2_chain_insert(parent, ichain,
2943 HAMMER2_CHAIN_INSERT_SPIN |
2944 HAMMER2_CHAIN_INSERT_LIVE,
2948 * Make sure flushes propogate after our manual insertion.
2950 hammer2_chain_setflush(trans, ichain);
2951 hammer2_chain_setflush(trans, parent);
2954 * Figure out what to return.
2956 if (~(((hammer2_key_t)1 << keybits) - 1) &
2957 (create_key ^ key)) {
2959 * Key being created is outside the key range,
2960 * return the original parent.
2962 hammer2_chain_unlock(ichain);
2965 * Otherwise its in the range, return the new parent.
2966 * (leave both the new and old parent locked).
2975 * Calculate the keybits and highside/lowside of the freemap node the
2976 * caller is creating.
2978 * This routine will specify the next higher-level freemap key/radix
2979 * representing the lowest-ordered set. By doing so, eventually all
2980 * low-ordered sets will be moved one level down.
2982 * We have to be careful here because the freemap reserves a limited
2983 * number of blocks for a limited number of levels. So we can't just
2984 * push indiscriminately.
2987 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2988 int keybits, hammer2_blockref_t *base, int count)
2990 hammer2_chain_t *chain;
2991 hammer2_blockref_t *bref;
2993 hammer2_key_t key_beg;
2994 hammer2_key_t key_end;
2995 hammer2_key_t key_next;
2999 int maxloops = 300000;
3007 * Calculate the range of keys in the array being careful to skip
3008 * slots which are overridden with a deletion.
3011 key_end = HAMMER2_KEY_MAX;
3013 hammer2_spin_ex(&parent->core.spin);
3016 if (--maxloops == 0) {
3017 panic("indkey_freemap shit %p %p:%d\n",
3018 parent, base, count);
3020 chain = hammer2_combined_find(parent, base, count,
3021 &cache_index, &key_next,
3032 * Skip deleted chains.
3034 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3035 if (key_next == 0 || key_next > key_end)
3042 * Use the full live (not deleted) element for the scan
3043 * iteration. HAMMER2 does not allow partial replacements.
3045 * XXX should be built into hammer2_combined_find().
3047 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3049 if (keybits > bref->keybits) {
3051 keybits = bref->keybits;
3052 } else if (keybits == bref->keybits && bref->key < key) {
3059 hammer2_spin_unex(&parent->core.spin);
3062 * Return the keybits for a higher-level FREEMAP_NODE covering
3066 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3067 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3069 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3070 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3072 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3073 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3075 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3076 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3078 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3079 panic("hammer2_chain_indkey_freemap: level too high");
3082 panic("hammer2_chain_indkey_freemap: bad radix");
3091 * Calculate the keybits and highside/lowside of the indirect block the
3092 * caller is creating.
3095 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3096 int keybits, hammer2_blockref_t *base, int count)
3098 hammer2_blockref_t *bref;
3099 hammer2_chain_t *chain;
3100 hammer2_key_t key_beg;
3101 hammer2_key_t key_end;
3102 hammer2_key_t key_next;
3108 int maxloops = 300000;
3115 * Calculate the range of keys in the array being careful to skip
3116 * slots which are overridden with a deletion. Once the scan
3117 * completes we will cut the key range in half and shift half the
3118 * range into the new indirect block.
3121 key_end = HAMMER2_KEY_MAX;
3123 hammer2_spin_ex(&parent->core.spin);
3126 if (--maxloops == 0) {
3127 panic("indkey_freemap shit %p %p:%d\n",
3128 parent, base, count);
3130 chain = hammer2_combined_find(parent, base, count,
3131 &cache_index, &key_next,
3142 * NOTE: No need to check DUPLICATED here because we do
3143 * not release the spinlock.
3145 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3146 if (key_next == 0 || key_next > key_end)
3153 * Use the full live (not deleted) element for the scan
3154 * iteration. HAMMER2 does not allow partial replacements.
3156 * XXX should be built into hammer2_combined_find().
3158 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3161 * Expand our calculated key range (key, keybits) to fit
3162 * the scanned key. nkeybits represents the full range
3163 * that we will later cut in half (two halves @ nkeybits - 1).
3166 if (nkeybits < bref->keybits) {
3167 if (bref->keybits > 64) {
3168 kprintf("bad bref chain %p bref %p\n",
3172 nkeybits = bref->keybits;
3174 while (nkeybits < 64 &&
3175 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3176 (key ^ bref->key)) != 0) {
3181 * If the new key range is larger we have to determine
3182 * which side of the new key range the existing keys fall
3183 * under by checking the high bit, then collapsing the
3184 * locount into the hicount or vise-versa.
3186 if (keybits != nkeybits) {
3187 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3198 * The newly scanned key will be in the lower half or the
3199 * upper half of the (new) key range.
3201 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3210 hammer2_spin_unex(&parent->core.spin);
3211 bref = NULL; /* now invalid (safety) */
3214 * Adjust keybits to represent half of the full range calculated
3215 * above (radix 63 max)
3220 * Select whichever half contains the most elements. Theoretically
3221 * we can select either side as long as it contains at least one
3222 * element (in order to ensure that a free slot is present to hold
3223 * the indirect block).
3225 if (hammer2_indirect_optimize) {
3227 * Insert node for least number of keys, this will arrange
3228 * the first few blocks of a large file or the first few
3229 * inodes in a directory with fewer indirect blocks when
3232 if (hicount < locount && hicount != 0)
3233 key |= (hammer2_key_t)1 << keybits;
3235 key &= ~(hammer2_key_t)1 << keybits;
3238 * Insert node for most number of keys, best for heavily
3241 if (hicount > locount)
3242 key |= (hammer2_key_t)1 << keybits;
3244 key &= ~(hammer2_key_t)1 << keybits;
3252 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3255 * Both parent and chain must be locked exclusively.
3257 * This function will modify the parent if the blockref requires removal
3258 * from the parent's block table.
3260 * This function is NOT recursive. Any entity already pushed into the
3261 * chain (such as an inode) may still need visibility into its contents,
3262 * as well as the ability to read and modify the contents. For example,
3263 * for an unlinked file which is still open.
3266 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3267 hammer2_chain_t *chain, int flags)
3269 KKASSERT(hammer2_mtx_owned(&chain->core.lock));
3272 * Nothing to do if already marked.
3274 * We need the spinlock on the core whos RBTREE contains chain
3275 * to protect against races.
3277 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3278 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3279 chain->parent == parent);
3280 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3283 if (flags & HAMMER2_DELETE_PERMANENT) {
3284 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3285 hammer2_flush(trans, chain);
3287 /* XXX might not be needed */
3288 hammer2_chain_setflush(trans, chain);
3293 * Returns the index of the nearest element in the blockref array >= elm.
3294 * Returns (count) if no element could be found.
3296 * Sets *key_nextp to the next key for loop purposes but does not modify
3297 * it if the next key would be higher than the current value of *key_nextp.
3298 * Note that *key_nexp can overflow to 0, which should be tested by the
3301 * (*cache_indexp) is a heuristic and can be any value without effecting
3304 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3305 * held through the operation.
3308 hammer2_base_find(hammer2_chain_t *parent,
3309 hammer2_blockref_t *base, int count,
3310 int *cache_indexp, hammer2_key_t *key_nextp,
3311 hammer2_key_t key_beg, hammer2_key_t key_end)
3313 hammer2_blockref_t *scan;
3314 hammer2_key_t scan_end;
3319 * Require the live chain's already have their core's counted
3320 * so we can optimize operations.
3322 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3327 if (count == 0 || base == NULL)
3331 * Sequential optimization using *cache_indexp. This is the most
3334 * We can avoid trailing empty entries on live chains, otherwise
3335 * we might have to check the whole block array.
3339 limit = parent->core.live_zero;
3344 KKASSERT(i < count);
3350 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3357 * Search forwards, stop when we find a scan element which
3358 * encloses the key or until we know that there are no further
3362 if (scan->type != 0) {
3363 scan_end = scan->key +
3364 ((hammer2_key_t)1 << scan->keybits) - 1;
3365 if (scan->key > key_beg || scan_end >= key_beg)
3378 scan_end = scan->key +
3379 ((hammer2_key_t)1 << scan->keybits);
3380 if (scan_end && (*key_nextp > scan_end ||
3382 *key_nextp = scan_end;
3390 * Do a combined search and return the next match either from the blockref
3391 * array or from the in-memory chain. Sets *bresp to the returned bref in
3392 * both cases, or sets it to NULL if the search exhausted. Only returns
3393 * a non-NULL chain if the search matched from the in-memory chain.
3395 * When no in-memory chain has been found and a non-NULL bref is returned
3399 * The returned chain is not locked or referenced. Use the returned bref
3400 * to determine if the search exhausted or not. Iterate if the base find
3401 * is chosen but matches a deleted chain.
3403 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3404 * held through the operation.
3406 static hammer2_chain_t *
3407 hammer2_combined_find(hammer2_chain_t *parent,
3408 hammer2_blockref_t *base, int count,
3409 int *cache_indexp, hammer2_key_t *key_nextp,
3410 hammer2_key_t key_beg, hammer2_key_t key_end,
3411 hammer2_blockref_t **bresp)
3413 hammer2_blockref_t *bref;
3414 hammer2_chain_t *chain;
3418 * Lookup in block array and in rbtree.
3420 *key_nextp = key_end + 1;
3421 i = hammer2_base_find(parent, base, count, cache_indexp,
3422 key_nextp, key_beg, key_end);
3423 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3428 if (i == count && chain == NULL) {
3434 * Only chain matched.
3437 bref = &chain->bref;
3442 * Only blockref matched.
3444 if (chain == NULL) {
3450 * Both in-memory and blockref matched, select the nearer element.
3452 * If both are flush with the left-hand side or both are the
3453 * same distance away, select the chain. In this situation the
3454 * chain must have been loaded from the matching blockmap.
3456 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3457 chain->bref.key == base[i].key) {
3458 KKASSERT(chain->bref.key == base[i].key);
3459 bref = &chain->bref;
3464 * Select the nearer key
3466 if (chain->bref.key < base[i].key) {
3467 bref = &chain->bref;
3474 * If the bref is out of bounds we've exhausted our search.
3477 if (bref->key > key_end) {
3487 * Locate the specified block array element and delete it. The element
3490 * The spin lock on the related chain must be held.
3492 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3493 * need to be adjusted when we commit the media change.
3496 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3497 hammer2_blockref_t *base, int count,
3498 int *cache_indexp, hammer2_chain_t *chain)
3500 hammer2_blockref_t *elm = &chain->bref;
3501 hammer2_key_t key_next;
3505 * Delete element. Expect the element to exist.
3507 * XXX see caller, flush code not yet sophisticated enough to prevent
3508 * re-flushed in some cases.
3510 key_next = 0; /* max range */
3511 i = hammer2_base_find(parent, base, count, cache_indexp,
3512 &key_next, elm->key, elm->key);
3513 if (i == count || base[i].type == 0 ||
3514 base[i].key != elm->key ||
3515 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3516 base[i].keybits != elm->keybits)) {
3517 hammer2_spin_unex(&parent->core.spin);
3518 panic("delete base %p element not found at %d/%d elm %p\n",
3519 base, i, count, elm);
3522 bzero(&base[i], sizeof(*base));
3525 * We can only optimize parent->core.live_zero for live chains.
3527 if (parent->core.live_zero == i + 1) {
3528 while (--i >= 0 && base[i].type == 0)
3530 parent->core.live_zero = i + 1;
3534 * Clear appropriate blockmap flags in chain.
3536 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3537 HAMMER2_CHAIN_BMAPUPD);
3541 * Insert the specified element. The block array must not already have the
3542 * element and must have space available for the insertion.
3544 * The spin lock on the related chain must be held.
3546 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3547 * need to be adjusted when we commit the media change.
3550 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3551 hammer2_blockref_t *base, int count,
3552 int *cache_indexp, hammer2_chain_t *chain)
3554 hammer2_blockref_t *elm = &chain->bref;
3555 hammer2_key_t key_next;
3564 * Insert new element. Expect the element to not already exist
3565 * unless we are replacing it.
3567 * XXX see caller, flush code not yet sophisticated enough to prevent
3568 * re-flushed in some cases.
3570 key_next = 0; /* max range */
3571 i = hammer2_base_find(parent, base, count, cache_indexp,
3572 &key_next, elm->key, elm->key);
3575 * Shortcut fill optimization, typical ordered insertion(s) may not
3578 KKASSERT(i >= 0 && i <= count);
3581 * Set appropriate blockmap flags in chain.
3583 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3586 * We can only optimize parent->core.live_zero for live chains.
3588 if (i == count && parent->core.live_zero < count) {
3589 i = parent->core.live_zero++;
3594 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3595 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3596 hammer2_spin_unex(&parent->core.spin);
3597 panic("insert base %p overlapping elements at %d elm %p\n",
3602 * Try to find an empty slot before or after.
3606 while (j > 0 || k < count) {
3608 if (j >= 0 && base[j].type == 0) {
3612 bcopy(&base[j+1], &base[j],
3613 (i - j - 1) * sizeof(*base));
3619 if (k < count && base[k].type == 0) {
3620 bcopy(&base[i], &base[i+1],
3621 (k - i) * sizeof(hammer2_blockref_t));
3625 * We can only update parent->core.live_zero for live
3628 if (parent->core.live_zero <= k)
3629 parent->core.live_zero = k + 1;
3634 panic("hammer2_base_insert: no room!");
3641 for (l = 0; l < count; ++l) {
3643 key_next = base[l].key +
3644 ((hammer2_key_t)1 << base[l].keybits) - 1;
3648 while (++l < count) {
3650 if (base[l].key <= key_next)
3651 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3652 key_next = base[l].key +
3653 ((hammer2_key_t)1 << base[l].keybits) - 1;
3663 * Sort the blockref array for the chain. Used by the flush code to
3664 * sort the blockref[] array.
3666 * The chain must be exclusively locked AND spin-locked.
3668 typedef hammer2_blockref_t *hammer2_blockref_p;
3672 hammer2_base_sort_callback(const void *v1, const void *v2)
3674 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3675 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3678 * Make sure empty elements are placed at the end of the array
3680 if (bref1->type == 0) {
3681 if (bref2->type == 0)
3684 } else if (bref2->type == 0) {
3691 if (bref1->key < bref2->key)
3693 if (bref1->key > bref2->key)
3699 hammer2_base_sort(hammer2_chain_t *chain)
3701 hammer2_blockref_t *base;
3704 switch(chain->bref.type) {
3705 case HAMMER2_BREF_TYPE_INODE:
3707 * Special shortcut for embedded data returns the inode
3708 * itself. Callers must detect this condition and access
3709 * the embedded data (the strategy code does this for us).
3711 * This is only applicable to regular files and softlinks.
3713 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3715 base = &chain->data->ipdata.u.blockset.blockref[0];
3716 count = HAMMER2_SET_COUNT;
3718 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3719 case HAMMER2_BREF_TYPE_INDIRECT:
3721 * Optimize indirect blocks in the INITIAL state to avoid
3724 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3725 base = &chain->data->npdata[0];
3726 count = chain->bytes / sizeof(hammer2_blockref_t);
3728 case HAMMER2_BREF_TYPE_VOLUME:
3729 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3730 count = HAMMER2_SET_COUNT;
3732 case HAMMER2_BREF_TYPE_FREEMAP:
3733 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3734 count = HAMMER2_SET_COUNT;
3737 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3739 base = NULL; /* safety */
3740 count = 0; /* safety */
3742 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3748 * Chain memory management
3751 hammer2_chain_wait(hammer2_chain_t *chain)
3753 tsleep(chain, 0, "chnflw", 1);
3756 const hammer2_media_data_t *
3757 hammer2_chain_rdata(hammer2_chain_t *chain)
3759 KKASSERT(chain->data != NULL);
3760 return (chain->data);
3763 hammer2_media_data_t *
3764 hammer2_chain_wdata(hammer2_chain_t *chain)
3766 KKASSERT(chain->data != NULL);
3767 return (chain->data);
3771 * Set the check data for a chain. This can be a heavy-weight operation
3772 * and typically only runs on-flush. For file data check data is calculated
3773 * when the logical buffers are flushed.
3776 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3778 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3780 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3781 case HAMMER2_CHECK_NONE:
3783 case HAMMER2_CHECK_DISABLED:
3785 case HAMMER2_CHECK_ISCSI32:
3786 chain->bref.check.iscsi32.value =
3787 hammer2_icrc32(bdata, chain->bytes);
3789 case HAMMER2_CHECK_CRC64:
3790 chain->bref.check.crc64.value = 0;
3793 case HAMMER2_CHECK_SHA192:
3795 SHA256_CTX hash_ctx;
3797 uint8_t digest[SHA256_DIGEST_LENGTH];
3798 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3801 SHA256_Init(&hash_ctx);
3802 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3803 SHA256_Final(u.digest, &hash_ctx);
3804 u.digest64[2] ^= u.digest64[3];
3806 chain->bref.check.sha192.data,
3807 sizeof(chain->bref.check.sha192.data));
3810 case HAMMER2_CHECK_FREEMAP:
3811 chain->bref.check.freemap.icrc32 =
3812 hammer2_icrc32(bdata, chain->bytes);
3815 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3816 chain->bref.methods);
3822 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3826 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3829 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3830 case HAMMER2_CHECK_NONE:
3833 case HAMMER2_CHECK_DISABLED:
3836 case HAMMER2_CHECK_ISCSI32:
3837 r = (chain->bref.check.iscsi32.value ==
3838 hammer2_icrc32(bdata, chain->bytes));
3840 case HAMMER2_CHECK_CRC64:
3841 r = (chain->bref.check.crc64.value == 0);
3844 case HAMMER2_CHECK_SHA192:
3846 SHA256_CTX hash_ctx;
3848 uint8_t digest[SHA256_DIGEST_LENGTH];
3849 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3852 SHA256_Init(&hash_ctx);
3853 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3854 SHA256_Final(u.digest, &hash_ctx);
3855 u.digest64[2] ^= u.digest64[3];
3857 chain->bref.check.sha192.data,
3858 sizeof(chain->bref.check.sha192.data)) == 0) {
3865 case HAMMER2_CHECK_FREEMAP:
3866 r = (chain->bref.check.freemap.icrc32 ==
3867 hammer2_icrc32(bdata, chain->bytes));
3869 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3870 chain->bref.check.freemap.icrc32,
3871 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3873 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3874 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3879 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3880 chain->bref.methods);