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)
1021 chain->data_count += (ssize_t)(nbytes - obytes);
1024 * Make sure the old data is instantiated so we can copy it. If this
1025 * is a data block, the device data may be superfluous since the data
1026 * might be in a logical block, but compressed or encrypted data is
1029 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1031 hammer2_chain_modify(trans, chain, 0);
1034 * Relocate the block, even if making it smaller (because different
1035 * block sizes may be in different regions).
1037 * (data blocks only, we aren't copying the storage here).
1039 hammer2_freemap_alloc(trans, chain, nbytes);
1040 chain->bytes = nbytes;
1041 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1044 * We don't want the followup chain_modify() to try to copy data
1045 * from the old (wrong-sized) buffer. It won't know how much to
1046 * copy. This case should only occur during writes when the
1047 * originator already has the data to write in-hand.
1050 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1051 hammer2_io_brelse(&chain->dio);
1057 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1059 hammer2_blockref_t obref;
1068 obref = chain->bref;
1069 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1072 * Data is not optional for freemap chains (we must always be sure
1073 * to copy the data on COW storage allocations).
1075 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1076 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1077 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1078 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1082 * Data must be resolved if already assigned, unless explicitly
1083 * flagged otherwise.
1085 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1086 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1087 hammer2_chain_load_data(chain);
1091 * Set MODIFIED to indicate that the chain has been modified.
1092 * Set UPDATE to ensure that the blockref is updated in the parent.
1094 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1095 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1096 hammer2_chain_ref(chain);
1097 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1102 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1103 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1104 hammer2_chain_ref(chain);
1108 * The modification or re-modification requires an allocation and
1111 * We normally always allocate new storage here. If storage exists
1112 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1114 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1115 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1116 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1118 hammer2_freemap_alloc(trans, chain, chain->bytes);
1119 /* XXX failed allocation */
1124 * Update mirror_tid and modify_tid. modify_tid is only updated
1125 * automatically by this function when used from the frontend.
1126 * Flushes and synchronization adjust the flag manually.
1128 * NOTE: chain->pmp could be the device spmp.
1130 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1131 if (chain->pmp && (trans->flags & (HAMMER2_TRANS_KEEPMODIFY |
1132 HAMMER2_TRANS_ISFLUSH)) == 0) {
1133 chain->bref.modify_tid = chain->pmp->modify_tid + 1;
1137 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1138 * requires updating as well as to tell the delete code that the
1139 * chain's blockref might not exactly match (in terms of physical size
1140 * or block offset) the one in the parent's blocktable. The base key
1141 * of course will still match.
1143 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1144 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1147 * Short-cut data blocks which the caller does not need an actual
1148 * data reference to (aka OPTDATA), as long as the chain does not
1149 * already have a data pointer to the data. This generally means
1150 * that the modifications are being done via the logical buffer cache.
1151 * The INITIAL flag relates only to the device data buffer and thus
1152 * remains unchange in this situation.
1154 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1155 (flags & HAMMER2_MODIFY_OPTDATA) &&
1156 chain->data == NULL) {
1161 * Clearing the INITIAL flag (for indirect blocks) indicates that
1162 * we've processed the uninitialized storage allocation.
1164 * If this flag is already clear we are likely in a copy-on-write
1165 * situation but we have to be sure NOT to bzero the storage if
1166 * no data is present.
1168 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1169 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1176 * Instantiate data buffer and possibly execute COW operation
1178 switch(chain->bref.type) {
1179 case HAMMER2_BREF_TYPE_VOLUME:
1180 case HAMMER2_BREF_TYPE_FREEMAP:
1182 * The data is embedded, no copy-on-write operation is
1185 KKASSERT(chain->dio == NULL);
1187 case HAMMER2_BREF_TYPE_INODE:
1188 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1189 case HAMMER2_BREF_TYPE_DATA:
1190 case HAMMER2_BREF_TYPE_INDIRECT:
1191 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1193 * Perform the copy-on-write operation
1195 * zero-fill or copy-on-write depending on whether
1196 * chain->data exists or not and set the dirty state for
1197 * the new buffer. hammer2_io_new() will handle the
1200 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1203 error = hammer2_io_new(hmp, chain->bref.data_off,
1204 chain->bytes, &dio);
1206 error = hammer2_io_bread(hmp, chain->bref.data_off,
1207 chain->bytes, &dio);
1209 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1212 * If an I/O error occurs make sure callers cannot accidently
1213 * modify the old buffer's contents and corrupt the filesystem.
1216 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1218 chain->error = HAMMER2_ERROR_IO;
1219 hammer2_io_brelse(&dio);
1220 hammer2_io_brelse(&chain->dio);
1225 bdata = hammer2_io_data(dio, chain->bref.data_off);
1228 KKASSERT(chain->dio != NULL);
1229 if (chain->data != (void *)bdata) {
1230 bcopy(chain->data, bdata, chain->bytes);
1232 } else if (wasinitial == 0) {
1234 * We have a problem. We were asked to COW but
1235 * we don't have any data to COW with!
1237 panic("hammer2_chain_modify: having a COW %p\n",
1242 * Retire the old buffer, replace with the new. Dirty or
1243 * redirty the new buffer.
1245 * WARNING! The system buffer cache may have already flushed
1246 * the buffer, so we must be sure to [re]dirty it
1247 * for further modification.
1250 hammer2_io_brelse(&chain->dio);
1251 chain->data = (void *)bdata;
1253 hammer2_io_setdirty(dio); /* modified by bcopy above */
1256 panic("hammer2_chain_modify: illegal non-embedded type %d",
1263 * setflush on parent indicating that the parent must recurse down
1264 * to us. Do not call on chain itself which might already have it
1268 hammer2_chain_setflush(trans, chain->parent);
1272 * Volume header data locks
1275 hammer2_voldata_lock(hammer2_dev_t *hmp)
1277 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1281 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1283 lockmgr(&hmp->vollk, LK_RELEASE);
1287 hammer2_voldata_modify(hammer2_dev_t *hmp)
1289 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1290 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1291 hammer2_chain_ref(&hmp->vchain);
1292 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1297 * This function returns the chain at the nearest key within the specified
1298 * range. The returned chain will be referenced but not locked.
1300 * This function will recurse through chain->rbtree as necessary and will
1301 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1302 * the iteration value is less than the current value of *key_nextp.
1304 * The caller should use (*key_nextp) to calculate the actual range of
1305 * the returned element, which will be (key_beg to *key_nextp - 1), because
1306 * there might be another element which is superior to the returned element
1309 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1310 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1311 * it will wind up being (key_end + 1).
1313 * WARNING! Must be called with child's spinlock held. Spinlock remains
1314 * held through the operation.
1316 struct hammer2_chain_find_info {
1317 hammer2_chain_t *best;
1318 hammer2_key_t key_beg;
1319 hammer2_key_t key_end;
1320 hammer2_key_t key_next;
1323 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1324 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1328 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1329 hammer2_key_t key_beg, hammer2_key_t key_end)
1331 struct hammer2_chain_find_info info;
1334 info.key_beg = key_beg;
1335 info.key_end = key_end;
1336 info.key_next = *key_nextp;
1338 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1339 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1341 *key_nextp = info.key_next;
1343 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1344 parent, key_beg, key_end, *key_nextp);
1352 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1354 struct hammer2_chain_find_info *info = data;
1355 hammer2_key_t child_beg;
1356 hammer2_key_t child_end;
1358 child_beg = child->bref.key;
1359 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1361 if (child_end < info->key_beg)
1363 if (child_beg > info->key_end)
1370 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1372 struct hammer2_chain_find_info *info = data;
1373 hammer2_chain_t *best;
1374 hammer2_key_t child_end;
1377 * WARNING! Do not discard DUPLICATED chains, it is possible that
1378 * we are catching an insertion half-way done. If a
1379 * duplicated chain turns out to be the best choice the
1380 * caller will re-check its flags after locking it.
1382 * WARNING! Layerq is scanned forwards, exact matches should keep
1383 * the existing info->best.
1385 if ((best = info->best) == NULL) {
1387 * No previous best. Assign best
1390 } else if (best->bref.key <= info->key_beg &&
1391 child->bref.key <= info->key_beg) {
1396 /*info->best = child;*/
1397 } else if (child->bref.key < best->bref.key) {
1399 * Child has a nearer key and best is not flush with key_beg.
1400 * Set best to child. Truncate key_next to the old best key.
1403 if (info->key_next > best->bref.key || info->key_next == 0)
1404 info->key_next = best->bref.key;
1405 } else if (child->bref.key == best->bref.key) {
1407 * If our current best is flush with the child then this
1408 * is an illegal overlap.
1410 * key_next will automatically be limited to the smaller of
1411 * the two end-points.
1417 * Keep the current best but truncate key_next to the child's
1420 * key_next will also automatically be limited to the smaller
1421 * of the two end-points (probably not necessary for this case
1422 * but we do it anyway).
1424 if (info->key_next > child->bref.key || info->key_next == 0)
1425 info->key_next = child->bref.key;
1429 * Always truncate key_next based on child's end-of-range.
1431 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1432 if (child_end && (info->key_next > child_end || info->key_next == 0))
1433 info->key_next = child_end;
1439 * Retrieve the specified chain from a media blockref, creating the
1440 * in-memory chain structure which reflects it.
1442 * To handle insertion races pass the INSERT_RACE flag along with the
1443 * generation number of the core. NULL will be returned if the generation
1444 * number changes before we have a chance to insert the chain. Insert
1445 * races can occur because the parent might be held shared.
1447 * Caller must hold the parent locked shared or exclusive since we may
1448 * need the parent's bref array to find our block.
1450 * WARNING! chain->pmp is always set to NULL for any chain representing
1451 * part of the super-root topology.
1454 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1455 hammer2_blockref_t *bref)
1457 hammer2_dev_t *hmp = parent->hmp;
1458 hammer2_chain_t *chain;
1462 * Allocate a chain structure representing the existing media
1463 * entry. Resulting chain has one ref and is not locked.
1465 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1466 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1468 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1469 /* ref'd chain returned */
1472 * Flag that the chain is in the parent's blockmap so delete/flush
1473 * knows what to do with it.
1475 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1478 * Link the chain into its parent. A spinlock is required to safely
1479 * access the RBTREE, and it is possible to collide with another
1480 * hammer2_chain_get() operation because the caller might only hold
1481 * a shared lock on the parent.
1483 KKASSERT(parent->refs > 0);
1484 error = hammer2_chain_insert(parent, chain,
1485 HAMMER2_CHAIN_INSERT_SPIN |
1486 HAMMER2_CHAIN_INSERT_RACE,
1489 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1490 kprintf("chain %p get race\n", chain);
1491 hammer2_chain_drop(chain);
1494 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1498 * Return our new chain referenced but not locked, or NULL if
1505 * Lookup initialization/completion API
1508 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1510 hammer2_chain_ref(parent);
1511 if (flags & HAMMER2_LOOKUP_SHARED) {
1512 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1513 HAMMER2_RESOLVE_SHARED);
1515 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1521 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1524 hammer2_chain_unlock(parent);
1525 hammer2_chain_drop(parent);
1531 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1533 hammer2_chain_t *oparent;
1534 hammer2_chain_t *nparent;
1537 * Be careful of order, oparent must be unlocked before nparent
1538 * is locked below to avoid a deadlock.
1541 hammer2_spin_ex(&oparent->core.spin);
1542 nparent = oparent->parent;
1543 hammer2_chain_ref(nparent);
1544 hammer2_spin_unex(&oparent->core.spin);
1546 hammer2_chain_unlock(oparent);
1547 hammer2_chain_drop(oparent);
1551 hammer2_chain_lock(nparent, how);
1558 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1559 * (*parentp) typically points to an inode but can also point to a related
1560 * indirect block and this function will recurse upwards and find the inode
1563 * (*parentp) must be exclusively locked and referenced and can be an inode
1564 * or an existing indirect block within the inode.
1566 * On return (*parentp) will be modified to point at the deepest parent chain
1567 * element encountered during the search, as a helper for an insertion or
1568 * deletion. The new (*parentp) will be locked and referenced and the old
1569 * will be unlocked and dereferenced (no change if they are both the same).
1571 * The matching chain will be returned exclusively locked. If NOLOCK is
1572 * requested the chain will be returned only referenced. Note that the
1573 * parent chain must always be locked shared or exclusive, matching the
1574 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1575 * when NOLOCK is specified but that complicates matters if *parentp must
1576 * inherit the chain.
1578 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1579 * data pointer or can otherwise be in flux.
1581 * NULL is returned if no match was found, but (*parentp) will still
1582 * potentially be adjusted.
1584 * If a fatal error occurs (typically an I/O error), a dummy chain is
1585 * returned with chain->error and error-identifying information set. This
1586 * chain will assert if you try to do anything fancy with it.
1588 * XXX Depending on where the error occurs we should allow continued iteration.
1590 * On return (*key_nextp) will point to an iterative value for key_beg.
1591 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1593 * This function will also recurse up the chain if the key is not within the
1594 * current parent's range. (*parentp) can never be set to NULL. An iteration
1595 * can simply allow (*parentp) to float inside the loop.
1597 * NOTE! chain->data is not always resolved. By default it will not be
1598 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1599 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1600 * BREF_TYPE_DATA as the device buffer can alias the logical file
1604 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1605 hammer2_key_t key_beg, hammer2_key_t key_end,
1606 int *cache_indexp, int flags)
1609 hammer2_chain_t *parent;
1610 hammer2_chain_t *chain;
1611 hammer2_blockref_t *base;
1612 hammer2_blockref_t *bref;
1613 hammer2_blockref_t bcopy;
1614 hammer2_key_t scan_beg;
1615 hammer2_key_t scan_end;
1617 int how_always = HAMMER2_RESOLVE_ALWAYS;
1618 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1621 int maxloops = 300000;
1623 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1624 how_maybe = how_always;
1625 how = HAMMER2_RESOLVE_ALWAYS;
1626 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1627 how = HAMMER2_RESOLVE_NEVER;
1629 how = HAMMER2_RESOLVE_MAYBE;
1631 if (flags & HAMMER2_LOOKUP_SHARED) {
1632 how_maybe |= HAMMER2_RESOLVE_SHARED;
1633 how_always |= HAMMER2_RESOLVE_SHARED;
1634 how |= HAMMER2_RESOLVE_SHARED;
1638 * Recurse (*parentp) upward if necessary until the parent completely
1639 * encloses the key range or we hit the inode.
1641 * This function handles races against the flusher doing a delete-
1642 * duplicate above us and re-homes the parent to the duplicate in
1643 * that case, otherwise we'd wind up recursing down a stale chain.
1648 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1649 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1650 scan_beg = parent->bref.key;
1651 scan_end = scan_beg +
1652 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1653 if (key_beg >= scan_beg && key_end <= scan_end)
1655 parent = hammer2_chain_getparent(parentp, how_maybe);
1659 if (--maxloops == 0)
1660 panic("hammer2_chain_lookup: maxloops");
1662 * Locate the blockref array. Currently we do a fully associative
1663 * search through the array.
1665 switch(parent->bref.type) {
1666 case HAMMER2_BREF_TYPE_INODE:
1668 * Special shortcut for embedded data returns the inode
1669 * itself. Callers must detect this condition and access
1670 * the embedded data (the strategy code does this for us).
1672 * This is only applicable to regular files and softlinks.
1674 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1675 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1677 *key_nextp = key_end + 1;
1680 hammer2_chain_ref(parent);
1681 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1682 hammer2_chain_lock(parent, how_always);
1683 *key_nextp = key_end + 1;
1686 base = &parent->data->ipdata.u.blockset.blockref[0];
1687 count = HAMMER2_SET_COUNT;
1689 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1690 case HAMMER2_BREF_TYPE_INDIRECT:
1692 * Handle MATCHIND on the parent
1694 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1695 scan_beg = parent->bref.key;
1696 scan_end = scan_beg +
1697 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1698 if (key_beg == scan_beg && key_end == scan_end) {
1700 hammer2_chain_ref(chain);
1701 hammer2_chain_lock(chain, how_maybe);
1702 *key_nextp = scan_end + 1;
1707 * Optimize indirect blocks in the INITIAL state to avoid
1710 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1713 if (parent->data == NULL)
1714 panic("parent->data is NULL");
1715 base = &parent->data->npdata[0];
1717 count = parent->bytes / sizeof(hammer2_blockref_t);
1719 case HAMMER2_BREF_TYPE_VOLUME:
1720 base = &hmp->voldata.sroot_blockset.blockref[0];
1721 count = HAMMER2_SET_COUNT;
1723 case HAMMER2_BREF_TYPE_FREEMAP:
1724 base = &hmp->voldata.freemap_blockset.blockref[0];
1725 count = HAMMER2_SET_COUNT;
1728 kprintf("hammer2_chain_lookup: unrecognized "
1729 "blockref(B) type: %d",
1732 tsleep(&base, 0, "dead", 0);
1733 panic("hammer2_chain_lookup: unrecognized "
1734 "blockref(B) type: %d",
1736 base = NULL; /* safety */
1737 count = 0; /* safety */
1741 * Merged scan to find next candidate.
1743 * hammer2_base_*() functions require the parent->core.live_* fields
1744 * to be synchronized.
1746 * We need to hold the spinlock to access the block array and RB tree
1747 * and to interlock chain creation.
1749 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1750 hammer2_chain_countbrefs(parent, base, count);
1755 hammer2_spin_ex(&parent->core.spin);
1756 chain = hammer2_combined_find(parent, base, count,
1757 cache_indexp, key_nextp,
1760 generation = parent->core.generation;
1763 * Exhausted parent chain, iterate.
1766 hammer2_spin_unex(&parent->core.spin);
1767 if (key_beg == key_end) /* short cut single-key case */
1771 * Stop if we reached the end of the iteration.
1773 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1774 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1779 * Calculate next key, stop if we reached the end of the
1780 * iteration, otherwise go up one level and loop.
1782 key_beg = parent->bref.key +
1783 ((hammer2_key_t)1 << parent->bref.keybits);
1784 if (key_beg == 0 || key_beg > key_end)
1786 parent = hammer2_chain_getparent(parentp, how_maybe);
1791 * Selected from blockref or in-memory chain.
1793 if (chain == NULL) {
1795 hammer2_spin_unex(&parent->core.spin);
1796 chain = hammer2_chain_get(parent, generation,
1798 if (chain == NULL) {
1799 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1800 parent, key_beg, key_end);
1803 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1804 hammer2_chain_drop(chain);
1808 hammer2_chain_ref(chain);
1809 hammer2_spin_unex(&parent->core.spin);
1813 * chain is referenced but not locked. We must lock the chain
1814 * to obtain definitive DUPLICATED/DELETED state
1816 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1817 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1818 hammer2_chain_lock(chain, how_maybe);
1820 hammer2_chain_lock(chain, how);
1824 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1826 * NOTE: Chain's key range is not relevant as there might be
1827 * one-offs within the range that are not deleted.
1829 * NOTE: Lookups can race delete-duplicate because
1830 * delete-duplicate does not lock the parent's core
1831 * (they just use the spinlock on the core). We must
1832 * check for races by comparing the DUPLICATED flag before
1833 * releasing the spinlock with the flag after locking the
1836 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1837 hammer2_chain_unlock(chain);
1838 hammer2_chain_drop(chain);
1839 key_beg = *key_nextp;
1840 if (key_beg == 0 || key_beg > key_end)
1846 * If the chain element is an indirect block it becomes the new
1847 * parent and we loop on it. We must maintain our top-down locks
1848 * to prevent the flusher from interfering (i.e. doing a
1849 * delete-duplicate and leaving us recursing down a deleted chain).
1851 * The parent always has to be locked with at least RESOLVE_MAYBE
1852 * so we can access its data. It might need a fixup if the caller
1853 * passed incompatible flags. Be careful not to cause a deadlock
1854 * as a data-load requires an exclusive lock.
1856 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1857 * range is within the requested key range we return the indirect
1858 * block and do NOT loop. This is usually only used to acquire
1861 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1862 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1863 hammer2_chain_unlock(parent);
1864 hammer2_chain_drop(parent);
1865 *parentp = parent = chain;
1870 * All done, return the chain.
1872 * If the caller does not want a locked chain, replace the lock with
1873 * a ref. Perhaps this can eventually be optimized to not obtain the
1874 * lock in the first place for situations where the data does not
1875 * need to be resolved.
1878 if (flags & HAMMER2_LOOKUP_NOLOCK)
1879 hammer2_chain_unlock(chain);
1886 * After having issued a lookup we can iterate all matching keys.
1888 * If chain is non-NULL we continue the iteration from just after it's index.
1890 * If chain is NULL we assume the parent was exhausted and continue the
1891 * iteration at the next parent.
1893 * If a fatal error occurs (typically an I/O error), a dummy chain is
1894 * returned with chain->error and error-identifying information set. This
1895 * chain will assert if you try to do anything fancy with it.
1897 * XXX Depending on where the error occurs we should allow continued iteration.
1899 * parent must be locked on entry and remains locked throughout. chain's
1900 * lock status must match flags. Chain is always at least referenced.
1902 * WARNING! The MATCHIND flag does not apply to this function.
1905 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1906 hammer2_key_t *key_nextp,
1907 hammer2_key_t key_beg, hammer2_key_t key_end,
1908 int *cache_indexp, int flags)
1910 hammer2_chain_t *parent;
1914 * Calculate locking flags for upward recursion.
1916 how_maybe = HAMMER2_RESOLVE_MAYBE;
1917 if (flags & HAMMER2_LOOKUP_SHARED)
1918 how_maybe |= HAMMER2_RESOLVE_SHARED;
1923 * Calculate the next index and recalculate the parent if necessary.
1926 key_beg = chain->bref.key +
1927 ((hammer2_key_t)1 << chain->bref.keybits);
1928 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1929 hammer2_chain_unlock(chain);
1930 hammer2_chain_drop(chain);
1933 * chain invalid past this point, but we can still do a
1934 * pointer comparison w/parent.
1936 * Any scan where the lookup returned degenerate data embedded
1937 * in the inode has an invalid index and must terminate.
1939 if (chain == parent)
1941 if (key_beg == 0 || key_beg > key_end)
1944 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1945 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1947 * We reached the end of the iteration.
1952 * Continue iteration with next parent unless the current
1953 * parent covers the range.
1955 key_beg = parent->bref.key +
1956 ((hammer2_key_t)1 << parent->bref.keybits);
1957 if (key_beg == 0 || key_beg > key_end)
1959 parent = hammer2_chain_getparent(parentp, how_maybe);
1965 return (hammer2_chain_lookup(parentp, key_nextp,
1967 cache_indexp, flags));
1971 * The raw scan function is similar to lookup/next but does not seek to a key.
1972 * Blockrefs are iterated via first_chain = (parent, NULL) and
1973 * next_chain = (parent, chain).
1975 * The passed-in parent must be locked and its data resolved. The returned
1976 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1977 * under parent and then iterate with the passed-in chain (which this
1978 * function will unlock).
1981 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1982 int *cache_indexp, int flags)
1985 hammer2_blockref_t *base;
1986 hammer2_blockref_t *bref;
1987 hammer2_blockref_t bcopy;
1989 hammer2_key_t next_key;
1991 int how_always = HAMMER2_RESOLVE_ALWAYS;
1992 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1995 int maxloops = 300000;
2000 * Scan flags borrowed from lookup.
2002 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2003 how_maybe = how_always;
2004 how = HAMMER2_RESOLVE_ALWAYS;
2005 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2006 how = HAMMER2_RESOLVE_NEVER;
2008 how = HAMMER2_RESOLVE_MAYBE;
2010 if (flags & HAMMER2_LOOKUP_SHARED) {
2011 how_maybe |= HAMMER2_RESOLVE_SHARED;
2012 how_always |= HAMMER2_RESOLVE_SHARED;
2013 how |= HAMMER2_RESOLVE_SHARED;
2017 * Calculate key to locate first/next element, unlocking the previous
2018 * element as we go. Be careful, the key calculation can overflow.
2021 key = chain->bref.key +
2022 ((hammer2_key_t)1 << chain->bref.keybits);
2023 hammer2_chain_unlock(chain);
2024 hammer2_chain_drop(chain);
2033 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2034 if (--maxloops == 0)
2035 panic("hammer2_chain_scan: maxloops");
2037 * Locate the blockref array. Currently we do a fully associative
2038 * search through the array.
2040 switch(parent->bref.type) {
2041 case HAMMER2_BREF_TYPE_INODE:
2043 * An inode with embedded data has no sub-chains.
2045 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2047 base = &parent->data->ipdata.u.blockset.blockref[0];
2048 count = HAMMER2_SET_COUNT;
2050 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2051 case HAMMER2_BREF_TYPE_INDIRECT:
2053 * Optimize indirect blocks in the INITIAL state to avoid
2056 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2059 if (parent->data == NULL)
2060 panic("parent->data is NULL");
2061 base = &parent->data->npdata[0];
2063 count = parent->bytes / sizeof(hammer2_blockref_t);
2065 case HAMMER2_BREF_TYPE_VOLUME:
2066 base = &hmp->voldata.sroot_blockset.blockref[0];
2067 count = HAMMER2_SET_COUNT;
2069 case HAMMER2_BREF_TYPE_FREEMAP:
2070 base = &hmp->voldata.freemap_blockset.blockref[0];
2071 count = HAMMER2_SET_COUNT;
2074 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2076 base = NULL; /* safety */
2077 count = 0; /* safety */
2081 * Merged scan to find next candidate.
2083 * hammer2_base_*() functions require the parent->core.live_* fields
2084 * to be synchronized.
2086 * We need to hold the spinlock to access the block array and RB tree
2087 * and to interlock chain creation.
2089 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2090 hammer2_chain_countbrefs(parent, base, count);
2093 hammer2_spin_ex(&parent->core.spin);
2094 chain = hammer2_combined_find(parent, base, count,
2095 cache_indexp, &next_key,
2096 key, HAMMER2_KEY_MAX,
2098 generation = parent->core.generation;
2101 * Exhausted parent chain, we're done.
2104 hammer2_spin_unex(&parent->core.spin);
2105 KKASSERT(chain == NULL);
2110 * Selected from blockref or in-memory chain.
2112 if (chain == NULL) {
2114 hammer2_spin_unex(&parent->core.spin);
2115 chain = hammer2_chain_get(parent, generation, &bcopy);
2116 if (chain == NULL) {
2117 kprintf("retry scan parent %p keys %016jx\n",
2121 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2122 hammer2_chain_drop(chain);
2127 hammer2_chain_ref(chain);
2128 hammer2_spin_unex(&parent->core.spin);
2132 * chain is referenced but not locked. We must lock the chain
2133 * to obtain definitive DUPLICATED/DELETED state
2135 hammer2_chain_lock(chain, how);
2138 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2140 * NOTE: chain's key range is not relevant as there might be
2141 * one-offs within the range that are not deleted.
2143 * NOTE: XXX this could create problems with scans used in
2144 * situations other than mount-time recovery.
2146 * NOTE: Lookups can race delete-duplicate because
2147 * delete-duplicate does not lock the parent's core
2148 * (they just use the spinlock on the core). We must
2149 * check for races by comparing the DUPLICATED flag before
2150 * releasing the spinlock with the flag after locking the
2153 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2154 hammer2_chain_unlock(chain);
2155 hammer2_chain_drop(chain);
2166 * All done, return the chain or NULL
2172 * Create and return a new hammer2 system memory structure of the specified
2173 * key, type and size and insert it under (*parentp). This is a full
2174 * insertion, based on the supplied key/keybits, and may involve creating
2175 * indirect blocks and moving other chains around via delete/duplicate.
2177 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2178 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2179 * FULL. This typically means that the caller is creating the chain after
2180 * doing a hammer2_chain_lookup().
2182 * (*parentp) must be exclusive locked and may be replaced on return
2183 * depending on how much work the function had to do.
2185 * (*parentp) must not be errored or this function will assert.
2187 * (*chainp) usually starts out NULL and returns the newly created chain,
2188 * but if the caller desires the caller may allocate a disconnected chain
2189 * and pass it in instead.
2191 * This function should NOT be used to insert INDIRECT blocks. It is
2192 * typically used to create/insert inodes and data blocks.
2194 * Caller must pass-in an exclusively locked parent the new chain is to
2195 * be inserted under, and optionally pass-in a disconnected, exclusively
2196 * locked chain to insert (else we create a new chain). The function will
2197 * adjust (*parentp) as necessary, create or connect the chain, and
2198 * return an exclusively locked chain in *chainp.
2200 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2201 * and will be reassigned.
2204 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2205 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2206 hammer2_key_t key, int keybits, int type, size_t bytes,
2210 hammer2_chain_t *chain;
2211 hammer2_chain_t *parent;
2212 hammer2_blockref_t *base;
2213 hammer2_blockref_t dummy;
2217 int maxloops = 300000;
2220 * Topology may be crossing a PFS boundary.
2223 KKASSERT(hammer2_mtx_owned(&parent->lock));
2224 KKASSERT(parent->error == 0);
2228 if (chain == NULL) {
2230 * First allocate media space and construct the dummy bref,
2231 * then allocate the in-memory chain structure. Set the
2232 * INITIAL flag for fresh chains which do not have embedded
2235 bzero(&dummy, sizeof(dummy));
2238 dummy.keybits = keybits;
2239 dummy.data_off = hammer2_getradix(bytes);
2240 dummy.methods = parent->bref.methods;
2241 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2244 * Lock the chain manually, chain_lock will load the chain
2245 * which we do NOT want to do. (note: chain->refs is set
2246 * to 1 by chain_alloc() for us, but lockcnt is not).
2249 hammer2_mtx_ex(&chain->lock);
2253 * Set INITIAL to optimize I/O. The flag will generally be
2254 * processed when we call hammer2_chain_modify().
2256 * Recalculate bytes to reflect the actual media block
2259 bytes = (hammer2_off_t)1 <<
2260 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2261 chain->bytes = bytes;
2264 case HAMMER2_BREF_TYPE_VOLUME:
2265 case HAMMER2_BREF_TYPE_FREEMAP:
2266 panic("hammer2_chain_create: called with volume type");
2268 case HAMMER2_BREF_TYPE_INDIRECT:
2269 panic("hammer2_chain_create: cannot be used to"
2270 "create indirect block");
2272 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2273 panic("hammer2_chain_create: cannot be used to"
2274 "create freemap root or node");
2276 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2277 KKASSERT(bytes == sizeof(chain->data->bmdata));
2279 case HAMMER2_BREF_TYPE_INODE:
2280 case HAMMER2_BREF_TYPE_DATA:
2283 * leave chain->data NULL, set INITIAL
2285 KKASSERT(chain->data == NULL);
2286 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2291 * Set statistics for pending updates. These will be
2292 * synchronized by the flush code.
2295 case HAMMER2_BREF_TYPE_INODE:
2296 chain->inode_count = 1;
2298 case HAMMER2_BREF_TYPE_DATA:
2299 case HAMMER2_BREF_TYPE_INDIRECT:
2300 chain->data_count = chain->bytes;
2305 * We are reattaching a previously deleted chain, possibly
2306 * under a new parent and possibly with a new key/keybits.
2307 * The chain does not have to be in a modified state. The
2308 * UPDATE flag will be set later on in this routine.
2310 * Do NOT mess with the current state of the INITIAL flag.
2312 chain->bref.key = key;
2313 chain->bref.keybits = keybits;
2314 if (chain->flags & HAMMER2_CHAIN_DELETED)
2315 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2316 KKASSERT(chain->parent == NULL);
2318 if (flags & HAMMER2_INSERT_PFSROOT)
2319 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2321 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2324 * Calculate how many entries we have in the blockref array and
2325 * determine if an indirect block is required.
2328 if (--maxloops == 0)
2329 panic("hammer2_chain_create: maxloops");
2331 switch(parent->bref.type) {
2332 case HAMMER2_BREF_TYPE_INODE:
2333 KKASSERT((parent->data->ipdata.op_flags &
2334 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2335 KKASSERT(parent->data != NULL);
2336 base = &parent->data->ipdata.u.blockset.blockref[0];
2337 count = HAMMER2_SET_COUNT;
2339 case HAMMER2_BREF_TYPE_INDIRECT:
2340 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2341 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2344 base = &parent->data->npdata[0];
2345 count = parent->bytes / sizeof(hammer2_blockref_t);
2347 case HAMMER2_BREF_TYPE_VOLUME:
2348 KKASSERT(parent->data != NULL);
2349 base = &hmp->voldata.sroot_blockset.blockref[0];
2350 count = HAMMER2_SET_COUNT;
2352 case HAMMER2_BREF_TYPE_FREEMAP:
2353 KKASSERT(parent->data != NULL);
2354 base = &hmp->voldata.freemap_blockset.blockref[0];
2355 count = HAMMER2_SET_COUNT;
2358 panic("hammer2_chain_create: unrecognized blockref type: %d",
2366 * Make sure we've counted the brefs
2368 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2369 hammer2_chain_countbrefs(parent, base, count);
2371 KKASSERT(parent->core.live_count >= 0 &&
2372 parent->core.live_count <= count);
2375 * If no free blockref could be found we must create an indirect
2376 * block and move a number of blockrefs into it. With the parent
2377 * locked we can safely lock each child in order to delete+duplicate
2378 * it without causing a deadlock.
2380 * This may return the new indirect block or the old parent depending
2381 * on where the key falls. NULL is returned on error.
2383 if (parent->core.live_count == count) {
2384 hammer2_chain_t *nparent;
2386 nparent = hammer2_chain_create_indirect(trans, parent,
2389 if (nparent == NULL) {
2391 hammer2_chain_drop(chain);
2395 if (parent != nparent) {
2396 hammer2_chain_unlock(parent);
2397 hammer2_chain_drop(parent);
2398 parent = *parentp = nparent;
2404 * Link the chain into its parent.
2406 if (chain->parent != NULL)
2407 panic("hammer2: hammer2_chain_create: chain already connected");
2408 KKASSERT(chain->parent == NULL);
2409 hammer2_chain_insert(parent, chain,
2410 HAMMER2_CHAIN_INSERT_SPIN |
2411 HAMMER2_CHAIN_INSERT_LIVE,
2416 * Mark the newly created chain modified. This will cause
2417 * UPDATE to be set and process the INITIAL flag.
2419 * Device buffers are not instantiated for DATA elements
2420 * as these are handled by logical buffers.
2422 * Indirect and freemap node indirect blocks are handled
2423 * by hammer2_chain_create_indirect() and not by this
2426 * Data for all other bref types is expected to be
2427 * instantiated (INODE, LEAF).
2429 switch(chain->bref.type) {
2430 case HAMMER2_BREF_TYPE_DATA:
2431 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2432 case HAMMER2_BREF_TYPE_INODE:
2433 hammer2_chain_modify(trans, chain,
2434 HAMMER2_MODIFY_OPTDATA);
2438 * Remaining types are not supported by this function.
2439 * In particular, INDIRECT and LEAF_NODE types are
2440 * handled by create_indirect().
2442 panic("hammer2_chain_create: bad type: %d",
2449 * When reconnecting a chain we must set UPDATE and
2450 * setflush so the flush recognizes that it must update
2451 * the bref in the parent.
2453 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2454 hammer2_chain_ref(chain);
2455 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2457 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2458 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2459 KKASSERT(chain->data);
2460 chain->inode_count_up +=
2461 chain->data->ipdata.inode_count;
2462 chain->data_count_up +=
2463 chain->data->ipdata.data_count;
2468 * We must setflush(parent) to ensure that it recurses through to
2469 * chain. setflush(chain) might not work because ONFLUSH is possibly
2470 * already set in the chain (so it won't recurse up to set it in the
2473 hammer2_chain_setflush(trans, parent);
2482 * Move the chain from its old parent to a new parent. The chain must have
2483 * already been deleted or already disconnected (or never associated) with
2484 * a parent. The chain is reassociated with the new parent and the deleted
2485 * flag will be cleared (no longer deleted). The chain's modification state
2488 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2489 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2490 * FULL. This typically means that the caller is creating the chain after
2491 * doing a hammer2_chain_lookup().
2493 * A non-NULL bref is typically passed when key and keybits must be overridden.
2494 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2495 * from a passed-in bref and uses the old chain's bref for everything else.
2497 * Neither (parent) or (chain) can be errored.
2499 * If (parent) is non-NULL then the new duplicated chain is inserted under
2502 * If (parent) is NULL then the newly duplicated chain is not inserted
2503 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2504 * passing into hammer2_chain_create() after this function returns).
2506 * WARNING! This function calls create which means it can insert indirect
2507 * blocks. This can cause other unrelated chains in the parent to
2508 * be moved to a newly inserted indirect block in addition to the
2512 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2513 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2517 hammer2_chain_t *parent;
2521 * WARNING! We should never resolve DATA to device buffers
2522 * (XXX allow it if the caller did?), and since
2523 * we currently do not have the logical buffer cache
2524 * buffer in-hand to fix its cached physical offset
2525 * we also force the modify code to not COW it. XXX
2528 KKASSERT(chain->parent == NULL);
2529 KKASSERT(chain->error == 0);
2532 * Now create a duplicate of the chain structure, associating
2533 * it with the same core, making it the same size, pointing it
2534 * to the same bref (the same media block).
2537 bref = &chain->bref;
2538 bytes = (hammer2_off_t)1 <<
2539 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2542 * If parent is not NULL the duplicated chain will be entered under
2543 * the parent and the UPDATE bit set to tell flush to update
2546 * We must setflush(parent) to ensure that it recurses through to
2547 * chain. setflush(chain) might not work because ONFLUSH is possibly
2548 * already set in the chain (so it won't recurse up to set it in the
2551 * Having both chains locked is extremely important for atomicy.
2553 if (parentp && (parent = *parentp) != NULL) {
2554 KKASSERT(hammer2_mtx_owned(&parent->lock));
2555 KKASSERT(parent->refs > 0);
2556 KKASSERT(parent->error == 0);
2558 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2559 bref->key, bref->keybits, bref->type,
2560 chain->bytes, flags);
2561 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2562 hammer2_chain_setflush(trans, *parentp);
2567 * Helper function for deleting chains.
2569 * The chain is removed from the live view (the RBTREE) as well as the parent's
2570 * blockmap. Both chain and its parent must be locked.
2572 * parent may not be errored. chain can be errored.
2575 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2576 hammer2_chain_t *parent, hammer2_chain_t *chain,
2581 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2582 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2585 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2587 * Chain is blockmapped, so there must be a parent.
2588 * Atomically remove the chain from the parent and remove
2589 * the blockmap entry.
2591 hammer2_blockref_t *base;
2594 KKASSERT(parent != NULL);
2595 KKASSERT(parent->error == 0);
2596 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2597 hammer2_chain_modify(trans, parent,
2598 HAMMER2_MODIFY_OPTDATA);
2601 * Calculate blockmap pointer
2603 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2604 hammer2_spin_ex(&parent->core.spin);
2606 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2607 atomic_add_int(&parent->core.live_count, -1);
2608 ++parent->core.generation;
2609 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2610 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2611 --parent->core.chain_count;
2612 chain->parent = NULL;
2614 switch(parent->bref.type) {
2615 case HAMMER2_BREF_TYPE_INODE:
2617 * Access the inode's block array. However, there
2618 * is no block array if the inode is flagged
2619 * DIRECTDATA. The DIRECTDATA case typicaly only
2620 * occurs when a hardlink has been shifted up the
2621 * tree and the original inode gets replaced with
2622 * an OBJTYPE_HARDLINK placeholding inode.
2625 (parent->data->ipdata.op_flags &
2626 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2628 &parent->data->ipdata.u.blockset.blockref[0];
2632 count = HAMMER2_SET_COUNT;
2634 case HAMMER2_BREF_TYPE_INDIRECT:
2635 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2637 base = &parent->data->npdata[0];
2640 count = parent->bytes / sizeof(hammer2_blockref_t);
2642 case HAMMER2_BREF_TYPE_VOLUME:
2643 base = &hmp->voldata.sroot_blockset.blockref[0];
2644 count = HAMMER2_SET_COUNT;
2646 case HAMMER2_BREF_TYPE_FREEMAP:
2647 base = &parent->data->npdata[0];
2648 count = HAMMER2_SET_COUNT;
2653 panic("hammer2_flush_pass2: "
2654 "unrecognized blockref type: %d",
2659 * delete blockmapped chain from its parent.
2661 * The parent is not affected by any statistics in chain
2662 * which are pending synchronization. That is, there is
2663 * nothing to undo in the parent since they have not yet
2664 * been incorporated into the parent.
2666 * The parent is affected by statistics stored in inodes.
2667 * Those have already been synchronized, so they must be
2668 * undone. XXX split update possible w/delete in middle?
2671 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2672 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2673 KKASSERT(chain->data != NULL);
2674 parent->data_count -=
2675 chain->data->ipdata.data_count;
2676 parent->inode_count -=
2677 chain->data->ipdata.inode_count;
2680 int cache_index = -1;
2681 hammer2_base_delete(trans, parent, base, count,
2682 &cache_index, chain);
2684 hammer2_spin_unex(&parent->core.spin);
2685 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2687 * Chain is not blockmapped but a parent is present.
2688 * Atomically remove the chain from the parent. There is
2689 * no blockmap entry to remove.
2691 * Because chain was associated with a parent but not
2692 * synchronized, the chain's *_count_up fields contain
2693 * inode adjustment statistics which must be undone.
2695 hammer2_spin_ex(&parent->core.spin);
2696 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2697 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2698 KKASSERT(chain->data != NULL);
2699 chain->data_count_up -=
2700 chain->data->ipdata.data_count;
2701 chain->inode_count_up -=
2702 chain->data->ipdata.inode_count;
2704 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2705 atomic_add_int(&parent->core.live_count, -1);
2706 ++parent->core.generation;
2707 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2708 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2709 --parent->core.chain_count;
2710 chain->parent = NULL;
2711 hammer2_spin_unex(&parent->core.spin);
2714 * Chain is not blockmapped and has no parent. This
2715 * is a degenerate case.
2717 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2722 * Create an indirect block that covers one or more of the elements in the
2723 * current parent. Either returns the existing parent with no locking or
2724 * ref changes or returns the new indirect block locked and referenced
2725 * and leaving the original parent lock/ref intact as well.
2727 * If an error occurs, NULL is returned and *errorp is set to the error.
2729 * The returned chain depends on where the specified key falls.
2731 * The key/keybits for the indirect mode only needs to follow three rules:
2733 * (1) That all elements underneath it fit within its key space and
2735 * (2) That all elements outside it are outside its key space.
2737 * (3) When creating the new indirect block any elements in the current
2738 * parent that fit within the new indirect block's keyspace must be
2739 * moved into the new indirect block.
2741 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2742 * keyspace the the current parent, but lookup/iteration rules will
2743 * ensure (and must ensure) that rule (2) for all parents leading up
2744 * to the nearest inode or the root volume header is adhered to. This
2745 * is accomplished by always recursing through matching keyspaces in
2746 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2748 * The current implementation calculates the current worst-case keyspace by
2749 * iterating the current parent and then divides it into two halves, choosing
2750 * whichever half has the most elements (not necessarily the half containing
2751 * the requested key).
2753 * We can also opt to use the half with the least number of elements. This
2754 * causes lower-numbered keys (aka logical file offsets) to recurse through
2755 * fewer indirect blocks and higher-numbered keys to recurse through more.
2756 * This also has the risk of not moving enough elements to the new indirect
2757 * block and being forced to create several indirect blocks before the element
2760 * Must be called with an exclusively locked parent.
2762 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2763 hammer2_key_t *keyp, int keybits,
2764 hammer2_blockref_t *base, int count);
2765 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2766 hammer2_key_t *keyp, int keybits,
2767 hammer2_blockref_t *base, int count);
2770 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2771 hammer2_key_t create_key, int create_bits,
2772 int for_type, int *errorp)
2775 hammer2_blockref_t *base;
2776 hammer2_blockref_t *bref;
2777 hammer2_blockref_t bcopy;
2778 hammer2_chain_t *chain;
2779 hammer2_chain_t *ichain;
2780 hammer2_chain_t dummy;
2781 hammer2_key_t key = create_key;
2782 hammer2_key_t key_beg;
2783 hammer2_key_t key_end;
2784 hammer2_key_t key_next;
2785 int keybits = create_bits;
2792 int maxloops = 300000;
2795 * Calculate the base blockref pointer or NULL if the chain
2796 * is known to be empty. We need to calculate the array count
2797 * for RB lookups either way.
2801 KKASSERT(hammer2_mtx_owned(&parent->lock));
2803 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2804 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2807 switch(parent->bref.type) {
2808 case HAMMER2_BREF_TYPE_INODE:
2809 count = HAMMER2_SET_COUNT;
2811 case HAMMER2_BREF_TYPE_INDIRECT:
2812 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2813 count = parent->bytes / sizeof(hammer2_blockref_t);
2815 case HAMMER2_BREF_TYPE_VOLUME:
2816 count = HAMMER2_SET_COUNT;
2818 case HAMMER2_BREF_TYPE_FREEMAP:
2819 count = HAMMER2_SET_COUNT;
2822 panic("hammer2_chain_create_indirect: "
2823 "unrecognized blockref type: %d",
2829 switch(parent->bref.type) {
2830 case HAMMER2_BREF_TYPE_INODE:
2831 base = &parent->data->ipdata.u.blockset.blockref[0];
2832 count = HAMMER2_SET_COUNT;
2834 case HAMMER2_BREF_TYPE_INDIRECT:
2835 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2836 base = &parent->data->npdata[0];
2837 count = parent->bytes / sizeof(hammer2_blockref_t);
2839 case HAMMER2_BREF_TYPE_VOLUME:
2840 base = &hmp->voldata.sroot_blockset.blockref[0];
2841 count = HAMMER2_SET_COUNT;
2843 case HAMMER2_BREF_TYPE_FREEMAP:
2844 base = &hmp->voldata.freemap_blockset.blockref[0];
2845 count = HAMMER2_SET_COUNT;
2848 panic("hammer2_chain_create_indirect: "
2849 "unrecognized blockref type: %d",
2857 * dummy used in later chain allocation (no longer used for lookups).
2859 bzero(&dummy, sizeof(dummy));
2862 * When creating an indirect block for a freemap node or leaf
2863 * the key/keybits must be fitted to static radix levels because
2864 * particular radix levels use particular reserved blocks in the
2867 * This routine calculates the key/radix of the indirect block
2868 * we need to create, and whether it is on the high-side or the
2871 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2872 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2873 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2876 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2881 * Normalize the key for the radix being represented, keeping the
2882 * high bits and throwing away the low bits.
2884 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2887 * How big should our new indirect block be? It has to be at least
2888 * as large as its parent.
2890 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2891 nbytes = HAMMER2_IND_BYTES_MIN;
2893 nbytes = HAMMER2_IND_BYTES_MAX;
2894 if (nbytes < count * sizeof(hammer2_blockref_t))
2895 nbytes = count * sizeof(hammer2_blockref_t);
2898 * Ok, create our new indirect block
2900 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2901 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2902 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2904 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2906 dummy.bref.key = key;
2907 dummy.bref.keybits = keybits;
2908 dummy.bref.data_off = hammer2_getradix(nbytes);
2909 dummy.bref.methods = parent->bref.methods;
2911 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2912 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2913 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2914 /* ichain has one ref at this point */
2917 * We have to mark it modified to allocate its block, but use
2918 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2919 * it won't be acted upon by the flush code.
2921 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2924 * Iterate the original parent and move the matching brefs into
2925 * the new indirect block.
2927 * XXX handle flushes.
2930 key_end = HAMMER2_KEY_MAX;
2932 hammer2_spin_ex(&parent->core.spin);
2937 if (++loops > 100000) {
2938 hammer2_spin_unex(&parent->core.spin);
2939 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2940 reason, parent, base, count, key_next);
2944 * NOTE: spinlock stays intact, returned chain (if not NULL)
2945 * is not referenced or locked which means that we
2946 * cannot safely check its flagged / deletion status
2949 chain = hammer2_combined_find(parent, base, count,
2950 &cache_index, &key_next,
2953 generation = parent->core.generation;
2956 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2959 * Skip keys that are not within the key/radix of the new
2960 * indirect block. They stay in the parent.
2962 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2963 (key ^ bref->key)) != 0) {
2964 goto next_key_spinlocked;
2968 * Load the new indirect block by acquiring the related
2969 * chains (potentially from media as it might not be
2970 * in-memory). Then move it to the new parent (ichain)
2971 * via DELETE-DUPLICATE.
2973 * chain is referenced but not locked. We must lock the
2974 * chain to obtain definitive DUPLICATED/DELETED state
2978 * Use chain already present in the RBTREE
2980 hammer2_chain_ref(chain);
2981 hammer2_spin_unex(&parent->core.spin);
2982 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2985 * Get chain for blockref element. _get returns NULL
2986 * on insertion race.
2989 hammer2_spin_unex(&parent->core.spin);
2990 chain = hammer2_chain_get(parent, generation, &bcopy);
2991 if (chain == NULL) {
2993 hammer2_spin_ex(&parent->core.spin);
2996 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2997 kprintf("REASON 2\n");
2999 hammer2_chain_drop(chain);
3000 hammer2_spin_ex(&parent->core.spin);
3003 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3007 * This is always live so if the chain has been deleted
3008 * we raced someone and we have to retry.
3010 * NOTE: Lookups can race delete-duplicate because
3011 * delete-duplicate does not lock the parent's core
3012 * (they just use the spinlock on the core). We must
3013 * check for races by comparing the DUPLICATED flag before
3014 * releasing the spinlock with the flag after locking the
3017 * (note reversed logic for this one)
3019 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3020 hammer2_chain_unlock(chain);
3021 hammer2_chain_drop(chain);
3026 * Shift the chain to the indirect block.
3028 * WARNING! No reason for us to load chain data, pass NOSTATS
3029 * to prevent delete/insert from trying to access
3030 * inode stats (and thus asserting if there is no
3031 * chain->data loaded).
3033 hammer2_chain_delete(trans, parent, chain,
3034 HAMMER2_DELETE_NOSTATS);
3035 hammer2_chain_rename(trans, NULL, &ichain, chain,
3036 HAMMER2_INSERT_NOSTATS);
3037 hammer2_chain_unlock(chain);
3038 hammer2_chain_drop(chain);
3039 KKASSERT(parent->refs > 0);
3042 hammer2_spin_ex(&parent->core.spin);
3043 next_key_spinlocked:
3044 if (--maxloops == 0)
3045 panic("hammer2_chain_create_indirect: maxloops");
3047 if (key_next == 0 || key_next > key_end)
3052 hammer2_spin_unex(&parent->core.spin);
3055 * Insert the new indirect block into the parent now that we've
3056 * cleared out some entries in the parent. We calculated a good
3057 * insertion index in the loop above (ichain->index).
3059 * We don't have to set UPDATE here because we mark ichain
3060 * modified down below (so the normal modified -> flush -> set-moved
3061 * sequence applies).
3063 * The insertion shouldn't race as this is a completely new block
3064 * and the parent is locked.
3066 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3067 hammer2_chain_insert(parent, ichain,
3068 HAMMER2_CHAIN_INSERT_SPIN |
3069 HAMMER2_CHAIN_INSERT_LIVE,
3073 * Make sure flushes propogate after our manual insertion.
3075 hammer2_chain_setflush(trans, ichain);
3076 hammer2_chain_setflush(trans, parent);
3079 * Figure out what to return.
3081 if (~(((hammer2_key_t)1 << keybits) - 1) &
3082 (create_key ^ key)) {
3084 * Key being created is outside the key range,
3085 * return the original parent.
3087 hammer2_chain_unlock(ichain);
3088 hammer2_chain_drop(ichain);
3091 * Otherwise its in the range, return the new parent.
3092 * (leave both the new and old parent locked).
3101 * Calculate the keybits and highside/lowside of the freemap node the
3102 * caller is creating.
3104 * This routine will specify the next higher-level freemap key/radix
3105 * representing the lowest-ordered set. By doing so, eventually all
3106 * low-ordered sets will be moved one level down.
3108 * We have to be careful here because the freemap reserves a limited
3109 * number of blocks for a limited number of levels. So we can't just
3110 * push indiscriminately.
3113 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3114 int keybits, hammer2_blockref_t *base, int count)
3116 hammer2_chain_t *chain;
3117 hammer2_blockref_t *bref;
3119 hammer2_key_t key_beg;
3120 hammer2_key_t key_end;
3121 hammer2_key_t key_next;
3125 int maxloops = 300000;
3133 * Calculate the range of keys in the array being careful to skip
3134 * slots which are overridden with a deletion.
3137 key_end = HAMMER2_KEY_MAX;
3139 hammer2_spin_ex(&parent->core.spin);
3142 if (--maxloops == 0) {
3143 panic("indkey_freemap shit %p %p:%d\n",
3144 parent, base, count);
3146 chain = hammer2_combined_find(parent, base, count,
3147 &cache_index, &key_next,
3158 * Skip deleted chains.
3160 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3161 if (key_next == 0 || key_next > key_end)
3168 * Use the full live (not deleted) element for the scan
3169 * iteration. HAMMER2 does not allow partial replacements.
3171 * XXX should be built into hammer2_combined_find().
3173 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3175 if (keybits > bref->keybits) {
3177 keybits = bref->keybits;
3178 } else if (keybits == bref->keybits && bref->key < key) {
3185 hammer2_spin_unex(&parent->core.spin);
3188 * Return the keybits for a higher-level FREEMAP_NODE covering
3192 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3193 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3195 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3196 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3198 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3199 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3201 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3202 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3204 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3205 panic("hammer2_chain_indkey_freemap: level too high");
3208 panic("hammer2_chain_indkey_freemap: bad radix");
3217 * Calculate the keybits and highside/lowside of the indirect block the
3218 * caller is creating.
3221 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3222 int keybits, hammer2_blockref_t *base, int count)
3224 hammer2_blockref_t *bref;
3225 hammer2_chain_t *chain;
3226 hammer2_key_t key_beg;
3227 hammer2_key_t key_end;
3228 hammer2_key_t key_next;
3234 int maxloops = 300000;
3241 * Calculate the range of keys in the array being careful to skip
3242 * slots which are overridden with a deletion. Once the scan
3243 * completes we will cut the key range in half and shift half the
3244 * range into the new indirect block.
3247 key_end = HAMMER2_KEY_MAX;
3249 hammer2_spin_ex(&parent->core.spin);
3252 if (--maxloops == 0) {
3253 panic("indkey_freemap shit %p %p:%d\n",
3254 parent, base, count);
3256 chain = hammer2_combined_find(parent, base, count,
3257 &cache_index, &key_next,
3268 * NOTE: No need to check DUPLICATED here because we do
3269 * not release the spinlock.
3271 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3272 if (key_next == 0 || key_next > key_end)
3279 * Use the full live (not deleted) element for the scan
3280 * iteration. HAMMER2 does not allow partial replacements.
3282 * XXX should be built into hammer2_combined_find().
3284 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3287 * Expand our calculated key range (key, keybits) to fit
3288 * the scanned key. nkeybits represents the full range
3289 * that we will later cut in half (two halves @ nkeybits - 1).
3292 if (nkeybits < bref->keybits) {
3293 if (bref->keybits > 64) {
3294 kprintf("bad bref chain %p bref %p\n",
3298 nkeybits = bref->keybits;
3300 while (nkeybits < 64 &&
3301 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3302 (key ^ bref->key)) != 0) {
3307 * If the new key range is larger we have to determine
3308 * which side of the new key range the existing keys fall
3309 * under by checking the high bit, then collapsing the
3310 * locount into the hicount or vise-versa.
3312 if (keybits != nkeybits) {
3313 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3324 * The newly scanned key will be in the lower half or the
3325 * upper half of the (new) key range.
3327 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3336 hammer2_spin_unex(&parent->core.spin);
3337 bref = NULL; /* now invalid (safety) */
3340 * Adjust keybits to represent half of the full range calculated
3341 * above (radix 63 max)
3346 * Select whichever half contains the most elements. Theoretically
3347 * we can select either side as long as it contains at least one
3348 * element (in order to ensure that a free slot is present to hold
3349 * the indirect block).
3351 if (hammer2_indirect_optimize) {
3353 * Insert node for least number of keys, this will arrange
3354 * the first few blocks of a large file or the first few
3355 * inodes in a directory with fewer indirect blocks when
3358 if (hicount < locount && hicount != 0)
3359 key |= (hammer2_key_t)1 << keybits;
3361 key &= ~(hammer2_key_t)1 << keybits;
3364 * Insert node for most number of keys, best for heavily
3367 if (hicount > locount)
3368 key |= (hammer2_key_t)1 << keybits;
3370 key &= ~(hammer2_key_t)1 << keybits;
3378 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3381 * Both parent and chain must be locked exclusively.
3383 * This function will modify the parent if the blockref requires removal
3384 * from the parent's block table.
3386 * This function is NOT recursive. Any entity already pushed into the
3387 * chain (such as an inode) may still need visibility into its contents,
3388 * as well as the ability to read and modify the contents. For example,
3389 * for an unlinked file which is still open.
3392 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3393 hammer2_chain_t *chain, int flags)
3395 KKASSERT(hammer2_mtx_owned(&chain->lock));
3398 * Nothing to do if already marked.
3400 * We need the spinlock on the core whos RBTREE contains chain
3401 * to protect against races.
3403 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3404 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3405 chain->parent == parent);
3406 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3410 * To avoid losing track of a permanent deletion we add the chain
3411 * to the delayed flush queue. If were to flush it right now the
3412 * parent would end up in a modified state and generate I/O.
3413 * The delayed queue gives the parent a chance to be deleted to
3416 if (flags & HAMMER2_DELETE_PERMANENT) {
3417 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3418 hammer2_delayed_flush(trans, chain);
3420 /* XXX might not be needed */
3421 hammer2_chain_setflush(trans, chain);
3426 * Returns the index of the nearest element in the blockref array >= elm.
3427 * Returns (count) if no element could be found.
3429 * Sets *key_nextp to the next key for loop purposes but does not modify
3430 * it if the next key would be higher than the current value of *key_nextp.
3431 * Note that *key_nexp can overflow to 0, which should be tested by the
3434 * (*cache_indexp) is a heuristic and can be any value without effecting
3437 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3438 * held through the operation.
3441 hammer2_base_find(hammer2_chain_t *parent,
3442 hammer2_blockref_t *base, int count,
3443 int *cache_indexp, hammer2_key_t *key_nextp,
3444 hammer2_key_t key_beg, hammer2_key_t key_end)
3446 hammer2_blockref_t *scan;
3447 hammer2_key_t scan_end;
3452 * Require the live chain's already have their core's counted
3453 * so we can optimize operations.
3455 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3460 if (count == 0 || base == NULL)
3464 * Sequential optimization using *cache_indexp. This is the most
3467 * We can avoid trailing empty entries on live chains, otherwise
3468 * we might have to check the whole block array.
3472 limit = parent->core.live_zero;
3477 KKASSERT(i < count);
3483 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3490 * Search forwards, stop when we find a scan element which
3491 * encloses the key or until we know that there are no further
3495 if (scan->type != 0) {
3496 scan_end = scan->key +
3497 ((hammer2_key_t)1 << scan->keybits) - 1;
3498 if (scan->key > key_beg || scan_end >= key_beg)
3511 scan_end = scan->key +
3512 ((hammer2_key_t)1 << scan->keybits);
3513 if (scan_end && (*key_nextp > scan_end ||
3515 *key_nextp = scan_end;
3523 * Do a combined search and return the next match either from the blockref
3524 * array or from the in-memory chain. Sets *bresp to the returned bref in
3525 * both cases, or sets it to NULL if the search exhausted. Only returns
3526 * a non-NULL chain if the search matched from the in-memory chain.
3528 * When no in-memory chain has been found and a non-NULL bref is returned
3532 * The returned chain is not locked or referenced. Use the returned bref
3533 * to determine if the search exhausted or not. Iterate if the base find
3534 * is chosen but matches a deleted chain.
3536 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3537 * held through the operation.
3539 static hammer2_chain_t *
3540 hammer2_combined_find(hammer2_chain_t *parent,
3541 hammer2_blockref_t *base, int count,
3542 int *cache_indexp, hammer2_key_t *key_nextp,
3543 hammer2_key_t key_beg, hammer2_key_t key_end,
3544 hammer2_blockref_t **bresp)
3546 hammer2_blockref_t *bref;
3547 hammer2_chain_t *chain;
3551 * Lookup in block array and in rbtree.
3553 *key_nextp = key_end + 1;
3554 i = hammer2_base_find(parent, base, count, cache_indexp,
3555 key_nextp, key_beg, key_end);
3556 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3561 if (i == count && chain == NULL) {
3567 * Only chain matched.
3570 bref = &chain->bref;
3575 * Only blockref matched.
3577 if (chain == NULL) {
3583 * Both in-memory and blockref matched, select the nearer element.
3585 * If both are flush with the left-hand side or both are the
3586 * same distance away, select the chain. In this situation the
3587 * chain must have been loaded from the matching blockmap.
3589 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3590 chain->bref.key == base[i].key) {
3591 KKASSERT(chain->bref.key == base[i].key);
3592 bref = &chain->bref;
3597 * Select the nearer key
3599 if (chain->bref.key < base[i].key) {
3600 bref = &chain->bref;
3607 * If the bref is out of bounds we've exhausted our search.
3610 if (bref->key > key_end) {
3620 * Locate the specified block array element and delete it. The element
3623 * The spin lock on the related chain must be held.
3625 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3626 * need to be adjusted when we commit the media change.
3629 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3630 hammer2_blockref_t *base, int count,
3631 int *cache_indexp, hammer2_chain_t *chain)
3633 hammer2_blockref_t *elm = &chain->bref;
3634 hammer2_key_t key_next;
3638 * Delete element. Expect the element to exist.
3640 * XXX see caller, flush code not yet sophisticated enough to prevent
3641 * re-flushed in some cases.
3643 key_next = 0; /* max range */
3644 i = hammer2_base_find(parent, base, count, cache_indexp,
3645 &key_next, elm->key, elm->key);
3646 if (i == count || base[i].type == 0 ||
3647 base[i].key != elm->key ||
3648 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3649 base[i].keybits != elm->keybits)) {
3650 hammer2_spin_unex(&parent->core.spin);
3651 panic("delete base %p element not found at %d/%d elm %p\n",
3652 base, i, count, elm);
3655 bzero(&base[i], sizeof(*base));
3658 * We can only optimize parent->core.live_zero for live chains.
3660 if (parent->core.live_zero == i + 1) {
3661 while (--i >= 0 && base[i].type == 0)
3663 parent->core.live_zero = i + 1;
3667 * Clear appropriate blockmap flags in chain.
3669 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3670 HAMMER2_CHAIN_BMAPUPD);
3674 * Insert the specified element. The block array must not already have the
3675 * element and must have space available for the insertion.
3677 * The spin lock on the related chain must be held.
3679 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3680 * need to be adjusted when we commit the media change.
3683 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3684 hammer2_blockref_t *base, int count,
3685 int *cache_indexp, hammer2_chain_t *chain)
3687 hammer2_blockref_t *elm = &chain->bref;
3688 hammer2_key_t key_next;
3697 * Insert new element. Expect the element to not already exist
3698 * unless we are replacing it.
3700 * XXX see caller, flush code not yet sophisticated enough to prevent
3701 * re-flushed in some cases.
3703 key_next = 0; /* max range */
3704 i = hammer2_base_find(parent, base, count, cache_indexp,
3705 &key_next, elm->key, elm->key);
3708 * Shortcut fill optimization, typical ordered insertion(s) may not
3711 KKASSERT(i >= 0 && i <= count);
3714 * Set appropriate blockmap flags in chain.
3716 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3719 * We can only optimize parent->core.live_zero for live chains.
3721 if (i == count && parent->core.live_zero < count) {
3722 i = parent->core.live_zero++;
3727 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3728 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3729 hammer2_spin_unex(&parent->core.spin);
3730 panic("insert base %p overlapping elements at %d elm %p\n",
3735 * Try to find an empty slot before or after.
3739 while (j > 0 || k < count) {
3741 if (j >= 0 && base[j].type == 0) {
3745 bcopy(&base[j+1], &base[j],
3746 (i - j - 1) * sizeof(*base));
3752 if (k < count && base[k].type == 0) {
3753 bcopy(&base[i], &base[i+1],
3754 (k - i) * sizeof(hammer2_blockref_t));
3758 * We can only update parent->core.live_zero for live
3761 if (parent->core.live_zero <= k)
3762 parent->core.live_zero = k + 1;
3767 panic("hammer2_base_insert: no room!");
3774 for (l = 0; l < count; ++l) {
3776 key_next = base[l].key +
3777 ((hammer2_key_t)1 << base[l].keybits) - 1;
3781 while (++l < count) {
3783 if (base[l].key <= key_next)
3784 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3785 key_next = base[l].key +
3786 ((hammer2_key_t)1 << base[l].keybits) - 1;
3796 * Sort the blockref array for the chain. Used by the flush code to
3797 * sort the blockref[] array.
3799 * The chain must be exclusively locked AND spin-locked.
3801 typedef hammer2_blockref_t *hammer2_blockref_p;
3805 hammer2_base_sort_callback(const void *v1, const void *v2)
3807 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3808 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3811 * Make sure empty elements are placed at the end of the array
3813 if (bref1->type == 0) {
3814 if (bref2->type == 0)
3817 } else if (bref2->type == 0) {
3824 if (bref1->key < bref2->key)
3826 if (bref1->key > bref2->key)
3832 hammer2_base_sort(hammer2_chain_t *chain)
3834 hammer2_blockref_t *base;
3837 switch(chain->bref.type) {
3838 case HAMMER2_BREF_TYPE_INODE:
3840 * Special shortcut for embedded data returns the inode
3841 * itself. Callers must detect this condition and access
3842 * the embedded data (the strategy code does this for us).
3844 * This is only applicable to regular files and softlinks.
3846 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3848 base = &chain->data->ipdata.u.blockset.blockref[0];
3849 count = HAMMER2_SET_COUNT;
3851 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3852 case HAMMER2_BREF_TYPE_INDIRECT:
3854 * Optimize indirect blocks in the INITIAL state to avoid
3857 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3858 base = &chain->data->npdata[0];
3859 count = chain->bytes / sizeof(hammer2_blockref_t);
3861 case HAMMER2_BREF_TYPE_VOLUME:
3862 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3863 count = HAMMER2_SET_COUNT;
3865 case HAMMER2_BREF_TYPE_FREEMAP:
3866 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3867 count = HAMMER2_SET_COUNT;
3870 kprintf("hammer2_chain_lookup: unrecognized "
3871 "blockref(A) type: %d",
3874 tsleep(&base, 0, "dead", 0);
3875 panic("hammer2_chain_lookup: unrecognized "
3876 "blockref(A) type: %d",
3878 base = NULL; /* safety */
3879 count = 0; /* safety */
3881 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3887 * Chain memory management
3890 hammer2_chain_wait(hammer2_chain_t *chain)
3892 tsleep(chain, 0, "chnflw", 1);
3895 const hammer2_media_data_t *
3896 hammer2_chain_rdata(hammer2_chain_t *chain)
3898 KKASSERT(chain->data != NULL);
3899 return (chain->data);
3902 hammer2_media_data_t *
3903 hammer2_chain_wdata(hammer2_chain_t *chain)
3905 KKASSERT(chain->data != NULL);
3906 return (chain->data);
3910 * Set the check data for a chain. This can be a heavy-weight operation
3911 * and typically only runs on-flush. For file data check data is calculated
3912 * when the logical buffers are flushed.
3915 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3917 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3919 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3920 case HAMMER2_CHECK_NONE:
3922 case HAMMER2_CHECK_DISABLED:
3924 case HAMMER2_CHECK_ISCSI32:
3925 chain->bref.check.iscsi32.value =
3926 hammer2_icrc32(bdata, chain->bytes);
3928 case HAMMER2_CHECK_CRC64:
3929 chain->bref.check.crc64.value = 0;
3932 case HAMMER2_CHECK_SHA192:
3934 SHA256_CTX hash_ctx;
3936 uint8_t digest[SHA256_DIGEST_LENGTH];
3937 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3940 SHA256_Init(&hash_ctx);
3941 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3942 SHA256_Final(u.digest, &hash_ctx);
3943 u.digest64[2] ^= u.digest64[3];
3945 chain->bref.check.sha192.data,
3946 sizeof(chain->bref.check.sha192.data));
3949 case HAMMER2_CHECK_FREEMAP:
3950 chain->bref.check.freemap.icrc32 =
3951 hammer2_icrc32(bdata, chain->bytes);
3954 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3955 chain->bref.methods);
3961 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3965 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3968 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3969 case HAMMER2_CHECK_NONE:
3972 case HAMMER2_CHECK_DISABLED:
3975 case HAMMER2_CHECK_ISCSI32:
3976 r = (chain->bref.check.iscsi32.value ==
3977 hammer2_icrc32(bdata, chain->bytes));
3979 case HAMMER2_CHECK_CRC64:
3980 r = (chain->bref.check.crc64.value == 0);
3983 case HAMMER2_CHECK_SHA192:
3985 SHA256_CTX hash_ctx;
3987 uint8_t digest[SHA256_DIGEST_LENGTH];
3988 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3991 SHA256_Init(&hash_ctx);
3992 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3993 SHA256_Final(u.digest, &hash_ctx);
3994 u.digest64[2] ^= u.digest64[3];
3996 chain->bref.check.sha192.data,
3997 sizeof(chain->bref.check.sha192.data)) == 0) {
4004 case HAMMER2_CHECK_FREEMAP:
4005 r = (chain->bref.check.freemap.icrc32 ==
4006 hammer2_icrc32(bdata, chain->bytes));
4008 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4009 chain->bref.check.freemap.icrc32,
4010 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4012 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4013 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4018 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4019 chain->bref.methods);