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 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 volume root.
134 * This routine sets ONFLUSH upward until it hits the volume root. For
135 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
136 * Extra ONFLUSH flagging doesn't hurt the filesystem.
139 hammer2_chain_setflush(hammer2_trans_t *trans, hammer2_chain_t *chain)
141 hammer2_chain_t *parent;
143 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
144 hammer2_spin_sh(&chain->core.spin);
145 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
146 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
147 if ((parent = chain->parent) == NULL)
149 hammer2_spin_sh(&parent->core.spin);
150 hammer2_spin_unsh(&chain->core.spin);
153 hammer2_spin_unsh(&chain->core.spin);
158 * Allocate a new disconnected chain element representing the specified
159 * bref. chain->refs is set to 1 and the passed bref is copied to
160 * chain->bref. chain->bytes is derived from the bref.
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. pmp must be set to NULL for
202 * chains belonging to the super-root topology of a device mount.
204 if (pmp == hmp->spmp)
210 chain->bytes = bytes;
212 chain->flags = HAMMER2_CHAIN_ALLOCATED;
215 * Set the PFS boundary flag if this chain represents a PFS root.
217 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
218 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
219 hammer2_chain_core_init(chain);
225 * Initialize a chain's core structure. This structure used to be allocated
226 * but is now embedded.
228 * The core is not locked. No additional refs on the chain are made.
229 * (trans) must not be NULL if (core) is not NULL.
232 hammer2_chain_core_init(hammer2_chain_t *chain)
235 * Fresh core under nchain (no multi-homing of ochain's
238 RB_INIT(&chain->core.rbtree); /* live chains */
239 hammer2_mtx_init(&chain->lock, "h2chain");
243 * Add a reference to a chain element, preventing its destruction.
245 * (can be called with spinlock held)
248 hammer2_chain_ref(hammer2_chain_t *chain)
250 atomic_add_int(&chain->refs, 1);
252 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
258 * Insert the chain in the core rbtree.
260 * Normal insertions are placed in the live rbtree. Insertion of a deleted
261 * chain is a special case used by the flush code that is placed on the
262 * unstaged deleted list to avoid confusing the live view.
264 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
265 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
266 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
270 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
271 int flags, int generation)
273 hammer2_chain_t *xchain;
276 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
277 hammer2_spin_ex(&parent->core.spin);
280 * Interlocked by spinlock, check for race
282 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
283 parent->core.generation != generation) {
291 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
292 KASSERT(xchain == NULL,
293 ("hammer2_chain_insert: collision %p %p", chain, xchain));
294 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
295 chain->parent = parent;
296 ++parent->core.chain_count;
297 ++parent->core.generation; /* XXX incs for _get() too, XXX */
300 * We have to keep track of the effective live-view blockref count
301 * so the create code knows when to push an indirect block.
303 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
304 atomic_add_int(&parent->core.live_count, 1);
306 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
307 hammer2_spin_unex(&parent->core.spin);
312 * Drop the caller's reference to the chain. When the ref count drops to
313 * zero this function will try to disassociate the chain from its parent and
314 * deallocate it, then recursely drop the parent using the implied ref
315 * from the chain's chain->parent.
317 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
320 hammer2_chain_drop(hammer2_chain_t *chain)
325 if (hammer2_debug & 0x200000)
328 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
332 if (chain->flags & HAMMER2_CHAIN_UPDATE)
334 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
336 KKASSERT(chain->refs > need);
344 chain = hammer2_chain_lastdrop(chain);
346 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
348 /* retry the same chain */
354 * Safe handling of the 1->0 transition on chain. Returns a chain for
355 * recursive drop or NULL, possibly returning the same chain if the atomic
358 * Whem two chains need to be recursively dropped we use the chain
359 * we would otherwise free to placehold the additional chain. It's a bit
360 * convoluted but we can't just recurse without potentially blowing out
363 * The chain cannot be freed if it has any children.
365 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
369 hammer2_chain_lastdrop(hammer2_chain_t *chain)
373 hammer2_chain_t *parent;
374 hammer2_chain_t *rdrop;
377 * Spinlock the core and check to see if it is empty. If it is
378 * not empty we leave chain intact with refs == 0. The elements
379 * in core->rbtree are associated with other chains contemporary
380 * with ours but not with our chain directly.
382 hammer2_spin_ex(&chain->core.spin);
385 * We can't free non-stale chains with children until we are
386 * able to free the children because there might be a flush
387 * dependency. Flushes of stale children (which should also
388 * have their deleted flag set) short-cut recursive flush
389 * dependencies and can be freed here. Any flushes which run
390 * through stale children due to the flush synchronization
391 * point should have a FLUSH_* bit set in the chain and not
392 * reach lastdrop at this time.
394 * NOTE: We return (chain) on failure to retry.
396 if (chain->core.chain_count) {
397 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
398 hammer2_spin_unex(&chain->core.spin);
399 chain = NULL; /* success */
401 hammer2_spin_unex(&chain->core.spin);
405 /* no chains left under us */
408 * chain->core has no children left so no accessors can get to our
409 * chain from there. Now we have to lock the parent core to interlock
410 * remaining possible accessors that might bump chain's refs before
411 * we can safely drop chain's refs with intent to free the chain.
414 pmp = chain->pmp; /* can be NULL */
418 * Spinlock the parent and try to drop the last ref on chain.
419 * On success remove chain from its parent, otherwise return NULL.
421 * (normal core locks are top-down recursive but we define core
422 * spinlocks as bottom-up recursive, so this is safe).
424 if ((parent = chain->parent) != NULL) {
425 hammer2_spin_ex(&parent->core.spin);
426 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
427 /* 1->0 transition failed */
428 hammer2_spin_unex(&parent->core.spin);
429 hammer2_spin_unex(&chain->core.spin);
430 return(chain); /* retry */
434 * 1->0 transition successful, remove chain from its
437 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
438 RB_REMOVE(hammer2_chain_tree,
439 &parent->core.rbtree, chain);
440 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
441 --parent->core.chain_count;
442 chain->parent = NULL;
446 * If our chain was the last chain in the parent's core the
447 * core is now empty and its parent might have to be
448 * re-dropped if it has 0 refs.
450 if (parent->core.chain_count == 0) {
452 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
456 hammer2_spin_unex(&parent->core.spin);
457 parent = NULL; /* safety */
461 * Successful 1->0 transition and the chain can be destroyed now.
463 * We still have the core spinlock, and core's chain_count is 0.
464 * Any parent spinlock is gone.
466 hammer2_spin_unex(&chain->core.spin);
467 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
468 chain->core.chain_count == 0);
471 * All spin locks are gone, finish freeing stuff.
473 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
474 HAMMER2_CHAIN_MODIFIED)) == 0);
475 hammer2_chain_drop_data(chain, 1);
477 KKASSERT(chain->dio == NULL);
480 * Once chain resources are gone we can use the now dead chain
481 * structure to placehold what might otherwise require a recursive
482 * drop, because we have potentially two things to drop and can only
483 * return one directly.
485 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
486 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
488 kfree(chain, hmp->mchain);
492 * Possible chaining loop when parent re-drop needed.
498 * On either last lock release or last drop
501 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
503 /*hammer2_dev_t *hmp = chain->hmp;*/
505 switch(chain->bref.type) {
506 case HAMMER2_BREF_TYPE_VOLUME:
507 case HAMMER2_BREF_TYPE_FREEMAP:
512 KKASSERT(chain->data == NULL);
518 * Lock a referenced chain element, acquiring its data with I/O if necessary,
519 * and specify how you would like the data to be resolved.
521 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
523 * The lock is allowed to recurse, multiple locking ops will aggregate
524 * the requested resolve types. Once data is assigned it will not be
525 * removed until the last unlock.
527 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
528 * (typically used to avoid device/logical buffer
531 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
532 * the INITIAL-create state (indirect blocks only).
534 * Do not resolve data elements for DATA chains.
535 * (typically used to avoid device/logical buffer
538 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
540 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
541 * it will be locked exclusive.
543 * NOTE: Embedded elements (volume header, inodes) are always resolved
546 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
547 * element will instantiate and zero its buffer, and flush it on
550 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
551 * so as not to instantiate a device buffer, which could alias against
552 * a logical file buffer. However, if ALWAYS is specified the
553 * device buffer will be instantiated anyway.
555 * WARNING! This function blocks on I/O if data needs to be fetched. This
556 * blocking can run concurrent with other compatible lock holders
557 * who do not need data returning. The lock is not upgraded to
558 * exclusive during a data fetch, a separate bit is used to
559 * interlock I/O. However, an exclusive lock holder can still count
560 * on being interlocked against an I/O fetch managed by a shared
564 hammer2_chain_lock(hammer2_chain_t *chain, int how)
567 * Ref and lock the element. Recursive locks are allowed.
569 KKASSERT(chain->refs > 0);
570 atomic_add_int(&chain->lockcnt, 1);
573 * Get the appropriate lock.
575 if (how & HAMMER2_RESOLVE_SHARED)
576 hammer2_mtx_sh(&chain->lock);
578 hammer2_mtx_ex(&chain->lock);
581 * If we already have a valid data pointer no further action is
588 * Do we have to resolve the data?
590 switch(how & HAMMER2_RESOLVE_MASK) {
591 case HAMMER2_RESOLVE_NEVER:
593 case HAMMER2_RESOLVE_MAYBE:
594 if (chain->flags & HAMMER2_CHAIN_INITIAL)
596 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
599 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
601 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
605 case HAMMER2_RESOLVE_ALWAYS:
610 * Caller requires data
612 hammer2_chain_load_data(chain);
616 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
617 * may be of any type.
619 * Once chain->data is set it cannot be disposed of until all locks are
623 hammer2_chain_load_data(hammer2_chain_t *chain)
625 hammer2_blockref_t *bref;
631 * Degenerate case, data already present.
637 KKASSERT(hmp != NULL);
640 * Gain the IOINPROG bit, interlocked block.
646 oflags = chain->flags;
648 if (oflags & HAMMER2_CHAIN_IOINPROG) {
649 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
650 tsleep_interlock(&chain->flags, 0);
651 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
652 tsleep(&chain->flags, PINTERLOCKED,
657 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
658 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
666 * We own CHAIN_IOINPROG
668 * Degenerate case if we raced another load.
674 * We must resolve to a device buffer, either by issuing I/O or
675 * by creating a zero-fill element. We do not mark the buffer
676 * dirty when creating a zero-fill element (the hammer2_chain_modify()
677 * API must still be used to do that).
679 * The device buffer is variable-sized in powers of 2 down
680 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
681 * chunk always contains buffers of the same size. (XXX)
683 * The minimum physical IO size may be larger than the variable
689 * The getblk() optimization can only be used on newly created
690 * elements if the physical block size matches the request.
692 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
693 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
696 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
698 hammer2_adjreadcounter(&chain->bref, chain->bytes);
701 chain->error = HAMMER2_ERROR_IO;
702 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
703 (intmax_t)bref->data_off, error);
704 hammer2_io_bqrelse(&chain->dio);
710 * NOTE: A locked chain's data cannot be modified without first
711 * calling hammer2_chain_modify().
715 * Clear INITIAL. In this case we used io_new() and the buffer has
716 * been zero'd and marked dirty.
718 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
719 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
720 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
721 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
722 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
724 * check data not currently synchronized due to
725 * modification. XXX assumes data stays in the buffer
726 * cache, which might not be true (need biodep on flush
727 * to calculate crc? or simple crc?).
730 if (hammer2_chain_testcheck(chain, bdata) == 0) {
731 kprintf("chain %016jx.%02x meth=%02x "
732 "CHECK FAIL %08x (flags=%08x)\n",
733 chain->bref.data_off,
736 hammer2_icrc32(bdata, chain->bytes),
738 chain->error = HAMMER2_ERROR_CHECK;
743 * Setup the data pointer, either pointing it to an embedded data
744 * structure and copying the data from the buffer, or pointing it
747 * The buffer is not retained when copying to an embedded data
748 * structure in order to avoid potential deadlocks or recursions
749 * on the same physical buffer.
751 * WARNING! Other threads can start using the data the instant we
752 * set chain->data non-NULL.
754 switch (bref->type) {
755 case HAMMER2_BREF_TYPE_VOLUME:
756 case HAMMER2_BREF_TYPE_FREEMAP:
758 * Copy data from bp to embedded buffer
760 panic("hammer2_chain_lock: called on unresolved volume header");
762 case HAMMER2_BREF_TYPE_INODE:
763 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
764 case HAMMER2_BREF_TYPE_INDIRECT:
765 case HAMMER2_BREF_TYPE_DATA:
766 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
769 * Point data at the device buffer and leave dio intact.
771 chain->data = (void *)bdata;
776 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
783 oflags = chain->flags;
784 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
785 HAMMER2_CHAIN_IOSIGNAL);
786 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
787 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
788 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
789 wakeup(&chain->flags);
796 * Unlock and deref a chain element.
798 * On the last lock release any non-embedded data (chain->dio) will be
802 hammer2_chain_unlock(hammer2_chain_t *chain)
804 hammer2_mtx_state_t ostate;
809 * If multiple locks are present (or being attempted) on this
810 * particular chain we can just unlock, drop refs, and return.
812 * Otherwise fall-through on the 1->0 transition.
815 lockcnt = chain->lockcnt;
816 KKASSERT(lockcnt > 0);
819 if (atomic_cmpset_int(&chain->lockcnt,
820 lockcnt, lockcnt - 1)) {
821 hammer2_mtx_unlock(&chain->lock);
825 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
832 * On the 1->0 transition we upgrade the core lock (if necessary)
833 * to exclusive for terminal processing. If after upgrading we find
834 * that lockcnt is non-zero, another thread is racing us and will
835 * handle the unload for us later on, so just cleanup and return
836 * leaving the data/io intact
838 * Otherwise if lockcnt is still 0 it is possible for it to become
839 * non-zero and race, but since we hold the core->lock exclusively
840 * all that will happen is that the chain will be reloaded after we
843 ostate = hammer2_mtx_upgrade(&chain->lock);
844 if (chain->lockcnt) {
845 hammer2_mtx_unlock(&chain->lock);
850 * Shortcut the case if the data is embedded or not resolved.
852 * Do NOT NULL out chain->data (e.g. inode data), it might be
855 if (chain->dio == NULL) {
856 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
857 hammer2_chain_drop_data(chain, 0);
858 hammer2_mtx_unlock(&chain->lock);
865 if (hammer2_io_isdirty(chain->dio) == 0) {
867 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
868 switch(chain->bref.type) {
869 case HAMMER2_BREF_TYPE_DATA:
870 counterp = &hammer2_ioa_file_write;
872 case HAMMER2_BREF_TYPE_INODE:
873 counterp = &hammer2_ioa_meta_write;
875 case HAMMER2_BREF_TYPE_INDIRECT:
876 counterp = &hammer2_ioa_indr_write;
878 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
879 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
880 counterp = &hammer2_ioa_fmap_write;
883 counterp = &hammer2_ioa_volu_write;
886 *counterp += chain->bytes;
888 switch(chain->bref.type) {
889 case HAMMER2_BREF_TYPE_DATA:
890 counterp = &hammer2_iod_file_write;
892 case HAMMER2_BREF_TYPE_INODE:
893 counterp = &hammer2_iod_meta_write;
895 case HAMMER2_BREF_TYPE_INDIRECT:
896 counterp = &hammer2_iod_indr_write;
898 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
899 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
900 counterp = &hammer2_iod_fmap_write;
903 counterp = &hammer2_iod_volu_write;
906 *counterp += chain->bytes;
912 * If a device buffer was used for data be sure to destroy the
913 * buffer when we are done to avoid aliases (XXX what about the
914 * underlying VM pages?).
916 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
919 * NOTE: The isdirty check tracks whether we have to bdwrite() the
920 * buffer or not. The buffer might already be dirty. The
921 * flag is re-set when chain_modify() is called, even if
922 * MODIFIED is already set, allowing the OS to retire the
923 * buffer independent of a hammer2 flush.
926 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
927 hammer2_io_isdirty(chain->dio)) {
928 hammer2_io_bawrite(&chain->dio);
930 hammer2_io_bqrelse(&chain->dio);
932 hammer2_mtx_unlock(&chain->lock);
936 * This counts the number of live blockrefs in a block array and
937 * also calculates the point at which all remaining blockrefs are empty.
938 * This routine can only be called on a live chain (DUPLICATED flag not set).
940 * NOTE: Flag is not set until after the count is complete, allowing
941 * callers to test the flag without holding the spinlock.
943 * NOTE: If base is NULL the related chain is still in the INITIAL
944 * state and there are no blockrefs to count.
946 * NOTE: live_count may already have some counts accumulated due to
947 * creation and deletion and could even be initially negative.
950 hammer2_chain_countbrefs(hammer2_chain_t *chain,
951 hammer2_blockref_t *base, int count)
953 hammer2_spin_ex(&chain->core.spin);
954 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
956 while (--count >= 0) {
957 if (base[count].type)
960 chain->core.live_zero = count + 1;
962 if (base[count].type)
963 atomic_add_int(&chain->core.live_count,
968 chain->core.live_zero = 0;
970 /* else do not modify live_count */
971 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
973 hammer2_spin_unex(&chain->core.spin);
977 * Resize the chain's physical storage allocation in-place. This function does
978 * not adjust the data pointer and must be followed by (typically) a
979 * hammer2_chain_modify() call to copy any old data over and adjust the
982 * Chains can be resized smaller without reallocating the storage. Resizing
983 * larger will reallocate the storage. Excess or prior storage is reclaimed
984 * asynchronously at a later time.
986 * Must be passed an exclusively locked parent and chain.
988 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
989 * to avoid instantiating a device buffer that conflicts with the vnode data
990 * buffer. However, because H2 can compress or encrypt data, the chain may
991 * have a dio assigned to it in those situations, and they do not conflict.
993 * XXX return error if cannot resize.
996 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
997 hammer2_chain_t *parent, hammer2_chain_t *chain,
998 int nradix, int flags)
1007 * Only data and indirect blocks can be resized for now.
1008 * (The volu root, inodes, and freemap elements use a fixed size).
1010 KKASSERT(chain != &hmp->vchain);
1011 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1012 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1015 * Nothing to do if the element is already the proper size
1017 obytes = chain->bytes;
1018 nbytes = 1U << nradix;
1019 if (obytes == nbytes)
1023 * Make sure the old data is instantiated so we can copy it. If this
1024 * is a data block, the device data may be superfluous since the data
1025 * might be in a logical block, but compressed or encrypted data is
1028 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1030 hammer2_chain_modify(trans, chain, 0);
1033 * Relocate the block, even if making it smaller (because different
1034 * block sizes may be in different regions).
1036 * (data blocks only, we aren't copying the storage here).
1038 hammer2_freemap_alloc(trans, chain, nbytes);
1039 chain->bytes = nbytes;
1040 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1043 * We don't want the followup chain_modify() to try to copy data
1044 * from the old (wrong-sized) buffer. It won't know how much to
1045 * copy. This case should only occur during writes when the
1046 * originator already has the data to write in-hand.
1049 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1050 hammer2_io_brelse(&chain->dio);
1056 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1058 hammer2_blockref_t obref;
1067 obref = chain->bref;
1068 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1071 * Data is not optional for freemap chains (we must always be sure
1072 * to copy the data on COW storage allocations).
1074 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1075 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1076 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1077 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1081 * Data must be resolved if already assigned, unless explicitly
1082 * flagged otherwise.
1084 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1085 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1086 hammer2_chain_load_data(chain);
1090 * Set MODIFIED to indicate that the chain has been modified.
1091 * Set UPDATE to ensure that the blockref is updated in the parent.
1093 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1094 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1095 hammer2_chain_ref(chain);
1096 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1101 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1102 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1103 hammer2_chain_ref(chain);
1107 * The modification or re-modification requires an allocation and
1110 * We normally always allocate new storage here. If storage exists
1111 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1113 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1114 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1115 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1117 hammer2_freemap_alloc(trans, chain, chain->bytes);
1118 /* XXX failed allocation */
1123 * Update mirror_tid and modify_tid. modify_tid is only updated
1124 * automatically by this function when used from the frontend.
1125 * Flushes and synchronization adjust the flag manually.
1127 * NOTE: chain->pmp could be the device spmp.
1129 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1130 if (chain->pmp && (trans->flags & (HAMMER2_TRANS_KEEPMODIFY |
1131 HAMMER2_TRANS_ISFLUSH)) == 0) {
1132 chain->bref.modify_tid = chain->pmp->modify_tid + 1;
1136 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1137 * requires updating as well as to tell the delete code that the
1138 * chain's blockref might not exactly match (in terms of physical size
1139 * or block offset) the one in the parent's blocktable. The base key
1140 * of course will still match.
1142 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1143 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1146 * Short-cut data blocks which the caller does not need an actual
1147 * data reference to (aka OPTDATA), as long as the chain does not
1148 * already have a data pointer to the data. This generally means
1149 * that the modifications are being done via the logical buffer cache.
1150 * The INITIAL flag relates only to the device data buffer and thus
1151 * remains unchange in this situation.
1153 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1154 (flags & HAMMER2_MODIFY_OPTDATA) &&
1155 chain->data == NULL) {
1160 * Clearing the INITIAL flag (for indirect blocks) indicates that
1161 * we've processed the uninitialized storage allocation.
1163 * If this flag is already clear we are likely in a copy-on-write
1164 * situation but we have to be sure NOT to bzero the storage if
1165 * no data is present.
1167 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1168 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1175 * Instantiate data buffer and possibly execute COW operation
1177 switch(chain->bref.type) {
1178 case HAMMER2_BREF_TYPE_VOLUME:
1179 case HAMMER2_BREF_TYPE_FREEMAP:
1181 * The data is embedded, no copy-on-write operation is
1184 KKASSERT(chain->dio == NULL);
1186 case HAMMER2_BREF_TYPE_INODE:
1187 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1188 case HAMMER2_BREF_TYPE_DATA:
1189 case HAMMER2_BREF_TYPE_INDIRECT:
1190 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1192 * Perform the copy-on-write operation
1194 * zero-fill or copy-on-write depending on whether
1195 * chain->data exists or not and set the dirty state for
1196 * the new buffer. hammer2_io_new() will handle the
1199 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1202 error = hammer2_io_new(hmp, chain->bref.data_off,
1203 chain->bytes, &dio);
1205 error = hammer2_io_bread(hmp, chain->bref.data_off,
1206 chain->bytes, &dio);
1208 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1211 * If an I/O error occurs make sure callers cannot accidently
1212 * modify the old buffer's contents and corrupt the filesystem.
1215 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1217 chain->error = HAMMER2_ERROR_IO;
1218 hammer2_io_brelse(&dio);
1219 hammer2_io_brelse(&chain->dio);
1224 bdata = hammer2_io_data(dio, chain->bref.data_off);
1227 KKASSERT(chain->dio != NULL);
1228 if (chain->data != (void *)bdata) {
1229 bcopy(chain->data, bdata, chain->bytes);
1231 } else if (wasinitial == 0) {
1233 * We have a problem. We were asked to COW but
1234 * we don't have any data to COW with!
1236 panic("hammer2_chain_modify: having a COW %p\n",
1241 * Retire the old buffer, replace with the new. Dirty or
1242 * redirty the new buffer.
1244 * WARNING! The system buffer cache may have already flushed
1245 * the buffer, so we must be sure to [re]dirty it
1246 * for further modification.
1249 hammer2_io_brelse(&chain->dio);
1250 chain->data = (void *)bdata;
1252 hammer2_io_setdirty(dio); /* modified by bcopy above */
1255 panic("hammer2_chain_modify: illegal non-embedded type %d",
1262 * setflush on parent indicating that the parent must recurse down
1263 * to us. Do not call on chain itself which might already have it
1267 hammer2_chain_setflush(trans, chain->parent);
1271 * Volume header data locks
1274 hammer2_voldata_lock(hammer2_dev_t *hmp)
1276 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1280 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1282 lockmgr(&hmp->vollk, LK_RELEASE);
1286 hammer2_voldata_modify(hammer2_dev_t *hmp)
1288 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1289 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1290 hammer2_chain_ref(&hmp->vchain);
1291 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1296 * This function returns the chain at the nearest key within the specified
1297 * range. The returned chain will be referenced but not locked.
1299 * This function will recurse through chain->rbtree as necessary and will
1300 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1301 * the iteration value is less than the current value of *key_nextp.
1303 * The caller should use (*key_nextp) to calculate the actual range of
1304 * the returned element, which will be (key_beg to *key_nextp - 1), because
1305 * there might be another element which is superior to the returned element
1308 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1309 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1310 * it will wind up being (key_end + 1).
1312 * WARNING! Must be called with child's spinlock held. Spinlock remains
1313 * held through the operation.
1315 struct hammer2_chain_find_info {
1316 hammer2_chain_t *best;
1317 hammer2_key_t key_beg;
1318 hammer2_key_t key_end;
1319 hammer2_key_t key_next;
1322 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1323 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1327 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1328 hammer2_key_t key_beg, hammer2_key_t key_end)
1330 struct hammer2_chain_find_info info;
1333 info.key_beg = key_beg;
1334 info.key_end = key_end;
1335 info.key_next = *key_nextp;
1337 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1338 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1340 *key_nextp = info.key_next;
1342 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1343 parent, key_beg, key_end, *key_nextp);
1351 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1353 struct hammer2_chain_find_info *info = data;
1354 hammer2_key_t child_beg;
1355 hammer2_key_t child_end;
1357 child_beg = child->bref.key;
1358 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1360 if (child_end < info->key_beg)
1362 if (child_beg > info->key_end)
1369 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1371 struct hammer2_chain_find_info *info = data;
1372 hammer2_chain_t *best;
1373 hammer2_key_t child_end;
1376 * WARNING! Do not discard DUPLICATED chains, it is possible that
1377 * we are catching an insertion half-way done. If a
1378 * duplicated chain turns out to be the best choice the
1379 * caller will re-check its flags after locking it.
1381 * WARNING! Layerq is scanned forwards, exact matches should keep
1382 * the existing info->best.
1384 if ((best = info->best) == NULL) {
1386 * No previous best. Assign best
1389 } else if (best->bref.key <= info->key_beg &&
1390 child->bref.key <= info->key_beg) {
1395 /*info->best = child;*/
1396 } else if (child->bref.key < best->bref.key) {
1398 * Child has a nearer key and best is not flush with key_beg.
1399 * Set best to child. Truncate key_next to the old best key.
1402 if (info->key_next > best->bref.key || info->key_next == 0)
1403 info->key_next = best->bref.key;
1404 } else if (child->bref.key == best->bref.key) {
1406 * If our current best is flush with the child then this
1407 * is an illegal overlap.
1409 * key_next will automatically be limited to the smaller of
1410 * the two end-points.
1416 * Keep the current best but truncate key_next to the child's
1419 * key_next will also automatically be limited to the smaller
1420 * of the two end-points (probably not necessary for this case
1421 * but we do it anyway).
1423 if (info->key_next > child->bref.key || info->key_next == 0)
1424 info->key_next = child->bref.key;
1428 * Always truncate key_next based on child's end-of-range.
1430 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1431 if (child_end && (info->key_next > child_end || info->key_next == 0))
1432 info->key_next = child_end;
1438 * Retrieve the specified chain from a media blockref, creating the
1439 * in-memory chain structure which reflects it.
1441 * To handle insertion races pass the INSERT_RACE flag along with the
1442 * generation number of the core. NULL will be returned if the generation
1443 * number changes before we have a chance to insert the chain. Insert
1444 * races can occur because the parent might be held shared.
1446 * Caller must hold the parent locked shared or exclusive since we may
1447 * need the parent's bref array to find our block.
1449 * WARNING! chain->pmp is always set to NULL for any chain representing
1450 * part of the super-root topology.
1453 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1454 hammer2_blockref_t *bref)
1456 hammer2_dev_t *hmp = parent->hmp;
1457 hammer2_chain_t *chain;
1461 * Allocate a chain structure representing the existing media
1462 * entry. Resulting chain has one ref and is not locked.
1464 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1465 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1467 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1468 /* ref'd chain returned */
1471 * Flag that the chain is in the parent's blockmap so delete/flush
1472 * knows what to do with it.
1474 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1477 * Link the chain into its parent. A spinlock is required to safely
1478 * access the RBTREE, and it is possible to collide with another
1479 * hammer2_chain_get() operation because the caller might only hold
1480 * a shared lock on the parent.
1482 KKASSERT(parent->refs > 0);
1483 error = hammer2_chain_insert(parent, chain,
1484 HAMMER2_CHAIN_INSERT_SPIN |
1485 HAMMER2_CHAIN_INSERT_RACE,
1488 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1489 kprintf("chain %p get race\n", chain);
1490 hammer2_chain_drop(chain);
1493 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1497 * Return our new chain referenced but not locked, or NULL if
1504 * Lookup initialization/completion API
1507 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1509 hammer2_chain_ref(parent);
1510 if (flags & HAMMER2_LOOKUP_SHARED) {
1511 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1512 HAMMER2_RESOLVE_SHARED);
1514 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1520 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1523 hammer2_chain_unlock(parent);
1524 hammer2_chain_drop(parent);
1530 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1532 hammer2_chain_t *oparent;
1533 hammer2_chain_t *nparent;
1536 * Be careful of order, oparent must be unlocked before nparent
1537 * is locked below to avoid a deadlock.
1540 hammer2_spin_ex(&oparent->core.spin);
1541 nparent = oparent->parent;
1542 hammer2_chain_ref(nparent);
1543 hammer2_spin_unex(&oparent->core.spin);
1545 hammer2_chain_unlock(oparent);
1546 hammer2_chain_drop(oparent);
1550 hammer2_chain_lock(nparent, how);
1557 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1558 * (*parentp) typically points to an inode but can also point to a related
1559 * indirect block and this function will recurse upwards and find the inode
1562 * (*parentp) must be exclusively locked and referenced and can be an inode
1563 * or an existing indirect block within the inode.
1565 * On return (*parentp) will be modified to point at the deepest parent chain
1566 * element encountered during the search, as a helper for an insertion or
1567 * deletion. The new (*parentp) will be locked and referenced and the old
1568 * will be unlocked and dereferenced (no change if they are both the same).
1570 * The matching chain will be returned exclusively locked. If NOLOCK is
1571 * requested the chain will be returned only referenced. Note that the
1572 * parent chain must always be locked shared or exclusive, matching the
1573 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1574 * when NOLOCK is specified but that complicates matters if *parentp must
1575 * inherit the chain.
1577 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1578 * data pointer or can otherwise be in flux.
1580 * NULL is returned if no match was found, but (*parentp) will still
1581 * potentially be adjusted.
1583 * If a fatal error occurs (typically an I/O error), a dummy chain is
1584 * returned with chain->error and error-identifying information set. This
1585 * chain will assert if you try to do anything fancy with it.
1587 * XXX Depending on where the error occurs we should allow continued iteration.
1589 * On return (*key_nextp) will point to an iterative value for key_beg.
1590 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1592 * This function will also recurse up the chain if the key is not within the
1593 * current parent's range. (*parentp) can never be set to NULL. An iteration
1594 * can simply allow (*parentp) to float inside the loop.
1596 * NOTE! chain->data is not always resolved. By default it will not be
1597 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1598 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1599 * BREF_TYPE_DATA as the device buffer can alias the logical file
1603 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1604 hammer2_key_t key_beg, hammer2_key_t key_end,
1605 int *cache_indexp, int flags)
1608 hammer2_chain_t *parent;
1609 hammer2_chain_t *chain;
1610 hammer2_blockref_t *base;
1611 hammer2_blockref_t *bref;
1612 hammer2_blockref_t bcopy;
1613 hammer2_key_t scan_beg;
1614 hammer2_key_t scan_end;
1616 int how_always = HAMMER2_RESOLVE_ALWAYS;
1617 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1620 int maxloops = 300000;
1622 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1623 how_maybe = how_always;
1624 how = HAMMER2_RESOLVE_ALWAYS;
1625 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1626 how = HAMMER2_RESOLVE_NEVER;
1628 how = HAMMER2_RESOLVE_MAYBE;
1630 if (flags & HAMMER2_LOOKUP_SHARED) {
1631 how_maybe |= HAMMER2_RESOLVE_SHARED;
1632 how_always |= HAMMER2_RESOLVE_SHARED;
1633 how |= HAMMER2_RESOLVE_SHARED;
1637 * Recurse (*parentp) upward if necessary until the parent completely
1638 * encloses the key range or we hit the inode.
1640 * This function handles races against the flusher doing a delete-
1641 * duplicate above us and re-homes the parent to the duplicate in
1642 * that case, otherwise we'd wind up recursing down a stale chain.
1647 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1648 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1649 scan_beg = parent->bref.key;
1650 scan_end = scan_beg +
1651 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1652 if (key_beg >= scan_beg && key_end <= scan_end)
1654 parent = hammer2_chain_getparent(parentp, how_maybe);
1658 if (--maxloops == 0)
1659 panic("hammer2_chain_lookup: maxloops");
1661 * Locate the blockref array. Currently we do a fully associative
1662 * search through the array.
1664 switch(parent->bref.type) {
1665 case HAMMER2_BREF_TYPE_INODE:
1667 * Special shortcut for embedded data returns the inode
1668 * itself. Callers must detect this condition and access
1669 * the embedded data (the strategy code does this for us).
1671 * This is only applicable to regular files and softlinks.
1673 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1674 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1676 *key_nextp = key_end + 1;
1679 hammer2_chain_ref(parent);
1680 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1681 hammer2_chain_lock(parent, how_always);
1682 *key_nextp = key_end + 1;
1685 base = &parent->data->ipdata.u.blockset.blockref[0];
1686 count = HAMMER2_SET_COUNT;
1688 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1689 case HAMMER2_BREF_TYPE_INDIRECT:
1691 * Handle MATCHIND on the parent
1693 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1694 scan_beg = parent->bref.key;
1695 scan_end = scan_beg +
1696 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1697 if (key_beg == scan_beg && key_end == scan_end) {
1699 hammer2_chain_ref(chain);
1700 hammer2_chain_lock(chain, how_maybe);
1701 *key_nextp = scan_end + 1;
1706 * Optimize indirect blocks in the INITIAL state to avoid
1709 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1712 if (parent->data == NULL)
1713 panic("parent->data is NULL");
1714 base = &parent->data->npdata[0];
1716 count = parent->bytes / sizeof(hammer2_blockref_t);
1718 case HAMMER2_BREF_TYPE_VOLUME:
1719 base = &hmp->voldata.sroot_blockset.blockref[0];
1720 count = HAMMER2_SET_COUNT;
1722 case HAMMER2_BREF_TYPE_FREEMAP:
1723 base = &hmp->voldata.freemap_blockset.blockref[0];
1724 count = HAMMER2_SET_COUNT;
1727 kprintf("hammer2_chain_lookup: unrecognized "
1728 "blockref(B) type: %d",
1731 tsleep(&base, 0, "dead", 0);
1732 panic("hammer2_chain_lookup: unrecognized "
1733 "blockref(B) type: %d",
1735 base = NULL; /* safety */
1736 count = 0; /* safety */
1740 * Merged scan to find next candidate.
1742 * hammer2_base_*() functions require the parent->core.live_* fields
1743 * to be synchronized.
1745 * We need to hold the spinlock to access the block array and RB tree
1746 * and to interlock chain creation.
1748 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1749 hammer2_chain_countbrefs(parent, base, count);
1754 hammer2_spin_ex(&parent->core.spin);
1755 chain = hammer2_combined_find(parent, base, count,
1756 cache_indexp, key_nextp,
1759 generation = parent->core.generation;
1762 * Exhausted parent chain, iterate.
1765 hammer2_spin_unex(&parent->core.spin);
1766 if (key_beg == key_end) /* short cut single-key case */
1770 * Stop if we reached the end of the iteration.
1772 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1773 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1778 * Calculate next key, stop if we reached the end of the
1779 * iteration, otherwise go up one level and loop.
1781 key_beg = parent->bref.key +
1782 ((hammer2_key_t)1 << parent->bref.keybits);
1783 if (key_beg == 0 || key_beg > key_end)
1785 parent = hammer2_chain_getparent(parentp, how_maybe);
1790 * Selected from blockref or in-memory chain.
1792 if (chain == NULL) {
1794 hammer2_spin_unex(&parent->core.spin);
1795 chain = hammer2_chain_get(parent, generation,
1797 if (chain == NULL) {
1798 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1799 parent, key_beg, key_end);
1802 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1803 hammer2_chain_drop(chain);
1807 hammer2_chain_ref(chain);
1808 hammer2_spin_unex(&parent->core.spin);
1812 * chain is referenced but not locked. We must lock the chain
1813 * to obtain definitive DUPLICATED/DELETED state
1815 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1816 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1817 hammer2_chain_lock(chain, how_maybe);
1819 hammer2_chain_lock(chain, how);
1823 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1825 * NOTE: Chain's key range is not relevant as there might be
1826 * one-offs within the range that are not deleted.
1828 * NOTE: Lookups can race delete-duplicate because
1829 * delete-duplicate does not lock the parent's core
1830 * (they just use the spinlock on the core). We must
1831 * check for races by comparing the DUPLICATED flag before
1832 * releasing the spinlock with the flag after locking the
1835 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1836 hammer2_chain_unlock(chain);
1837 hammer2_chain_drop(chain);
1838 key_beg = *key_nextp;
1839 if (key_beg == 0 || key_beg > key_end)
1845 * If the chain element is an indirect block it becomes the new
1846 * parent and we loop on it. We must maintain our top-down locks
1847 * to prevent the flusher from interfering (i.e. doing a
1848 * delete-duplicate and leaving us recursing down a deleted chain).
1850 * The parent always has to be locked with at least RESOLVE_MAYBE
1851 * so we can access its data. It might need a fixup if the caller
1852 * passed incompatible flags. Be careful not to cause a deadlock
1853 * as a data-load requires an exclusive lock.
1855 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1856 * range is within the requested key range we return the indirect
1857 * block and do NOT loop. This is usually only used to acquire
1860 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1861 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1862 hammer2_chain_unlock(parent);
1863 hammer2_chain_drop(parent);
1864 *parentp = parent = chain;
1869 * All done, return the chain.
1871 * If the caller does not want a locked chain, replace the lock with
1872 * a ref. Perhaps this can eventually be optimized to not obtain the
1873 * lock in the first place for situations where the data does not
1874 * need to be resolved.
1877 if (flags & HAMMER2_LOOKUP_NOLOCK)
1878 hammer2_chain_unlock(chain);
1885 * After having issued a lookup we can iterate all matching keys.
1887 * If chain is non-NULL we continue the iteration from just after it's index.
1889 * If chain is NULL we assume the parent was exhausted and continue the
1890 * iteration at the next parent.
1892 * If a fatal error occurs (typically an I/O error), a dummy chain is
1893 * returned with chain->error and error-identifying information set. This
1894 * chain will assert if you try to do anything fancy with it.
1896 * XXX Depending on where the error occurs we should allow continued iteration.
1898 * parent must be locked on entry and remains locked throughout. chain's
1899 * lock status must match flags. Chain is always at least referenced.
1901 * WARNING! The MATCHIND flag does not apply to this function.
1904 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1905 hammer2_key_t *key_nextp,
1906 hammer2_key_t key_beg, hammer2_key_t key_end,
1907 int *cache_indexp, int flags)
1909 hammer2_chain_t *parent;
1913 * Calculate locking flags for upward recursion.
1915 how_maybe = HAMMER2_RESOLVE_MAYBE;
1916 if (flags & HAMMER2_LOOKUP_SHARED)
1917 how_maybe |= HAMMER2_RESOLVE_SHARED;
1922 * Calculate the next index and recalculate the parent if necessary.
1925 key_beg = chain->bref.key +
1926 ((hammer2_key_t)1 << chain->bref.keybits);
1927 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1928 hammer2_chain_unlock(chain);
1929 hammer2_chain_drop(chain);
1932 * chain invalid past this point, but we can still do a
1933 * pointer comparison w/parent.
1935 * Any scan where the lookup returned degenerate data embedded
1936 * in the inode has an invalid index and must terminate.
1938 if (chain == parent)
1940 if (key_beg == 0 || key_beg > key_end)
1943 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1944 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1946 * We reached the end of the iteration.
1951 * Continue iteration with next parent unless the current
1952 * parent covers the range.
1954 key_beg = parent->bref.key +
1955 ((hammer2_key_t)1 << parent->bref.keybits);
1956 if (key_beg == 0 || key_beg > key_end)
1958 parent = hammer2_chain_getparent(parentp, how_maybe);
1964 return (hammer2_chain_lookup(parentp, key_nextp,
1966 cache_indexp, flags));
1970 * The raw scan function is similar to lookup/next but does not seek to a key.
1971 * Blockrefs are iterated via first_chain = (parent, NULL) and
1972 * next_chain = (parent, chain).
1974 * The passed-in parent must be locked and its data resolved. The returned
1975 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1976 * under parent and then iterate with the passed-in chain (which this
1977 * function will unlock).
1980 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1981 int *cache_indexp, int flags)
1984 hammer2_blockref_t *base;
1985 hammer2_blockref_t *bref;
1986 hammer2_blockref_t bcopy;
1988 hammer2_key_t next_key;
1990 int how_always = HAMMER2_RESOLVE_ALWAYS;
1991 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1994 int maxloops = 300000;
1999 * Scan flags borrowed from lookup.
2001 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2002 how_maybe = how_always;
2003 how = HAMMER2_RESOLVE_ALWAYS;
2004 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2005 how = HAMMER2_RESOLVE_NEVER;
2007 how = HAMMER2_RESOLVE_MAYBE;
2009 if (flags & HAMMER2_LOOKUP_SHARED) {
2010 how_maybe |= HAMMER2_RESOLVE_SHARED;
2011 how_always |= HAMMER2_RESOLVE_SHARED;
2012 how |= HAMMER2_RESOLVE_SHARED;
2016 * Calculate key to locate first/next element, unlocking the previous
2017 * element as we go. Be careful, the key calculation can overflow.
2020 key = chain->bref.key +
2021 ((hammer2_key_t)1 << chain->bref.keybits);
2022 hammer2_chain_unlock(chain);
2023 hammer2_chain_drop(chain);
2032 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2033 if (--maxloops == 0)
2034 panic("hammer2_chain_scan: maxloops");
2036 * Locate the blockref array. Currently we do a fully associative
2037 * search through the array.
2039 switch(parent->bref.type) {
2040 case HAMMER2_BREF_TYPE_INODE:
2042 * An inode with embedded data has no sub-chains.
2044 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2046 base = &parent->data->ipdata.u.blockset.blockref[0];
2047 count = HAMMER2_SET_COUNT;
2049 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2050 case HAMMER2_BREF_TYPE_INDIRECT:
2052 * Optimize indirect blocks in the INITIAL state to avoid
2055 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2058 if (parent->data == NULL)
2059 panic("parent->data is NULL");
2060 base = &parent->data->npdata[0];
2062 count = parent->bytes / sizeof(hammer2_blockref_t);
2064 case HAMMER2_BREF_TYPE_VOLUME:
2065 base = &hmp->voldata.sroot_blockset.blockref[0];
2066 count = HAMMER2_SET_COUNT;
2068 case HAMMER2_BREF_TYPE_FREEMAP:
2069 base = &hmp->voldata.freemap_blockset.blockref[0];
2070 count = HAMMER2_SET_COUNT;
2073 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2075 base = NULL; /* safety */
2076 count = 0; /* safety */
2080 * Merged scan to find next candidate.
2082 * hammer2_base_*() functions require the parent->core.live_* fields
2083 * to be synchronized.
2085 * We need to hold the spinlock to access the block array and RB tree
2086 * and to interlock chain creation.
2088 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2089 hammer2_chain_countbrefs(parent, base, count);
2092 hammer2_spin_ex(&parent->core.spin);
2093 chain = hammer2_combined_find(parent, base, count,
2094 cache_indexp, &next_key,
2095 key, HAMMER2_KEY_MAX,
2097 generation = parent->core.generation;
2100 * Exhausted parent chain, we're done.
2103 hammer2_spin_unex(&parent->core.spin);
2104 KKASSERT(chain == NULL);
2109 * Selected from blockref or in-memory chain.
2111 if (chain == NULL) {
2113 hammer2_spin_unex(&parent->core.spin);
2114 chain = hammer2_chain_get(parent, generation, &bcopy);
2115 if (chain == NULL) {
2116 kprintf("retry scan parent %p keys %016jx\n",
2120 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2121 hammer2_chain_drop(chain);
2126 hammer2_chain_ref(chain);
2127 hammer2_spin_unex(&parent->core.spin);
2131 * chain is referenced but not locked. We must lock the chain
2132 * to obtain definitive DUPLICATED/DELETED state
2134 hammer2_chain_lock(chain, how);
2137 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2139 * NOTE: chain's key range is not relevant as there might be
2140 * one-offs within the range that are not deleted.
2142 * NOTE: XXX this could create problems with scans used in
2143 * situations other than mount-time recovery.
2145 * NOTE: Lookups can race delete-duplicate because
2146 * delete-duplicate does not lock the parent's core
2147 * (they just use the spinlock on the core). We must
2148 * check for races by comparing the DUPLICATED flag before
2149 * releasing the spinlock with the flag after locking the
2152 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2153 hammer2_chain_unlock(chain);
2154 hammer2_chain_drop(chain);
2165 * All done, return the chain or NULL
2171 * Create and return a new hammer2 system memory structure of the specified
2172 * key, type and size and insert it under (*parentp). This is a full
2173 * insertion, based on the supplied key/keybits, and may involve creating
2174 * indirect blocks and moving other chains around via delete/duplicate.
2176 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2177 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2178 * FULL. This typically means that the caller is creating the chain after
2179 * doing a hammer2_chain_lookup().
2181 * (*parentp) must be exclusive locked and may be replaced on return
2182 * depending on how much work the function had to do.
2184 * (*parentp) must not be errored or this function will assert.
2186 * (*chainp) usually starts out NULL and returns the newly created chain,
2187 * but if the caller desires the caller may allocate a disconnected chain
2188 * and pass it in instead.
2190 * This function should NOT be used to insert INDIRECT blocks. It is
2191 * typically used to create/insert inodes and data blocks.
2193 * Caller must pass-in an exclusively locked parent the new chain is to
2194 * be inserted under, and optionally pass-in a disconnected, exclusively
2195 * locked chain to insert (else we create a new chain). The function will
2196 * adjust (*parentp) as necessary, create or connect the chain, and
2197 * return an exclusively locked chain in *chainp.
2199 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2200 * and will be reassigned.
2203 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2204 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2205 hammer2_key_t key, int keybits, int type, size_t bytes,
2209 hammer2_chain_t *chain;
2210 hammer2_chain_t *parent;
2211 hammer2_blockref_t *base;
2212 hammer2_blockref_t dummy;
2216 int maxloops = 300000;
2219 * Topology may be crossing a PFS boundary.
2222 KKASSERT(hammer2_mtx_owned(&parent->lock));
2223 KKASSERT(parent->error == 0);
2227 if (chain == NULL) {
2229 * First allocate media space and construct the dummy bref,
2230 * then allocate the in-memory chain structure. Set the
2231 * INITIAL flag for fresh chains which do not have embedded
2234 bzero(&dummy, sizeof(dummy));
2237 dummy.keybits = keybits;
2238 dummy.data_off = hammer2_getradix(bytes);
2239 dummy.methods = parent->bref.methods;
2240 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2243 * Lock the chain manually, chain_lock will load the chain
2244 * which we do NOT want to do. (note: chain->refs is set
2245 * to 1 by chain_alloc() for us, but lockcnt is not).
2248 hammer2_mtx_ex(&chain->lock);
2252 * Set INITIAL to optimize I/O. The flag will generally be
2253 * processed when we call hammer2_chain_modify().
2255 * Recalculate bytes to reflect the actual media block
2258 bytes = (hammer2_off_t)1 <<
2259 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2260 chain->bytes = bytes;
2263 case HAMMER2_BREF_TYPE_VOLUME:
2264 case HAMMER2_BREF_TYPE_FREEMAP:
2265 panic("hammer2_chain_create: called with volume type");
2267 case HAMMER2_BREF_TYPE_INDIRECT:
2268 panic("hammer2_chain_create: cannot be used to"
2269 "create indirect block");
2271 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2272 panic("hammer2_chain_create: cannot be used to"
2273 "create freemap root or node");
2275 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2276 KKASSERT(bytes == sizeof(chain->data->bmdata));
2278 case HAMMER2_BREF_TYPE_INODE:
2279 case HAMMER2_BREF_TYPE_DATA:
2282 * leave chain->data NULL, set INITIAL
2284 KKASSERT(chain->data == NULL);
2285 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2290 * We are reattaching a previously deleted chain, possibly
2291 * under a new parent and possibly with a new key/keybits.
2292 * The chain does not have to be in a modified state. The
2293 * UPDATE flag will be set later on in this routine.
2295 * Do NOT mess with the current state of the INITIAL flag.
2297 chain->bref.key = key;
2298 chain->bref.keybits = keybits;
2299 if (chain->flags & HAMMER2_CHAIN_DELETED)
2300 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2301 KKASSERT(chain->parent == NULL);
2303 if (flags & HAMMER2_INSERT_PFSROOT)
2304 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2306 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2309 * Calculate how many entries we have in the blockref array and
2310 * determine if an indirect block is required.
2313 if (--maxloops == 0)
2314 panic("hammer2_chain_create: maxloops");
2316 switch(parent->bref.type) {
2317 case HAMMER2_BREF_TYPE_INODE:
2318 KKASSERT((parent->data->ipdata.op_flags &
2319 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2320 KKASSERT(parent->data != NULL);
2321 base = &parent->data->ipdata.u.blockset.blockref[0];
2322 count = HAMMER2_SET_COUNT;
2324 case HAMMER2_BREF_TYPE_INDIRECT:
2325 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2326 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2329 base = &parent->data->npdata[0];
2330 count = parent->bytes / sizeof(hammer2_blockref_t);
2332 case HAMMER2_BREF_TYPE_VOLUME:
2333 KKASSERT(parent->data != NULL);
2334 base = &hmp->voldata.sroot_blockset.blockref[0];
2335 count = HAMMER2_SET_COUNT;
2337 case HAMMER2_BREF_TYPE_FREEMAP:
2338 KKASSERT(parent->data != NULL);
2339 base = &hmp->voldata.freemap_blockset.blockref[0];
2340 count = HAMMER2_SET_COUNT;
2343 panic("hammer2_chain_create: unrecognized blockref type: %d",
2351 * Make sure we've counted the brefs
2353 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2354 hammer2_chain_countbrefs(parent, base, count);
2356 KKASSERT(parent->core.live_count >= 0 &&
2357 parent->core.live_count <= count);
2360 * If no free blockref could be found we must create an indirect
2361 * block and move a number of blockrefs into it. With the parent
2362 * locked we can safely lock each child in order to delete+duplicate
2363 * it without causing a deadlock.
2365 * This may return the new indirect block or the old parent depending
2366 * on where the key falls. NULL is returned on error.
2368 if (parent->core.live_count == count) {
2369 hammer2_chain_t *nparent;
2371 nparent = hammer2_chain_create_indirect(trans, parent,
2374 if (nparent == NULL) {
2376 hammer2_chain_drop(chain);
2380 if (parent != nparent) {
2381 hammer2_chain_unlock(parent);
2382 hammer2_chain_drop(parent);
2383 parent = *parentp = nparent;
2389 * Link the chain into its parent.
2391 if (chain->parent != NULL)
2392 panic("hammer2: hammer2_chain_create: chain already connected");
2393 KKASSERT(chain->parent == NULL);
2394 hammer2_chain_insert(parent, chain,
2395 HAMMER2_CHAIN_INSERT_SPIN |
2396 HAMMER2_CHAIN_INSERT_LIVE,
2401 * Mark the newly created chain modified. This will cause
2402 * UPDATE to be set and process the INITIAL flag.
2404 * Device buffers are not instantiated for DATA elements
2405 * as these are handled by logical buffers.
2407 * Indirect and freemap node indirect blocks are handled
2408 * by hammer2_chain_create_indirect() and not by this
2411 * Data for all other bref types is expected to be
2412 * instantiated (INODE, LEAF).
2414 switch(chain->bref.type) {
2415 case HAMMER2_BREF_TYPE_DATA:
2416 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2417 case HAMMER2_BREF_TYPE_INODE:
2418 hammer2_chain_modify(trans, chain,
2419 HAMMER2_MODIFY_OPTDATA);
2423 * Remaining types are not supported by this function.
2424 * In particular, INDIRECT and LEAF_NODE types are
2425 * handled by create_indirect().
2427 panic("hammer2_chain_create: bad type: %d",
2434 * When reconnecting a chain we must set UPDATE and
2435 * setflush so the flush recognizes that it must update
2436 * the bref in the parent.
2438 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2439 hammer2_chain_ref(chain);
2440 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2445 * We must setflush(parent) to ensure that it recurses through to
2446 * chain. setflush(chain) might not work because ONFLUSH is possibly
2447 * already set in the chain (so it won't recurse up to set it in the
2450 hammer2_chain_setflush(trans, parent);
2459 * Move the chain from its old parent to a new parent. The chain must have
2460 * already been deleted or already disconnected (or never associated) with
2461 * a parent. The chain is reassociated with the new parent and the deleted
2462 * flag will be cleared (no longer deleted). The chain's modification state
2465 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2466 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2467 * FULL. This typically means that the caller is creating the chain after
2468 * doing a hammer2_chain_lookup().
2470 * A non-NULL bref is typically passed when key and keybits must be overridden.
2471 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2472 * from a passed-in bref and uses the old chain's bref for everything else.
2474 * Neither (parent) or (chain) can be errored.
2476 * If (parent) is non-NULL then the new duplicated chain is inserted under
2479 * If (parent) is NULL then the newly duplicated chain is not inserted
2480 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2481 * passing into hammer2_chain_create() after this function returns).
2483 * WARNING! This function calls create which means it can insert indirect
2484 * blocks. This can cause other unrelated chains in the parent to
2485 * be moved to a newly inserted indirect block in addition to the
2489 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2490 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2494 hammer2_chain_t *parent;
2498 * WARNING! We should never resolve DATA to device buffers
2499 * (XXX allow it if the caller did?), and since
2500 * we currently do not have the logical buffer cache
2501 * buffer in-hand to fix its cached physical offset
2502 * we also force the modify code to not COW it. XXX
2505 KKASSERT(chain->parent == NULL);
2506 KKASSERT(chain->error == 0);
2509 * Now create a duplicate of the chain structure, associating
2510 * it with the same core, making it the same size, pointing it
2511 * to the same bref (the same media block).
2514 bref = &chain->bref;
2515 bytes = (hammer2_off_t)1 <<
2516 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2519 * If parent is not NULL the duplicated chain will be entered under
2520 * the parent and the UPDATE bit set to tell flush to update
2523 * We must setflush(parent) to ensure that it recurses through to
2524 * chain. setflush(chain) might not work because ONFLUSH is possibly
2525 * already set in the chain (so it won't recurse up to set it in the
2528 * Having both chains locked is extremely important for atomicy.
2530 if (parentp && (parent = *parentp) != NULL) {
2531 KKASSERT(hammer2_mtx_owned(&parent->lock));
2532 KKASSERT(parent->refs > 0);
2533 KKASSERT(parent->error == 0);
2535 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2536 bref->key, bref->keybits, bref->type,
2537 chain->bytes, flags);
2538 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2539 hammer2_chain_setflush(trans, *parentp);
2544 * Helper function for deleting chains.
2546 * The chain is removed from the live view (the RBTREE) as well as the parent's
2547 * blockmap. Both chain and its parent must be locked.
2549 * parent may not be errored. chain can be errored.
2552 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2553 hammer2_chain_t *parent, hammer2_chain_t *chain,
2558 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2559 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2562 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2564 * Chain is blockmapped, so there must be a parent.
2565 * Atomically remove the chain from the parent and remove
2566 * the blockmap entry.
2568 hammer2_blockref_t *base;
2571 KKASSERT(parent != NULL);
2572 KKASSERT(parent->error == 0);
2573 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2574 hammer2_chain_modify(trans, parent,
2575 HAMMER2_MODIFY_OPTDATA);
2578 * Calculate blockmap pointer
2580 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2581 hammer2_spin_ex(&parent->core.spin);
2583 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2584 atomic_add_int(&parent->core.live_count, -1);
2585 ++parent->core.generation;
2586 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2587 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2588 --parent->core.chain_count;
2589 chain->parent = NULL;
2591 switch(parent->bref.type) {
2592 case HAMMER2_BREF_TYPE_INODE:
2594 * Access the inode's block array. However, there
2595 * is no block array if the inode is flagged
2596 * DIRECTDATA. The DIRECTDATA case typicaly only
2597 * occurs when a hardlink has been shifted up the
2598 * tree and the original inode gets replaced with
2599 * an OBJTYPE_HARDLINK placeholding inode.
2602 (parent->data->ipdata.op_flags &
2603 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2605 &parent->data->ipdata.u.blockset.blockref[0];
2609 count = HAMMER2_SET_COUNT;
2611 case HAMMER2_BREF_TYPE_INDIRECT:
2612 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2614 base = &parent->data->npdata[0];
2617 count = parent->bytes / sizeof(hammer2_blockref_t);
2619 case HAMMER2_BREF_TYPE_VOLUME:
2620 base = &hmp->voldata.sroot_blockset.blockref[0];
2621 count = HAMMER2_SET_COUNT;
2623 case HAMMER2_BREF_TYPE_FREEMAP:
2624 base = &parent->data->npdata[0];
2625 count = HAMMER2_SET_COUNT;
2630 panic("hammer2_flush_pass2: "
2631 "unrecognized blockref type: %d",
2636 * delete blockmapped chain from its parent.
2638 * The parent is not affected by any statistics in chain
2639 * which are pending synchronization. That is, there is
2640 * nothing to undo in the parent since they have not yet
2641 * been incorporated into the parent.
2643 * The parent is affected by statistics stored in inodes.
2644 * Those have already been synchronized, so they must be
2645 * undone. XXX split update possible w/delete in middle?
2648 int cache_index = -1;
2649 hammer2_base_delete(trans, parent, base, count,
2650 &cache_index, chain);
2652 hammer2_spin_unex(&parent->core.spin);
2653 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2655 * Chain is not blockmapped but a parent is present.
2656 * Atomically remove the chain from the parent. There is
2657 * no blockmap entry to remove.
2659 * Because chain was associated with a parent but not
2660 * synchronized, the chain's *_count_up fields contain
2661 * inode adjustment statistics which must be undone.
2663 hammer2_spin_ex(&parent->core.spin);
2664 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2665 atomic_add_int(&parent->core.live_count, -1);
2666 ++parent->core.generation;
2667 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2668 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2669 --parent->core.chain_count;
2670 chain->parent = NULL;
2671 hammer2_spin_unex(&parent->core.spin);
2674 * Chain is not blockmapped and has no parent. This
2675 * is a degenerate case.
2677 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2682 * Create an indirect block that covers one or more of the elements in the
2683 * current parent. Either returns the existing parent with no locking or
2684 * ref changes or returns the new indirect block locked and referenced
2685 * and leaving the original parent lock/ref intact as well.
2687 * If an error occurs, NULL is returned and *errorp is set to the error.
2689 * The returned chain depends on where the specified key falls.
2691 * The key/keybits for the indirect mode only needs to follow three rules:
2693 * (1) That all elements underneath it fit within its key space and
2695 * (2) That all elements outside it are outside its key space.
2697 * (3) When creating the new indirect block any elements in the current
2698 * parent that fit within the new indirect block's keyspace must be
2699 * moved into the new indirect block.
2701 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2702 * keyspace the the current parent, but lookup/iteration rules will
2703 * ensure (and must ensure) that rule (2) for all parents leading up
2704 * to the nearest inode or the root volume header is adhered to. This
2705 * is accomplished by always recursing through matching keyspaces in
2706 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2708 * The current implementation calculates the current worst-case keyspace by
2709 * iterating the current parent and then divides it into two halves, choosing
2710 * whichever half has the most elements (not necessarily the half containing
2711 * the requested key).
2713 * We can also opt to use the half with the least number of elements. This
2714 * causes lower-numbered keys (aka logical file offsets) to recurse through
2715 * fewer indirect blocks and higher-numbered keys to recurse through more.
2716 * This also has the risk of not moving enough elements to the new indirect
2717 * block and being forced to create several indirect blocks before the element
2720 * Must be called with an exclusively locked parent.
2722 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2723 hammer2_key_t *keyp, int keybits,
2724 hammer2_blockref_t *base, int count);
2725 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2726 hammer2_key_t *keyp, int keybits,
2727 hammer2_blockref_t *base, int count);
2730 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2731 hammer2_key_t create_key, int create_bits,
2732 int for_type, int *errorp)
2735 hammer2_blockref_t *base;
2736 hammer2_blockref_t *bref;
2737 hammer2_blockref_t bcopy;
2738 hammer2_chain_t *chain;
2739 hammer2_chain_t *ichain;
2740 hammer2_chain_t dummy;
2741 hammer2_key_t key = create_key;
2742 hammer2_key_t key_beg;
2743 hammer2_key_t key_end;
2744 hammer2_key_t key_next;
2745 int keybits = create_bits;
2752 int maxloops = 300000;
2755 * Calculate the base blockref pointer or NULL if the chain
2756 * is known to be empty. We need to calculate the array count
2757 * for RB lookups either way.
2761 KKASSERT(hammer2_mtx_owned(&parent->lock));
2763 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2764 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2767 switch(parent->bref.type) {
2768 case HAMMER2_BREF_TYPE_INODE:
2769 count = HAMMER2_SET_COUNT;
2771 case HAMMER2_BREF_TYPE_INDIRECT:
2772 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2773 count = parent->bytes / sizeof(hammer2_blockref_t);
2775 case HAMMER2_BREF_TYPE_VOLUME:
2776 count = HAMMER2_SET_COUNT;
2778 case HAMMER2_BREF_TYPE_FREEMAP:
2779 count = HAMMER2_SET_COUNT;
2782 panic("hammer2_chain_create_indirect: "
2783 "unrecognized blockref type: %d",
2789 switch(parent->bref.type) {
2790 case HAMMER2_BREF_TYPE_INODE:
2791 base = &parent->data->ipdata.u.blockset.blockref[0];
2792 count = HAMMER2_SET_COUNT;
2794 case HAMMER2_BREF_TYPE_INDIRECT:
2795 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2796 base = &parent->data->npdata[0];
2797 count = parent->bytes / sizeof(hammer2_blockref_t);
2799 case HAMMER2_BREF_TYPE_VOLUME:
2800 base = &hmp->voldata.sroot_blockset.blockref[0];
2801 count = HAMMER2_SET_COUNT;
2803 case HAMMER2_BREF_TYPE_FREEMAP:
2804 base = &hmp->voldata.freemap_blockset.blockref[0];
2805 count = HAMMER2_SET_COUNT;
2808 panic("hammer2_chain_create_indirect: "
2809 "unrecognized blockref type: %d",
2817 * dummy used in later chain allocation (no longer used for lookups).
2819 bzero(&dummy, sizeof(dummy));
2822 * When creating an indirect block for a freemap node or leaf
2823 * the key/keybits must be fitted to static radix levels because
2824 * particular radix levels use particular reserved blocks in the
2827 * This routine calculates the key/radix of the indirect block
2828 * we need to create, and whether it is on the high-side or the
2831 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2832 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2833 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2836 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2841 * Normalize the key for the radix being represented, keeping the
2842 * high bits and throwing away the low bits.
2844 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2847 * How big should our new indirect block be? It has to be at least
2848 * as large as its parent.
2850 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2851 nbytes = HAMMER2_IND_BYTES_MIN;
2853 nbytes = HAMMER2_IND_BYTES_MAX;
2854 if (nbytes < count * sizeof(hammer2_blockref_t))
2855 nbytes = count * sizeof(hammer2_blockref_t);
2858 * Ok, create our new indirect block
2860 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2861 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2862 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2864 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2866 dummy.bref.key = key;
2867 dummy.bref.keybits = keybits;
2868 dummy.bref.data_off = hammer2_getradix(nbytes);
2869 dummy.bref.methods = parent->bref.methods;
2871 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2872 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2873 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2874 /* ichain has one ref at this point */
2877 * We have to mark it modified to allocate its block, but use
2878 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2879 * it won't be acted upon by the flush code.
2881 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2884 * Iterate the original parent and move the matching brefs into
2885 * the new indirect block.
2887 * XXX handle flushes.
2890 key_end = HAMMER2_KEY_MAX;
2892 hammer2_spin_ex(&parent->core.spin);
2897 if (++loops > 100000) {
2898 hammer2_spin_unex(&parent->core.spin);
2899 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2900 reason, parent, base, count, key_next);
2904 * NOTE: spinlock stays intact, returned chain (if not NULL)
2905 * is not referenced or locked which means that we
2906 * cannot safely check its flagged / deletion status
2909 chain = hammer2_combined_find(parent, base, count,
2910 &cache_index, &key_next,
2913 generation = parent->core.generation;
2916 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2919 * Skip keys that are not within the key/radix of the new
2920 * indirect block. They stay in the parent.
2922 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2923 (key ^ bref->key)) != 0) {
2924 goto next_key_spinlocked;
2928 * Load the new indirect block by acquiring the related
2929 * chains (potentially from media as it might not be
2930 * in-memory). Then move it to the new parent (ichain)
2931 * via DELETE-DUPLICATE.
2933 * chain is referenced but not locked. We must lock the
2934 * chain to obtain definitive DUPLICATED/DELETED state
2938 * Use chain already present in the RBTREE
2940 hammer2_chain_ref(chain);
2941 hammer2_spin_unex(&parent->core.spin);
2942 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2945 * Get chain for blockref element. _get returns NULL
2946 * on insertion race.
2949 hammer2_spin_unex(&parent->core.spin);
2950 chain = hammer2_chain_get(parent, generation, &bcopy);
2951 if (chain == NULL) {
2953 hammer2_spin_ex(&parent->core.spin);
2956 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2957 kprintf("REASON 2\n");
2959 hammer2_chain_drop(chain);
2960 hammer2_spin_ex(&parent->core.spin);
2963 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2967 * This is always live so if the chain has been deleted
2968 * we raced someone and we have to retry.
2970 * NOTE: Lookups can race delete-duplicate because
2971 * delete-duplicate does not lock the parent's core
2972 * (they just use the spinlock on the core). We must
2973 * check for races by comparing the DUPLICATED flag before
2974 * releasing the spinlock with the flag after locking the
2977 * (note reversed logic for this one)
2979 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2980 hammer2_chain_unlock(chain);
2981 hammer2_chain_drop(chain);
2986 * Shift the chain to the indirect block.
2988 * WARNING! No reason for us to load chain data, pass NOSTATS
2989 * to prevent delete/insert from trying to access
2990 * inode stats (and thus asserting if there is no
2991 * chain->data loaded).
2993 hammer2_chain_delete(trans, parent, chain,
2994 HAMMER2_DELETE_NOSTATS);
2995 hammer2_chain_rename(trans, NULL, &ichain, chain,
2996 HAMMER2_INSERT_NOSTATS);
2997 hammer2_chain_unlock(chain);
2998 hammer2_chain_drop(chain);
2999 KKASSERT(parent->refs > 0);
3002 hammer2_spin_ex(&parent->core.spin);
3003 next_key_spinlocked:
3004 if (--maxloops == 0)
3005 panic("hammer2_chain_create_indirect: maxloops");
3007 if (key_next == 0 || key_next > key_end)
3012 hammer2_spin_unex(&parent->core.spin);
3015 * Insert the new indirect block into the parent now that we've
3016 * cleared out some entries in the parent. We calculated a good
3017 * insertion index in the loop above (ichain->index).
3019 * We don't have to set UPDATE here because we mark ichain
3020 * modified down below (so the normal modified -> flush -> set-moved
3021 * sequence applies).
3023 * The insertion shouldn't race as this is a completely new block
3024 * and the parent is locked.
3026 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3027 hammer2_chain_insert(parent, ichain,
3028 HAMMER2_CHAIN_INSERT_SPIN |
3029 HAMMER2_CHAIN_INSERT_LIVE,
3033 * Make sure flushes propogate after our manual insertion.
3035 hammer2_chain_setflush(trans, ichain);
3036 hammer2_chain_setflush(trans, parent);
3039 * Figure out what to return.
3041 if (~(((hammer2_key_t)1 << keybits) - 1) &
3042 (create_key ^ key)) {
3044 * Key being created is outside the key range,
3045 * return the original parent.
3047 hammer2_chain_unlock(ichain);
3048 hammer2_chain_drop(ichain);
3051 * Otherwise its in the range, return the new parent.
3052 * (leave both the new and old parent locked).
3061 * Calculate the keybits and highside/lowside of the freemap node the
3062 * caller is creating.
3064 * This routine will specify the next higher-level freemap key/radix
3065 * representing the lowest-ordered set. By doing so, eventually all
3066 * low-ordered sets will be moved one level down.
3068 * We have to be careful here because the freemap reserves a limited
3069 * number of blocks for a limited number of levels. So we can't just
3070 * push indiscriminately.
3073 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3074 int keybits, hammer2_blockref_t *base, int count)
3076 hammer2_chain_t *chain;
3077 hammer2_blockref_t *bref;
3079 hammer2_key_t key_beg;
3080 hammer2_key_t key_end;
3081 hammer2_key_t key_next;
3085 int maxloops = 300000;
3093 * Calculate the range of keys in the array being careful to skip
3094 * slots which are overridden with a deletion.
3097 key_end = HAMMER2_KEY_MAX;
3099 hammer2_spin_ex(&parent->core.spin);
3102 if (--maxloops == 0) {
3103 panic("indkey_freemap shit %p %p:%d\n",
3104 parent, base, count);
3106 chain = hammer2_combined_find(parent, base, count,
3107 &cache_index, &key_next,
3118 * Skip deleted chains.
3120 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3121 if (key_next == 0 || key_next > key_end)
3128 * Use the full live (not deleted) element for the scan
3129 * iteration. HAMMER2 does not allow partial replacements.
3131 * XXX should be built into hammer2_combined_find().
3133 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3135 if (keybits > bref->keybits) {
3137 keybits = bref->keybits;
3138 } else if (keybits == bref->keybits && bref->key < key) {
3145 hammer2_spin_unex(&parent->core.spin);
3148 * Return the keybits for a higher-level FREEMAP_NODE covering
3152 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3153 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3155 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3156 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3158 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3159 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3161 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3162 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3164 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3165 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3167 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3168 panic("hammer2_chain_indkey_freemap: level too high");
3171 panic("hammer2_chain_indkey_freemap: bad radix");
3180 * Calculate the keybits and highside/lowside of the indirect block the
3181 * caller is creating.
3184 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3185 int keybits, hammer2_blockref_t *base, int count)
3187 hammer2_blockref_t *bref;
3188 hammer2_chain_t *chain;
3189 hammer2_key_t key_beg;
3190 hammer2_key_t key_end;
3191 hammer2_key_t key_next;
3197 int maxloops = 300000;
3204 * Calculate the range of keys in the array being careful to skip
3205 * slots which are overridden with a deletion. Once the scan
3206 * completes we will cut the key range in half and shift half the
3207 * range into the new indirect block.
3210 key_end = HAMMER2_KEY_MAX;
3212 hammer2_spin_ex(&parent->core.spin);
3215 if (--maxloops == 0) {
3216 panic("indkey_freemap shit %p %p:%d\n",
3217 parent, base, count);
3219 chain = hammer2_combined_find(parent, base, count,
3220 &cache_index, &key_next,
3231 * NOTE: No need to check DUPLICATED here because we do
3232 * not release the spinlock.
3234 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3235 if (key_next == 0 || key_next > key_end)
3242 * Use the full live (not deleted) element for the scan
3243 * iteration. HAMMER2 does not allow partial replacements.
3245 * XXX should be built into hammer2_combined_find().
3247 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3250 * Expand our calculated key range (key, keybits) to fit
3251 * the scanned key. nkeybits represents the full range
3252 * that we will later cut in half (two halves @ nkeybits - 1).
3255 if (nkeybits < bref->keybits) {
3256 if (bref->keybits > 64) {
3257 kprintf("bad bref chain %p bref %p\n",
3261 nkeybits = bref->keybits;
3263 while (nkeybits < 64 &&
3264 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3265 (key ^ bref->key)) != 0) {
3270 * If the new key range is larger we have to determine
3271 * which side of the new key range the existing keys fall
3272 * under by checking the high bit, then collapsing the
3273 * locount into the hicount or vise-versa.
3275 if (keybits != nkeybits) {
3276 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3287 * The newly scanned key will be in the lower half or the
3288 * upper half of the (new) key range.
3290 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3299 hammer2_spin_unex(&parent->core.spin);
3300 bref = NULL; /* now invalid (safety) */
3303 * Adjust keybits to represent half of the full range calculated
3304 * above (radix 63 max)
3309 * Select whichever half contains the most elements. Theoretically
3310 * we can select either side as long as it contains at least one
3311 * element (in order to ensure that a free slot is present to hold
3312 * the indirect block).
3314 if (hammer2_indirect_optimize) {
3316 * Insert node for least number of keys, this will arrange
3317 * the first few blocks of a large file or the first few
3318 * inodes in a directory with fewer indirect blocks when
3321 if (hicount < locount && hicount != 0)
3322 key |= (hammer2_key_t)1 << keybits;
3324 key &= ~(hammer2_key_t)1 << keybits;
3327 * Insert node for most number of keys, best for heavily
3330 if (hicount > locount)
3331 key |= (hammer2_key_t)1 << keybits;
3333 key &= ~(hammer2_key_t)1 << keybits;
3341 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3344 * Both parent and chain must be locked exclusively.
3346 * This function will modify the parent if the blockref requires removal
3347 * from the parent's block table.
3349 * This function is NOT recursive. Any entity already pushed into the
3350 * chain (such as an inode) may still need visibility into its contents,
3351 * as well as the ability to read and modify the contents. For example,
3352 * for an unlinked file which is still open.
3355 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3356 hammer2_chain_t *chain, int flags)
3358 KKASSERT(hammer2_mtx_owned(&chain->lock));
3361 * Nothing to do if already marked.
3363 * We need the spinlock on the core whos RBTREE contains chain
3364 * to protect against races.
3366 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3367 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3368 chain->parent == parent);
3369 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3373 * To avoid losing track of a permanent deletion we add the chain
3374 * to the delayed flush queue. If were to flush it right now the
3375 * parent would end up in a modified state and generate I/O.
3376 * The delayed queue gives the parent a chance to be deleted to
3379 if (flags & HAMMER2_DELETE_PERMANENT) {
3380 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3381 hammer2_delayed_flush(trans, chain);
3383 /* XXX might not be needed */
3384 hammer2_chain_setflush(trans, chain);
3389 * Returns the index of the nearest element in the blockref array >= elm.
3390 * Returns (count) if no element could be found.
3392 * Sets *key_nextp to the next key for loop purposes but does not modify
3393 * it if the next key would be higher than the current value of *key_nextp.
3394 * Note that *key_nexp can overflow to 0, which should be tested by the
3397 * (*cache_indexp) is a heuristic and can be any value without effecting
3400 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3401 * held through the operation.
3404 hammer2_base_find(hammer2_chain_t *parent,
3405 hammer2_blockref_t *base, int count,
3406 int *cache_indexp, hammer2_key_t *key_nextp,
3407 hammer2_key_t key_beg, hammer2_key_t key_end)
3409 hammer2_blockref_t *scan;
3410 hammer2_key_t scan_end;
3415 * Require the live chain's already have their core's counted
3416 * so we can optimize operations.
3418 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3423 if (count == 0 || base == NULL)
3427 * Sequential optimization using *cache_indexp. This is the most
3430 * We can avoid trailing empty entries on live chains, otherwise
3431 * we might have to check the whole block array.
3435 limit = parent->core.live_zero;
3440 KKASSERT(i < count);
3446 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3453 * Search forwards, stop when we find a scan element which
3454 * encloses the key or until we know that there are no further
3458 if (scan->type != 0) {
3459 scan_end = scan->key +
3460 ((hammer2_key_t)1 << scan->keybits) - 1;
3461 if (scan->key > key_beg || scan_end >= key_beg)
3474 scan_end = scan->key +
3475 ((hammer2_key_t)1 << scan->keybits);
3476 if (scan_end && (*key_nextp > scan_end ||
3478 *key_nextp = scan_end;
3486 * Do a combined search and return the next match either from the blockref
3487 * array or from the in-memory chain. Sets *bresp to the returned bref in
3488 * both cases, or sets it to NULL if the search exhausted. Only returns
3489 * a non-NULL chain if the search matched from the in-memory chain.
3491 * When no in-memory chain has been found and a non-NULL bref is returned
3495 * The returned chain is not locked or referenced. Use the returned bref
3496 * to determine if the search exhausted or not. Iterate if the base find
3497 * is chosen but matches a deleted chain.
3499 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3500 * held through the operation.
3502 static hammer2_chain_t *
3503 hammer2_combined_find(hammer2_chain_t *parent,
3504 hammer2_blockref_t *base, int count,
3505 int *cache_indexp, hammer2_key_t *key_nextp,
3506 hammer2_key_t key_beg, hammer2_key_t key_end,
3507 hammer2_blockref_t **bresp)
3509 hammer2_blockref_t *bref;
3510 hammer2_chain_t *chain;
3514 * Lookup in block array and in rbtree.
3516 *key_nextp = key_end + 1;
3517 i = hammer2_base_find(parent, base, count, cache_indexp,
3518 key_nextp, key_beg, key_end);
3519 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3524 if (i == count && chain == NULL) {
3530 * Only chain matched.
3533 bref = &chain->bref;
3538 * Only blockref matched.
3540 if (chain == NULL) {
3546 * Both in-memory and blockref matched, select the nearer element.
3548 * If both are flush with the left-hand side or both are the
3549 * same distance away, select the chain. In this situation the
3550 * chain must have been loaded from the matching blockmap.
3552 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3553 chain->bref.key == base[i].key) {
3554 KKASSERT(chain->bref.key == base[i].key);
3555 bref = &chain->bref;
3560 * Select the nearer key
3562 if (chain->bref.key < base[i].key) {
3563 bref = &chain->bref;
3570 * If the bref is out of bounds we've exhausted our search.
3573 if (bref->key > key_end) {
3583 * Locate the specified block array element and delete it. The element
3586 * The spin lock on the related chain must be held.
3588 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3589 * need to be adjusted when we commit the media change.
3592 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3593 hammer2_blockref_t *base, int count,
3594 int *cache_indexp, hammer2_chain_t *chain)
3596 hammer2_blockref_t *elm = &chain->bref;
3597 hammer2_key_t key_next;
3601 * Delete element. Expect the element to exist.
3603 * XXX see caller, flush code not yet sophisticated enough to prevent
3604 * re-flushed in some cases.
3606 key_next = 0; /* max range */
3607 i = hammer2_base_find(parent, base, count, cache_indexp,
3608 &key_next, elm->key, elm->key);
3609 if (i == count || base[i].type == 0 ||
3610 base[i].key != elm->key ||
3611 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3612 base[i].keybits != elm->keybits)) {
3613 hammer2_spin_unex(&parent->core.spin);
3614 panic("delete base %p element not found at %d/%d elm %p\n",
3615 base, i, count, elm);
3618 bzero(&base[i], sizeof(*base));
3621 * We can only optimize parent->core.live_zero for live chains.
3623 if (parent->core.live_zero == i + 1) {
3624 while (--i >= 0 && base[i].type == 0)
3626 parent->core.live_zero = i + 1;
3630 * Clear appropriate blockmap flags in chain.
3632 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3633 HAMMER2_CHAIN_BMAPUPD);
3637 * Insert the specified element. The block array must not already have the
3638 * element and must have space available for the insertion.
3640 * The spin lock on the related chain must be held.
3642 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3643 * need to be adjusted when we commit the media change.
3646 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3647 hammer2_blockref_t *base, int count,
3648 int *cache_indexp, hammer2_chain_t *chain)
3650 hammer2_blockref_t *elm = &chain->bref;
3651 hammer2_key_t key_next;
3660 * Insert new element. Expect the element to not already exist
3661 * unless we are replacing it.
3663 * XXX see caller, flush code not yet sophisticated enough to prevent
3664 * re-flushed in some cases.
3666 key_next = 0; /* max range */
3667 i = hammer2_base_find(parent, base, count, cache_indexp,
3668 &key_next, elm->key, elm->key);
3671 * Shortcut fill optimization, typical ordered insertion(s) may not
3674 KKASSERT(i >= 0 && i <= count);
3677 * Set appropriate blockmap flags in chain.
3679 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3682 * We can only optimize parent->core.live_zero for live chains.
3684 if (i == count && parent->core.live_zero < count) {
3685 i = parent->core.live_zero++;
3690 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3691 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3692 hammer2_spin_unex(&parent->core.spin);
3693 panic("insert base %p overlapping elements at %d elm %p\n",
3698 * Try to find an empty slot before or after.
3702 while (j > 0 || k < count) {
3704 if (j >= 0 && base[j].type == 0) {
3708 bcopy(&base[j+1], &base[j],
3709 (i - j - 1) * sizeof(*base));
3715 if (k < count && base[k].type == 0) {
3716 bcopy(&base[i], &base[i+1],
3717 (k - i) * sizeof(hammer2_blockref_t));
3721 * We can only update parent->core.live_zero for live
3724 if (parent->core.live_zero <= k)
3725 parent->core.live_zero = k + 1;
3730 panic("hammer2_base_insert: no room!");
3737 for (l = 0; l < count; ++l) {
3739 key_next = base[l].key +
3740 ((hammer2_key_t)1 << base[l].keybits) - 1;
3744 while (++l < count) {
3746 if (base[l].key <= key_next)
3747 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3748 key_next = base[l].key +
3749 ((hammer2_key_t)1 << base[l].keybits) - 1;
3759 * Sort the blockref array for the chain. Used by the flush code to
3760 * sort the blockref[] array.
3762 * The chain must be exclusively locked AND spin-locked.
3764 typedef hammer2_blockref_t *hammer2_blockref_p;
3768 hammer2_base_sort_callback(const void *v1, const void *v2)
3770 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3771 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3774 * Make sure empty elements are placed at the end of the array
3776 if (bref1->type == 0) {
3777 if (bref2->type == 0)
3780 } else if (bref2->type == 0) {
3787 if (bref1->key < bref2->key)
3789 if (bref1->key > bref2->key)
3795 hammer2_base_sort(hammer2_chain_t *chain)
3797 hammer2_blockref_t *base;
3800 switch(chain->bref.type) {
3801 case HAMMER2_BREF_TYPE_INODE:
3803 * Special shortcut for embedded data returns the inode
3804 * itself. Callers must detect this condition and access
3805 * the embedded data (the strategy code does this for us).
3807 * This is only applicable to regular files and softlinks.
3809 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3811 base = &chain->data->ipdata.u.blockset.blockref[0];
3812 count = HAMMER2_SET_COUNT;
3814 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3815 case HAMMER2_BREF_TYPE_INDIRECT:
3817 * Optimize indirect blocks in the INITIAL state to avoid
3820 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3821 base = &chain->data->npdata[0];
3822 count = chain->bytes / sizeof(hammer2_blockref_t);
3824 case HAMMER2_BREF_TYPE_VOLUME:
3825 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3826 count = HAMMER2_SET_COUNT;
3828 case HAMMER2_BREF_TYPE_FREEMAP:
3829 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3830 count = HAMMER2_SET_COUNT;
3833 kprintf("hammer2_chain_lookup: unrecognized "
3834 "blockref(A) type: %d",
3837 tsleep(&base, 0, "dead", 0);
3838 panic("hammer2_chain_lookup: unrecognized "
3839 "blockref(A) type: %d",
3841 base = NULL; /* safety */
3842 count = 0; /* safety */
3844 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3850 * Chain memory management
3853 hammer2_chain_wait(hammer2_chain_t *chain)
3855 tsleep(chain, 0, "chnflw", 1);
3858 const hammer2_media_data_t *
3859 hammer2_chain_rdata(hammer2_chain_t *chain)
3861 KKASSERT(chain->data != NULL);
3862 return (chain->data);
3865 hammer2_media_data_t *
3866 hammer2_chain_wdata(hammer2_chain_t *chain)
3868 KKASSERT(chain->data != NULL);
3869 return (chain->data);
3873 * Set the check data for a chain. This can be a heavy-weight operation
3874 * and typically only runs on-flush. For file data check data is calculated
3875 * when the logical buffers are flushed.
3878 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3880 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3882 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3883 case HAMMER2_CHECK_NONE:
3885 case HAMMER2_CHECK_DISABLED:
3887 case HAMMER2_CHECK_ISCSI32:
3888 chain->bref.check.iscsi32.value =
3889 hammer2_icrc32(bdata, chain->bytes);
3891 case HAMMER2_CHECK_CRC64:
3892 chain->bref.check.crc64.value = 0;
3895 case HAMMER2_CHECK_SHA192:
3897 SHA256_CTX hash_ctx;
3899 uint8_t digest[SHA256_DIGEST_LENGTH];
3900 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3903 SHA256_Init(&hash_ctx);
3904 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3905 SHA256_Final(u.digest, &hash_ctx);
3906 u.digest64[2] ^= u.digest64[3];
3908 chain->bref.check.sha192.data,
3909 sizeof(chain->bref.check.sha192.data));
3912 case HAMMER2_CHECK_FREEMAP:
3913 chain->bref.check.freemap.icrc32 =
3914 hammer2_icrc32(bdata, chain->bytes);
3917 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3918 chain->bref.methods);
3924 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3928 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3931 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3932 case HAMMER2_CHECK_NONE:
3935 case HAMMER2_CHECK_DISABLED:
3938 case HAMMER2_CHECK_ISCSI32:
3939 r = (chain->bref.check.iscsi32.value ==
3940 hammer2_icrc32(bdata, chain->bytes));
3942 case HAMMER2_CHECK_CRC64:
3943 r = (chain->bref.check.crc64.value == 0);
3946 case HAMMER2_CHECK_SHA192:
3948 SHA256_CTX hash_ctx;
3950 uint8_t digest[SHA256_DIGEST_LENGTH];
3951 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3954 SHA256_Init(&hash_ctx);
3955 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3956 SHA256_Final(u.digest, &hash_ctx);
3957 u.digest64[2] ^= u.digest64[3];
3959 chain->bref.check.sha192.data,
3960 sizeof(chain->bref.check.sha192.data)) == 0) {
3967 case HAMMER2_CHECK_FREEMAP:
3968 r = (chain->bref.check.freemap.icrc32 ==
3969 hammer2_icrc32(bdata, chain->bytes));
3971 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3972 chain->bref.check.freemap.icrc32,
3973 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3975 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3976 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3981 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3982 chain->bref.methods);