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_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_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_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_inode_t *ip,
997 hammer2_chain_t *parent, hammer2_chain_t *chain,
998 int nradix, int flags)
1007 * Only data and indirect blocks can be resized for now.
1008 * (The volu root, inodes, and freemap elements use a fixed size).
1010 KKASSERT(chain != &hmp->vchain);
1011 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1012 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1015 * Nothing to do if the element is already the proper size
1017 obytes = chain->bytes;
1018 nbytes = 1U << nradix;
1019 if (obytes == nbytes)
1023 * Make sure the old data is instantiated so we can copy it. If this
1024 * is a data block, the device data may be superfluous since the data
1025 * might be in a logical block, but compressed or encrypted data is
1028 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1030 hammer2_chain_modify(chain, 0);
1033 * Relocate the block, even if making it smaller (because different
1034 * block sizes may be in different regions).
1036 * (data blocks only, we aren't copying the storage here).
1038 hammer2_freemap_alloc(chain, nbytes);
1039 chain->bytes = nbytes;
1040 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1043 * We don't want the followup chain_modify() to try to copy data
1044 * from the old (wrong-sized) buffer. It won't know how much to
1045 * copy. This case should only occur during writes when the
1046 * originator already has the data to write in-hand.
1049 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1050 hammer2_io_brelse(&chain->dio);
1056 hammer2_chain_modify(hammer2_chain_t *chain, int flags)
1058 hammer2_blockref_t obref;
1067 obref = chain->bref;
1068 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1071 * Data is not optional for freemap chains (we must always be sure
1072 * to copy the data on COW storage allocations).
1074 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1075 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1076 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1077 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1081 * Data must be resolved if already assigned, unless explicitly
1082 * flagged otherwise.
1084 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1085 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1086 hammer2_chain_load_data(chain);
1090 * Set MODIFIED to indicate that the chain has been modified.
1091 * Set UPDATE to ensure that the blockref is updated in the parent.
1093 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1094 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1095 hammer2_chain_ref(chain);
1096 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1101 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1102 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1103 hammer2_chain_ref(chain);
1107 * The modification or re-modification requires an allocation and
1110 * We normally always allocate new storage here. If storage exists
1111 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1113 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1114 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1115 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1117 hammer2_freemap_alloc(chain, chain->bytes);
1118 /* XXX failed allocation */
1123 * Update mirror_tid and modify_tid. modify_tid is only updated
1124 * automatically by this function when used from the frontend.
1125 * Flushes and synchronization adjust the flag manually.
1127 * NOTE: chain->pmp could be the device spmp.
1129 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1130 if (chain->pmp && (flags & HAMMER2_MODIFY_KEEPMODIFY) == 0) {
1131 /* XXX HAMMER2_TRANS_ISFLUSH */
1132 chain->bref.modify_tid = chain->pmp->modify_tid;
1136 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1137 * requires updating as well as to tell the delete code that the
1138 * chain's blockref might not exactly match (in terms of physical size
1139 * or block offset) the one in the parent's blocktable. The base key
1140 * of course will still match.
1142 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1143 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1146 * Short-cut data blocks which the caller does not need an actual
1147 * data reference to (aka OPTDATA), as long as the chain does not
1148 * already have a data pointer to the data. This generally means
1149 * that the modifications are being done via the logical buffer cache.
1150 * The INITIAL flag relates only to the device data buffer and thus
1151 * remains unchange in this situation.
1153 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1154 (flags & HAMMER2_MODIFY_OPTDATA) &&
1155 chain->data == NULL) {
1160 * Clearing the INITIAL flag (for indirect blocks) indicates that
1161 * we've processed the uninitialized storage allocation.
1163 * If this flag is already clear we are likely in a copy-on-write
1164 * situation but we have to be sure NOT to bzero the storage if
1165 * no data is present.
1167 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1168 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1175 * Instantiate data buffer and possibly execute COW operation
1177 switch(chain->bref.type) {
1178 case HAMMER2_BREF_TYPE_VOLUME:
1179 case HAMMER2_BREF_TYPE_FREEMAP:
1181 * The data is embedded, no copy-on-write operation is
1184 KKASSERT(chain->dio == NULL);
1186 case HAMMER2_BREF_TYPE_INODE:
1187 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1188 case HAMMER2_BREF_TYPE_DATA:
1189 case HAMMER2_BREF_TYPE_INDIRECT:
1190 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1192 * Perform the copy-on-write operation
1194 * zero-fill or copy-on-write depending on whether
1195 * chain->data exists or not and set the dirty state for
1196 * the new buffer. hammer2_io_new() will handle the
1199 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1202 error = hammer2_io_new(hmp, chain->bref.data_off,
1203 chain->bytes, &dio);
1205 error = hammer2_io_bread(hmp, chain->bref.data_off,
1206 chain->bytes, &dio);
1208 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1211 * If an I/O error occurs make sure callers cannot accidently
1212 * modify the old buffer's contents and corrupt the filesystem.
1215 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1217 chain->error = HAMMER2_ERROR_IO;
1218 hammer2_io_brelse(&dio);
1219 hammer2_io_brelse(&chain->dio);
1224 bdata = hammer2_io_data(dio, chain->bref.data_off);
1227 KKASSERT(chain->dio != NULL);
1228 if (chain->data != (void *)bdata) {
1229 bcopy(chain->data, bdata, chain->bytes);
1231 } else if (wasinitial == 0) {
1233 * We have a problem. We were asked to COW but
1234 * we don't have any data to COW with!
1236 panic("hammer2_chain_modify: having a COW %p\n",
1241 * Retire the old buffer, replace with the new. Dirty or
1242 * redirty the new buffer.
1244 * WARNING! The system buffer cache may have already flushed
1245 * the buffer, so we must be sure to [re]dirty it
1246 * for further modification.
1249 hammer2_io_brelse(&chain->dio);
1250 chain->data = (void *)bdata;
1252 hammer2_io_setdirty(dio); /* modified by bcopy above */
1255 panic("hammer2_chain_modify: illegal non-embedded type %d",
1262 * setflush on parent indicating that the parent must recurse down
1263 * to us. Do not call on chain itself which might already have it
1267 hammer2_chain_setflush(chain->parent);
1271 * Modify the chain associated with an inode.
1274 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain, int flags)
1276 hammer2_inode_modify(ip);
1277 hammer2_chain_modify(chain, flags);
1281 * Volume header data locks
1284 hammer2_voldata_lock(hammer2_dev_t *hmp)
1286 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1290 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1292 lockmgr(&hmp->vollk, LK_RELEASE);
1296 hammer2_voldata_modify(hammer2_dev_t *hmp)
1298 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1299 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1300 hammer2_chain_ref(&hmp->vchain);
1301 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1306 * This function returns the chain at the nearest key within the specified
1307 * range. The returned chain will be referenced but not locked.
1309 * This function will recurse through chain->rbtree as necessary and will
1310 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1311 * the iteration value is less than the current value of *key_nextp.
1313 * The caller should use (*key_nextp) to calculate the actual range of
1314 * the returned element, which will be (key_beg to *key_nextp - 1), because
1315 * there might be another element which is superior to the returned element
1318 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1319 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1320 * it will wind up being (key_end + 1).
1322 * WARNING! Must be called with child's spinlock held. Spinlock remains
1323 * held through the operation.
1325 struct hammer2_chain_find_info {
1326 hammer2_chain_t *best;
1327 hammer2_key_t key_beg;
1328 hammer2_key_t key_end;
1329 hammer2_key_t key_next;
1332 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1333 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1337 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1338 hammer2_key_t key_beg, hammer2_key_t key_end)
1340 struct hammer2_chain_find_info info;
1343 info.key_beg = key_beg;
1344 info.key_end = key_end;
1345 info.key_next = *key_nextp;
1347 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1348 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1350 *key_nextp = info.key_next;
1352 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1353 parent, key_beg, key_end, *key_nextp);
1361 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1363 struct hammer2_chain_find_info *info = data;
1364 hammer2_key_t child_beg;
1365 hammer2_key_t child_end;
1367 child_beg = child->bref.key;
1368 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1370 if (child_end < info->key_beg)
1372 if (child_beg > info->key_end)
1379 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1381 struct hammer2_chain_find_info *info = data;
1382 hammer2_chain_t *best;
1383 hammer2_key_t child_end;
1386 * WARNING! Do not discard DUPLICATED chains, it is possible that
1387 * we are catching an insertion half-way done. If a
1388 * duplicated chain turns out to be the best choice the
1389 * caller will re-check its flags after locking it.
1391 * WARNING! Layerq is scanned forwards, exact matches should keep
1392 * the existing info->best.
1394 if ((best = info->best) == NULL) {
1396 * No previous best. Assign best
1399 } else if (best->bref.key <= info->key_beg &&
1400 child->bref.key <= info->key_beg) {
1405 /*info->best = child;*/
1406 } else if (child->bref.key < best->bref.key) {
1408 * Child has a nearer key and best is not flush with key_beg.
1409 * Set best to child. Truncate key_next to the old best key.
1412 if (info->key_next > best->bref.key || info->key_next == 0)
1413 info->key_next = best->bref.key;
1414 } else if (child->bref.key == best->bref.key) {
1416 * If our current best is flush with the child then this
1417 * is an illegal overlap.
1419 * key_next will automatically be limited to the smaller of
1420 * the two end-points.
1426 * Keep the current best but truncate key_next to the child's
1429 * key_next will also automatically be limited to the smaller
1430 * of the two end-points (probably not necessary for this case
1431 * but we do it anyway).
1433 if (info->key_next > child->bref.key || info->key_next == 0)
1434 info->key_next = child->bref.key;
1438 * Always truncate key_next based on child's end-of-range.
1440 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1441 if (child_end && (info->key_next > child_end || info->key_next == 0))
1442 info->key_next = child_end;
1448 * Retrieve the specified chain from a media blockref, creating the
1449 * in-memory chain structure which reflects it.
1451 * To handle insertion races pass the INSERT_RACE flag along with the
1452 * generation number of the core. NULL will be returned if the generation
1453 * number changes before we have a chance to insert the chain. Insert
1454 * races can occur because the parent might be held shared.
1456 * Caller must hold the parent locked shared or exclusive since we may
1457 * need the parent's bref array to find our block.
1459 * WARNING! chain->pmp is always set to NULL for any chain representing
1460 * part of the super-root topology.
1463 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1464 hammer2_blockref_t *bref)
1466 hammer2_dev_t *hmp = parent->hmp;
1467 hammer2_chain_t *chain;
1471 * Allocate a chain structure representing the existing media
1472 * entry. Resulting chain has one ref and is not locked.
1474 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1475 chain = hammer2_chain_alloc(hmp, NULL, bref);
1477 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1478 /* ref'd chain returned */
1481 * Flag that the chain is in the parent's blockmap so delete/flush
1482 * knows what to do with it.
1484 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1487 * Link the chain into its parent. A spinlock is required to safely
1488 * access the RBTREE, and it is possible to collide with another
1489 * hammer2_chain_get() operation because the caller might only hold
1490 * a shared lock on the parent.
1492 KKASSERT(parent->refs > 0);
1493 error = hammer2_chain_insert(parent, chain,
1494 HAMMER2_CHAIN_INSERT_SPIN |
1495 HAMMER2_CHAIN_INSERT_RACE,
1498 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1499 kprintf("chain %p get race\n", chain);
1500 hammer2_chain_drop(chain);
1503 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1507 * Return our new chain referenced but not locked, or NULL if
1514 * Lookup initialization/completion API
1517 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1519 hammer2_chain_ref(parent);
1520 if (flags & HAMMER2_LOOKUP_SHARED) {
1521 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1522 HAMMER2_RESOLVE_SHARED);
1524 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1530 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1533 hammer2_chain_unlock(parent);
1534 hammer2_chain_drop(parent);
1540 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1542 hammer2_chain_t *oparent;
1543 hammer2_chain_t *nparent;
1546 * Be careful of order, oparent must be unlocked before nparent
1547 * is locked below to avoid a deadlock.
1550 hammer2_spin_ex(&oparent->core.spin);
1551 nparent = oparent->parent;
1552 hammer2_chain_ref(nparent);
1553 hammer2_spin_unex(&oparent->core.spin);
1555 hammer2_chain_unlock(oparent);
1556 hammer2_chain_drop(oparent);
1560 hammer2_chain_lock(nparent, how);
1567 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1568 * (*parentp) typically points to an inode but can also point to a related
1569 * indirect block and this function will recurse upwards and find the inode
1572 * (*parentp) must be exclusively locked and referenced and can be an inode
1573 * or an existing indirect block within the inode.
1575 * On return (*parentp) will be modified to point at the deepest parent chain
1576 * element encountered during the search, as a helper for an insertion or
1577 * deletion. The new (*parentp) will be locked and referenced and the old
1578 * will be unlocked and dereferenced (no change if they are both the same).
1580 * The matching chain will be returned exclusively locked. If NOLOCK is
1581 * requested the chain will be returned only referenced. Note that the
1582 * parent chain must always be locked shared or exclusive, matching the
1583 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1584 * when NOLOCK is specified but that complicates matters if *parentp must
1585 * inherit the chain.
1587 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1588 * data pointer or can otherwise be in flux.
1590 * NULL is returned if no match was found, but (*parentp) will still
1591 * potentially be adjusted.
1593 * If a fatal error occurs (typically an I/O error), a dummy chain is
1594 * returned with chain->error and error-identifying information set. This
1595 * chain will assert if you try to do anything fancy with it.
1597 * XXX Depending on where the error occurs we should allow continued iteration.
1599 * On return (*key_nextp) will point to an iterative value for key_beg.
1600 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1602 * This function will also recurse up the chain if the key is not within the
1603 * current parent's range. (*parentp) can never be set to NULL. An iteration
1604 * can simply allow (*parentp) to float inside the loop.
1606 * NOTE! chain->data is not always resolved. By default it will not be
1607 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1608 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1609 * BREF_TYPE_DATA as the device buffer can alias the logical file
1613 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1614 hammer2_key_t key_beg, hammer2_key_t key_end,
1615 int *cache_indexp, int flags)
1618 hammer2_chain_t *parent;
1619 hammer2_chain_t *chain;
1620 hammer2_blockref_t *base;
1621 hammer2_blockref_t *bref;
1622 hammer2_blockref_t bcopy;
1623 hammer2_key_t scan_beg;
1624 hammer2_key_t scan_end;
1626 int how_always = HAMMER2_RESOLVE_ALWAYS;
1627 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1630 int maxloops = 300000;
1632 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1633 how_maybe = how_always;
1634 how = HAMMER2_RESOLVE_ALWAYS;
1635 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1636 how = HAMMER2_RESOLVE_NEVER;
1638 how = HAMMER2_RESOLVE_MAYBE;
1640 if (flags & HAMMER2_LOOKUP_SHARED) {
1641 how_maybe |= HAMMER2_RESOLVE_SHARED;
1642 how_always |= HAMMER2_RESOLVE_SHARED;
1643 how |= HAMMER2_RESOLVE_SHARED;
1647 * Recurse (*parentp) upward if necessary until the parent completely
1648 * encloses the key range or we hit the inode.
1650 * This function handles races against the flusher doing a delete-
1651 * duplicate above us and re-homes the parent to the duplicate in
1652 * that case, otherwise we'd wind up recursing down a stale chain.
1657 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1658 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1659 scan_beg = parent->bref.key;
1660 scan_end = scan_beg +
1661 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1662 if (key_beg >= scan_beg && key_end <= scan_end)
1664 parent = hammer2_chain_getparent(parentp, how_maybe);
1668 if (--maxloops == 0)
1669 panic("hammer2_chain_lookup: maxloops");
1671 * Locate the blockref array. Currently we do a fully associative
1672 * search through the array.
1674 switch(parent->bref.type) {
1675 case HAMMER2_BREF_TYPE_INODE:
1677 * Special shortcut for embedded data returns the inode
1678 * itself. Callers must detect this condition and access
1679 * the embedded data (the strategy code does this for us).
1681 * This is only applicable to regular files and softlinks.
1683 if (parent->data->ipdata.meta.op_flags &
1684 HAMMER2_OPFLAG_DIRECTDATA) {
1685 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1687 *key_nextp = key_end + 1;
1690 hammer2_chain_ref(parent);
1691 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1692 hammer2_chain_lock(parent, how_always);
1693 *key_nextp = key_end + 1;
1696 base = &parent->data->ipdata.u.blockset.blockref[0];
1697 count = HAMMER2_SET_COUNT;
1699 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1700 case HAMMER2_BREF_TYPE_INDIRECT:
1702 * Handle MATCHIND on the parent
1704 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1705 scan_beg = parent->bref.key;
1706 scan_end = scan_beg +
1707 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1708 if (key_beg == scan_beg && key_end == scan_end) {
1710 hammer2_chain_ref(chain);
1711 hammer2_chain_lock(chain, how_maybe);
1712 *key_nextp = scan_end + 1;
1717 * Optimize indirect blocks in the INITIAL state to avoid
1720 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1723 if (parent->data == NULL)
1724 panic("parent->data is NULL");
1725 base = &parent->data->npdata[0];
1727 count = parent->bytes / sizeof(hammer2_blockref_t);
1729 case HAMMER2_BREF_TYPE_VOLUME:
1730 base = &hmp->voldata.sroot_blockset.blockref[0];
1731 count = HAMMER2_SET_COUNT;
1733 case HAMMER2_BREF_TYPE_FREEMAP:
1734 base = &hmp->voldata.freemap_blockset.blockref[0];
1735 count = HAMMER2_SET_COUNT;
1738 kprintf("hammer2_chain_lookup: unrecognized "
1739 "blockref(B) type: %d",
1742 tsleep(&base, 0, "dead", 0);
1743 panic("hammer2_chain_lookup: unrecognized "
1744 "blockref(B) type: %d",
1746 base = NULL; /* safety */
1747 count = 0; /* safety */
1751 * Merged scan to find next candidate.
1753 * hammer2_base_*() functions require the parent->core.live_* fields
1754 * to be synchronized.
1756 * We need to hold the spinlock to access the block array and RB tree
1757 * and to interlock chain creation.
1759 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1760 hammer2_chain_countbrefs(parent, base, count);
1765 hammer2_spin_ex(&parent->core.spin);
1766 chain = hammer2_combined_find(parent, base, count,
1767 cache_indexp, key_nextp,
1770 generation = parent->core.generation;
1773 * Exhausted parent chain, iterate.
1776 hammer2_spin_unex(&parent->core.spin);
1777 if (key_beg == key_end) /* short cut single-key case */
1781 * Stop if we reached the end of the iteration.
1783 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1784 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1789 * Calculate next key, stop if we reached the end of the
1790 * iteration, otherwise go up one level and loop.
1792 key_beg = parent->bref.key +
1793 ((hammer2_key_t)1 << parent->bref.keybits);
1794 if (key_beg == 0 || key_beg > key_end)
1796 parent = hammer2_chain_getparent(parentp, how_maybe);
1801 * Selected from blockref or in-memory chain.
1803 if (chain == NULL) {
1805 hammer2_spin_unex(&parent->core.spin);
1806 chain = hammer2_chain_get(parent, generation,
1808 if (chain == NULL) {
1809 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1810 parent, key_beg, key_end);
1813 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1814 hammer2_chain_drop(chain);
1818 hammer2_chain_ref(chain);
1819 hammer2_spin_unex(&parent->core.spin);
1823 * chain is referenced but not locked. We must lock the chain
1824 * to obtain definitive DUPLICATED/DELETED state
1826 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1827 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1828 hammer2_chain_lock(chain, how_maybe);
1830 hammer2_chain_lock(chain, how);
1834 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1836 * NOTE: Chain's key range is not relevant as there might be
1837 * one-offs within the range that are not deleted.
1839 * NOTE: Lookups can race delete-duplicate because
1840 * delete-duplicate does not lock the parent's core
1841 * (they just use the spinlock on the core). We must
1842 * check for races by comparing the DUPLICATED flag before
1843 * releasing the spinlock with the flag after locking the
1846 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1847 hammer2_chain_unlock(chain);
1848 hammer2_chain_drop(chain);
1849 key_beg = *key_nextp;
1850 if (key_beg == 0 || key_beg > key_end)
1856 * If the chain element is an indirect block it becomes the new
1857 * parent and we loop on it. We must maintain our top-down locks
1858 * to prevent the flusher from interfering (i.e. doing a
1859 * delete-duplicate and leaving us recursing down a deleted chain).
1861 * The parent always has to be locked with at least RESOLVE_MAYBE
1862 * so we can access its data. It might need a fixup if the caller
1863 * passed incompatible flags. Be careful not to cause a deadlock
1864 * as a data-load requires an exclusive lock.
1866 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1867 * range is within the requested key range we return the indirect
1868 * block and do NOT loop. This is usually only used to acquire
1871 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1872 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1873 hammer2_chain_unlock(parent);
1874 hammer2_chain_drop(parent);
1875 *parentp = parent = chain;
1880 * All done, return the chain.
1882 * If the caller does not want a locked chain, replace the lock with
1883 * a ref. Perhaps this can eventually be optimized to not obtain the
1884 * lock in the first place for situations where the data does not
1885 * need to be resolved.
1888 if (flags & HAMMER2_LOOKUP_NOLOCK)
1889 hammer2_chain_unlock(chain);
1896 * After having issued a lookup we can iterate all matching keys.
1898 * If chain is non-NULL we continue the iteration from just after it's index.
1900 * If chain is NULL we assume the parent was exhausted and continue the
1901 * iteration at the next parent.
1903 * If a fatal error occurs (typically an I/O error), a dummy chain is
1904 * returned with chain->error and error-identifying information set. This
1905 * chain will assert if you try to do anything fancy with it.
1907 * XXX Depending on where the error occurs we should allow continued iteration.
1909 * parent must be locked on entry and remains locked throughout. chain's
1910 * lock status must match flags. Chain is always at least referenced.
1912 * WARNING! The MATCHIND flag does not apply to this function.
1915 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1916 hammer2_key_t *key_nextp,
1917 hammer2_key_t key_beg, hammer2_key_t key_end,
1918 int *cache_indexp, int flags)
1920 hammer2_chain_t *parent;
1924 * Calculate locking flags for upward recursion.
1926 how_maybe = HAMMER2_RESOLVE_MAYBE;
1927 if (flags & HAMMER2_LOOKUP_SHARED)
1928 how_maybe |= HAMMER2_RESOLVE_SHARED;
1933 * Calculate the next index and recalculate the parent if necessary.
1936 key_beg = chain->bref.key +
1937 ((hammer2_key_t)1 << chain->bref.keybits);
1938 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1939 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1940 hammer2_chain_unlock(chain);
1942 hammer2_chain_drop(chain);
1945 * chain invalid past this point, but we can still do a
1946 * pointer comparison w/parent.
1948 * Any scan where the lookup returned degenerate data embedded
1949 * in the inode has an invalid index and must terminate.
1951 if (chain == parent)
1953 if (key_beg == 0 || key_beg > key_end)
1956 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1957 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1959 * We reached the end of the iteration.
1964 * Continue iteration with next parent unless the current
1965 * parent covers the range.
1967 key_beg = parent->bref.key +
1968 ((hammer2_key_t)1 << parent->bref.keybits);
1969 if (key_beg == 0 || key_beg > key_end)
1971 parent = hammer2_chain_getparent(parentp, how_maybe);
1977 return (hammer2_chain_lookup(parentp, key_nextp,
1979 cache_indexp, flags));
1983 * The raw scan function is similar to lookup/next but does not seek to a key.
1984 * Blockrefs are iterated via first_chain = (parent, NULL) and
1985 * next_chain = (parent, chain).
1987 * The passed-in parent must be locked and its data resolved. The returned
1988 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1989 * under parent and then iterate with the passed-in chain (which this
1990 * function will unlock).
1993 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1994 int *cache_indexp, int flags)
1997 hammer2_blockref_t *base;
1998 hammer2_blockref_t *bref;
1999 hammer2_blockref_t bcopy;
2001 hammer2_key_t next_key;
2003 int how_always = HAMMER2_RESOLVE_ALWAYS;
2004 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2007 int maxloops = 300000;
2012 * Scan flags borrowed from lookup.
2014 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2015 how_maybe = how_always;
2016 how = HAMMER2_RESOLVE_ALWAYS;
2017 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2018 how = HAMMER2_RESOLVE_NEVER;
2020 how = HAMMER2_RESOLVE_MAYBE;
2022 if (flags & HAMMER2_LOOKUP_SHARED) {
2023 how_maybe |= HAMMER2_RESOLVE_SHARED;
2024 how_always |= HAMMER2_RESOLVE_SHARED;
2025 how |= HAMMER2_RESOLVE_SHARED;
2029 * Calculate key to locate first/next element, unlocking the previous
2030 * element as we go. Be careful, the key calculation can overflow.
2033 key = chain->bref.key +
2034 ((hammer2_key_t)1 << chain->bref.keybits);
2035 hammer2_chain_unlock(chain);
2036 hammer2_chain_drop(chain);
2045 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2046 if (--maxloops == 0)
2047 panic("hammer2_chain_scan: maxloops");
2049 * Locate the blockref array. Currently we do a fully associative
2050 * search through the array.
2052 switch(parent->bref.type) {
2053 case HAMMER2_BREF_TYPE_INODE:
2055 * An inode with embedded data has no sub-chains.
2057 if (parent->data->ipdata.meta.op_flags &
2058 HAMMER2_OPFLAG_DIRECTDATA) {
2061 base = &parent->data->ipdata.u.blockset.blockref[0];
2062 count = HAMMER2_SET_COUNT;
2064 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2065 case HAMMER2_BREF_TYPE_INDIRECT:
2067 * Optimize indirect blocks in the INITIAL state to avoid
2070 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2073 if (parent->data == NULL)
2074 panic("parent->data is NULL");
2075 base = &parent->data->npdata[0];
2077 count = parent->bytes / sizeof(hammer2_blockref_t);
2079 case HAMMER2_BREF_TYPE_VOLUME:
2080 base = &hmp->voldata.sroot_blockset.blockref[0];
2081 count = HAMMER2_SET_COUNT;
2083 case HAMMER2_BREF_TYPE_FREEMAP:
2084 base = &hmp->voldata.freemap_blockset.blockref[0];
2085 count = HAMMER2_SET_COUNT;
2088 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2090 base = NULL; /* safety */
2091 count = 0; /* safety */
2095 * Merged scan to find next candidate.
2097 * hammer2_base_*() functions require the parent->core.live_* fields
2098 * to be synchronized.
2100 * We need to hold the spinlock to access the block array and RB tree
2101 * and to interlock chain creation.
2103 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2104 hammer2_chain_countbrefs(parent, base, count);
2107 hammer2_spin_ex(&parent->core.spin);
2108 chain = hammer2_combined_find(parent, base, count,
2109 cache_indexp, &next_key,
2110 key, HAMMER2_KEY_MAX,
2112 generation = parent->core.generation;
2115 * Exhausted parent chain, we're done.
2118 hammer2_spin_unex(&parent->core.spin);
2119 KKASSERT(chain == NULL);
2124 * Selected from blockref or in-memory chain.
2126 if (chain == NULL) {
2128 hammer2_spin_unex(&parent->core.spin);
2129 chain = hammer2_chain_get(parent, generation, &bcopy);
2130 if (chain == NULL) {
2131 kprintf("retry scan parent %p keys %016jx\n",
2135 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2136 hammer2_chain_drop(chain);
2141 hammer2_chain_ref(chain);
2142 hammer2_spin_unex(&parent->core.spin);
2146 * chain is referenced but not locked. We must lock the chain
2147 * to obtain definitive DUPLICATED/DELETED state
2149 hammer2_chain_lock(chain, how);
2152 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2154 * NOTE: chain's key range is not relevant as there might be
2155 * one-offs within the range that are not deleted.
2157 * NOTE: XXX this could create problems with scans used in
2158 * situations other than mount-time recovery.
2160 * NOTE: Lookups can race delete-duplicate because
2161 * delete-duplicate does not lock the parent's core
2162 * (they just use the spinlock on the core). We must
2163 * check for races by comparing the DUPLICATED flag before
2164 * releasing the spinlock with the flag after locking the
2167 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2168 hammer2_chain_unlock(chain);
2169 hammer2_chain_drop(chain);
2180 * All done, return the chain or NULL
2186 * Create and return a new hammer2 system memory structure of the specified
2187 * key, type and size and insert it under (*parentp). This is a full
2188 * insertion, based on the supplied key/keybits, and may involve creating
2189 * indirect blocks and moving other chains around via delete/duplicate.
2191 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2192 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2193 * FULL. This typically means that the caller is creating the chain after
2194 * doing a hammer2_chain_lookup().
2196 * (*parentp) must be exclusive locked and may be replaced on return
2197 * depending on how much work the function had to do.
2199 * (*parentp) must not be errored or this function will assert.
2201 * (*chainp) usually starts out NULL and returns the newly created chain,
2202 * but if the caller desires the caller may allocate a disconnected chain
2203 * and pass it in instead.
2205 * This function should NOT be used to insert INDIRECT blocks. It is
2206 * typically used to create/insert inodes and data blocks.
2208 * Caller must pass-in an exclusively locked parent the new chain is to
2209 * be inserted under, and optionally pass-in a disconnected, exclusively
2210 * locked chain to insert (else we create a new chain). The function will
2211 * adjust (*parentp) as necessary, create or connect the chain, and
2212 * return an exclusively locked chain in *chainp.
2214 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2215 * and will be reassigned.
2218 hammer2_chain_create(hammer2_chain_t **parentp,
2219 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2220 hammer2_key_t key, int keybits, int type, size_t bytes,
2224 hammer2_chain_t *chain;
2225 hammer2_chain_t *parent;
2226 hammer2_blockref_t *base;
2227 hammer2_blockref_t dummy;
2231 int maxloops = 300000;
2234 * Topology may be crossing a PFS boundary.
2237 KKASSERT(hammer2_mtx_owned(&parent->lock));
2238 KKASSERT(parent->error == 0);
2242 if (chain == NULL) {
2244 * First allocate media space and construct the dummy bref,
2245 * then allocate the in-memory chain structure. Set the
2246 * INITIAL flag for fresh chains which do not have embedded
2249 bzero(&dummy, sizeof(dummy));
2252 dummy.keybits = keybits;
2253 dummy.data_off = hammer2_getradix(bytes);
2254 dummy.methods = parent->bref.methods;
2255 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2258 * Lock the chain manually, chain_lock will load the chain
2259 * which we do NOT want to do. (note: chain->refs is set
2260 * to 1 by chain_alloc() for us, but lockcnt is not).
2263 hammer2_mtx_ex(&chain->lock);
2267 * Set INITIAL to optimize I/O. The flag will generally be
2268 * processed when we call hammer2_chain_modify().
2270 * Recalculate bytes to reflect the actual media block
2273 bytes = (hammer2_off_t)1 <<
2274 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2275 chain->bytes = bytes;
2278 case HAMMER2_BREF_TYPE_VOLUME:
2279 case HAMMER2_BREF_TYPE_FREEMAP:
2280 panic("hammer2_chain_create: called with volume type");
2282 case HAMMER2_BREF_TYPE_INDIRECT:
2283 panic("hammer2_chain_create: cannot be used to"
2284 "create indirect block");
2286 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2287 panic("hammer2_chain_create: cannot be used to"
2288 "create freemap root or node");
2290 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2291 KKASSERT(bytes == sizeof(chain->data->bmdata));
2293 case HAMMER2_BREF_TYPE_INODE:
2294 case HAMMER2_BREF_TYPE_DATA:
2297 * leave chain->data NULL, set INITIAL
2299 KKASSERT(chain->data == NULL);
2300 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
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.meta.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(parent, key, keybits,
2388 if (nparent == NULL) {
2390 hammer2_chain_drop(chain);
2394 if (parent != nparent) {
2395 hammer2_chain_unlock(parent);
2396 hammer2_chain_drop(parent);
2397 parent = *parentp = nparent;
2403 * Link the chain into its parent.
2405 if (chain->parent != NULL)
2406 panic("hammer2: hammer2_chain_create: chain already connected");
2407 KKASSERT(chain->parent == NULL);
2408 hammer2_chain_insert(parent, chain,
2409 HAMMER2_CHAIN_INSERT_SPIN |
2410 HAMMER2_CHAIN_INSERT_LIVE,
2415 * Mark the newly created chain modified. This will cause
2416 * UPDATE to be set and process the INITIAL flag.
2418 * Device buffers are not instantiated for DATA elements
2419 * as these are handled by logical buffers.
2421 * Indirect and freemap node indirect blocks are handled
2422 * by hammer2_chain_create_indirect() and not by this
2425 * Data for all other bref types is expected to be
2426 * instantiated (INODE, LEAF).
2428 switch(chain->bref.type) {
2429 case HAMMER2_BREF_TYPE_DATA:
2430 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2431 case HAMMER2_BREF_TYPE_INODE:
2432 hammer2_chain_modify(chain, HAMMER2_MODIFY_OPTDATA);
2436 * Remaining types are not supported by this function.
2437 * In particular, INDIRECT and LEAF_NODE types are
2438 * handled by create_indirect().
2440 panic("hammer2_chain_create: bad type: %d",
2447 * When reconnecting a chain we must set UPDATE and
2448 * setflush so the flush recognizes that it must update
2449 * the bref in the parent.
2451 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2452 hammer2_chain_ref(chain);
2453 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2458 * We must setflush(parent) to ensure that it recurses through to
2459 * chain. setflush(chain) might not work because ONFLUSH is possibly
2460 * already set in the chain (so it won't recurse up to set it in the
2463 hammer2_chain_setflush(parent);
2472 * Move the chain from its old parent to a new parent. The chain must have
2473 * already been deleted or already disconnected (or never associated) with
2474 * a parent. The chain is reassociated with the new parent and the deleted
2475 * flag will be cleared (no longer deleted). The chain's modification state
2478 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2479 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2480 * FULL. This typically means that the caller is creating the chain after
2481 * doing a hammer2_chain_lookup().
2483 * A non-NULL bref is typically passed when key and keybits must be overridden.
2484 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2485 * from a passed-in bref and uses the old chain's bref for everything else.
2487 * Neither (parent) or (chain) can be errored.
2489 * If (parent) is non-NULL then the new duplicated chain is inserted under
2492 * If (parent) is NULL then the newly duplicated chain is not inserted
2493 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2494 * passing into hammer2_chain_create() after this function returns).
2496 * WARNING! This function calls create which means it can insert indirect
2497 * blocks. This can cause other unrelated chains in the parent to
2498 * be moved to a newly inserted indirect block in addition to the
2502 hammer2_chain_rename(hammer2_blockref_t *bref,
2503 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2507 hammer2_chain_t *parent;
2511 * WARNING! We should never resolve DATA to device buffers
2512 * (XXX allow it if the caller did?), and since
2513 * we currently do not have the logical buffer cache
2514 * buffer in-hand to fix its cached physical offset
2515 * we also force the modify code to not COW it. XXX
2518 KKASSERT(chain->parent == NULL);
2519 KKASSERT(chain->error == 0);
2522 * Now create a duplicate of the chain structure, associating
2523 * it with the same core, making it the same size, pointing it
2524 * to the same bref (the same media block).
2527 bref = &chain->bref;
2528 bytes = (hammer2_off_t)1 <<
2529 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2532 * If parent is not NULL the duplicated chain will be entered under
2533 * the parent and the UPDATE bit set to tell flush to update
2536 * We must setflush(parent) to ensure that it recurses through to
2537 * chain. setflush(chain) might not work because ONFLUSH is possibly
2538 * already set in the chain (so it won't recurse up to set it in the
2541 * Having both chains locked is extremely important for atomicy.
2543 if (parentp && (parent = *parentp) != NULL) {
2544 KKASSERT(hammer2_mtx_owned(&parent->lock));
2545 KKASSERT(parent->refs > 0);
2546 KKASSERT(parent->error == 0);
2548 hammer2_chain_create(parentp, &chain, chain->pmp,
2549 bref->key, bref->keybits, bref->type,
2550 chain->bytes, flags);
2551 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2552 hammer2_chain_setflush(*parentp);
2557 * Helper function for deleting chains.
2559 * The chain is removed from the live view (the RBTREE) as well as the parent's
2560 * blockmap. Both chain and its parent must be locked.
2562 * parent may not be errored. chain can be errored.
2565 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2570 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2571 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2574 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2576 * Chain is blockmapped, so there must be a parent.
2577 * Atomically remove the chain from the parent and remove
2578 * the blockmap entry.
2580 hammer2_blockref_t *base;
2583 KKASSERT(parent != NULL);
2584 KKASSERT(parent->error == 0);
2585 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2586 hammer2_chain_modify(parent, HAMMER2_MODIFY_OPTDATA);
2589 * Calculate blockmap pointer
2591 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2592 hammer2_spin_ex(&parent->core.spin);
2594 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2595 atomic_add_int(&parent->core.live_count, -1);
2596 ++parent->core.generation;
2597 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2598 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2599 --parent->core.chain_count;
2600 chain->parent = NULL;
2602 switch(parent->bref.type) {
2603 case HAMMER2_BREF_TYPE_INODE:
2605 * Access the inode's block array. However, there
2606 * is no block array if the inode is flagged
2607 * DIRECTDATA. The DIRECTDATA case typicaly only
2608 * occurs when a hardlink has been shifted up the
2609 * tree and the original inode gets replaced with
2610 * an OBJTYPE_HARDLINK placeholding inode.
2613 (parent->data->ipdata.meta.op_flags &
2614 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2616 &parent->data->ipdata.u.blockset.blockref[0];
2620 count = HAMMER2_SET_COUNT;
2622 case HAMMER2_BREF_TYPE_INDIRECT:
2623 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2625 base = &parent->data->npdata[0];
2628 count = parent->bytes / sizeof(hammer2_blockref_t);
2630 case HAMMER2_BREF_TYPE_VOLUME:
2631 base = &hmp->voldata.sroot_blockset.blockref[0];
2632 count = HAMMER2_SET_COUNT;
2634 case HAMMER2_BREF_TYPE_FREEMAP:
2635 base = &parent->data->npdata[0];
2636 count = HAMMER2_SET_COUNT;
2641 panic("hammer2_flush_pass2: "
2642 "unrecognized blockref type: %d",
2647 * delete blockmapped chain from its parent.
2649 * The parent is not affected by any statistics in chain
2650 * which are pending synchronization. That is, there is
2651 * nothing to undo in the parent since they have not yet
2652 * been incorporated into the parent.
2654 * The parent is affected by statistics stored in inodes.
2655 * Those have already been synchronized, so they must be
2656 * undone. XXX split update possible w/delete in middle?
2659 int cache_index = -1;
2660 hammer2_base_delete(parent, base, count,
2661 &cache_index, chain);
2663 hammer2_spin_unex(&parent->core.spin);
2664 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2666 * Chain is not blockmapped but a parent is present.
2667 * Atomically remove the chain from the parent. There is
2668 * no blockmap entry to remove.
2670 * Because chain was associated with a parent but not
2671 * synchronized, the chain's *_count_up fields contain
2672 * inode adjustment statistics which must be undone.
2674 hammer2_spin_ex(&parent->core.spin);
2675 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2676 atomic_add_int(&parent->core.live_count, -1);
2677 ++parent->core.generation;
2678 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2679 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2680 --parent->core.chain_count;
2681 chain->parent = NULL;
2682 hammer2_spin_unex(&parent->core.spin);
2685 * Chain is not blockmapped and has no parent. This
2686 * is a degenerate case.
2688 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2693 * Create an indirect block that covers one or more of the elements in the
2694 * current parent. Either returns the existing parent with no locking or
2695 * ref changes or returns the new indirect block locked and referenced
2696 * and leaving the original parent lock/ref intact as well.
2698 * If an error occurs, NULL is returned and *errorp is set to the error.
2700 * The returned chain depends on where the specified key falls.
2702 * The key/keybits for the indirect mode only needs to follow three rules:
2704 * (1) That all elements underneath it fit within its key space and
2706 * (2) That all elements outside it are outside its key space.
2708 * (3) When creating the new indirect block any elements in the current
2709 * parent that fit within the new indirect block's keyspace must be
2710 * moved into the new indirect block.
2712 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2713 * keyspace the the current parent, but lookup/iteration rules will
2714 * ensure (and must ensure) that rule (2) for all parents leading up
2715 * to the nearest inode or the root volume header is adhered to. This
2716 * is accomplished by always recursing through matching keyspaces in
2717 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2719 * The current implementation calculates the current worst-case keyspace by
2720 * iterating the current parent and then divides it into two halves, choosing
2721 * whichever half has the most elements (not necessarily the half containing
2722 * the requested key).
2724 * We can also opt to use the half with the least number of elements. This
2725 * causes lower-numbered keys (aka logical file offsets) to recurse through
2726 * fewer indirect blocks and higher-numbered keys to recurse through more.
2727 * This also has the risk of not moving enough elements to the new indirect
2728 * block and being forced to create several indirect blocks before the element
2731 * Must be called with an exclusively locked parent.
2733 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2734 hammer2_key_t *keyp, int keybits,
2735 hammer2_blockref_t *base, int count);
2736 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2737 hammer2_key_t *keyp, int keybits,
2738 hammer2_blockref_t *base, int count);
2741 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2742 hammer2_key_t create_key, int create_bits,
2743 int for_type, int *errorp)
2746 hammer2_blockref_t *base;
2747 hammer2_blockref_t *bref;
2748 hammer2_blockref_t bcopy;
2749 hammer2_chain_t *chain;
2750 hammer2_chain_t *ichain;
2751 hammer2_chain_t dummy;
2752 hammer2_key_t key = create_key;
2753 hammer2_key_t key_beg;
2754 hammer2_key_t key_end;
2755 hammer2_key_t key_next;
2756 int keybits = create_bits;
2763 int maxloops = 300000;
2766 * Calculate the base blockref pointer or NULL if the chain
2767 * is known to be empty. We need to calculate the array count
2768 * for RB lookups either way.
2772 KKASSERT(hammer2_mtx_owned(&parent->lock));
2774 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2775 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2778 switch(parent->bref.type) {
2779 case HAMMER2_BREF_TYPE_INODE:
2780 count = HAMMER2_SET_COUNT;
2782 case HAMMER2_BREF_TYPE_INDIRECT:
2783 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2784 count = parent->bytes / sizeof(hammer2_blockref_t);
2786 case HAMMER2_BREF_TYPE_VOLUME:
2787 count = HAMMER2_SET_COUNT;
2789 case HAMMER2_BREF_TYPE_FREEMAP:
2790 count = HAMMER2_SET_COUNT;
2793 panic("hammer2_chain_create_indirect: "
2794 "unrecognized blockref type: %d",
2800 switch(parent->bref.type) {
2801 case HAMMER2_BREF_TYPE_INODE:
2802 base = &parent->data->ipdata.u.blockset.blockref[0];
2803 count = HAMMER2_SET_COUNT;
2805 case HAMMER2_BREF_TYPE_INDIRECT:
2806 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2807 base = &parent->data->npdata[0];
2808 count = parent->bytes / sizeof(hammer2_blockref_t);
2810 case HAMMER2_BREF_TYPE_VOLUME:
2811 base = &hmp->voldata.sroot_blockset.blockref[0];
2812 count = HAMMER2_SET_COUNT;
2814 case HAMMER2_BREF_TYPE_FREEMAP:
2815 base = &hmp->voldata.freemap_blockset.blockref[0];
2816 count = HAMMER2_SET_COUNT;
2819 panic("hammer2_chain_create_indirect: "
2820 "unrecognized blockref type: %d",
2828 * dummy used in later chain allocation (no longer used for lookups).
2830 bzero(&dummy, sizeof(dummy));
2833 * When creating an indirect block for a freemap node or leaf
2834 * the key/keybits must be fitted to static radix levels because
2835 * particular radix levels use particular reserved blocks in the
2838 * This routine calculates the key/radix of the indirect block
2839 * we need to create, and whether it is on the high-side or the
2842 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2843 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2844 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2847 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2852 * Normalize the key for the radix being represented, keeping the
2853 * high bits and throwing away the low bits.
2855 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2858 * How big should our new indirect block be? It has to be at least
2859 * as large as its parent.
2861 * The freemap uses a specific indirect block size.
2863 * The first indirect block level down from an inode typically
2864 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2866 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2867 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2868 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2869 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2870 nbytes = HAMMER2_IND_BYTES_MIN;
2872 nbytes = HAMMER2_IND_BYTES_MAX;
2874 if (nbytes < count * sizeof(hammer2_blockref_t)) {
2875 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2876 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2877 nbytes = count * sizeof(hammer2_blockref_t);
2881 * Ok, create our new indirect block
2883 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2884 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2885 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2887 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2889 dummy.bref.key = key;
2890 dummy.bref.keybits = keybits;
2891 dummy.bref.data_off = hammer2_getradix(nbytes);
2892 dummy.bref.methods = parent->bref.methods;
2894 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2895 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2896 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2897 /* ichain has one ref at this point */
2900 * We have to mark it modified to allocate its block, but use
2901 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2902 * it won't be acted upon by the flush code.
2904 hammer2_chain_modify(ichain, HAMMER2_MODIFY_OPTDATA);
2907 * Iterate the original parent and move the matching brefs into
2908 * the new indirect block.
2910 * XXX handle flushes.
2913 key_end = HAMMER2_KEY_MAX;
2915 hammer2_spin_ex(&parent->core.spin);
2920 if (++loops > 100000) {
2921 hammer2_spin_unex(&parent->core.spin);
2922 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2923 reason, parent, base, count, key_next);
2927 * NOTE: spinlock stays intact, returned chain (if not NULL)
2928 * is not referenced or locked which means that we
2929 * cannot safely check its flagged / deletion status
2932 chain = hammer2_combined_find(parent, base, count,
2933 &cache_index, &key_next,
2936 generation = parent->core.generation;
2939 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2942 * Skip keys that are not within the key/radix of the new
2943 * indirect block. They stay in the parent.
2945 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2946 (key ^ bref->key)) != 0) {
2947 goto next_key_spinlocked;
2951 * Load the new indirect block by acquiring the related
2952 * chains (potentially from media as it might not be
2953 * in-memory). Then move it to the new parent (ichain)
2954 * via DELETE-DUPLICATE.
2956 * chain is referenced but not locked. We must lock the
2957 * chain to obtain definitive DUPLICATED/DELETED state
2961 * Use chain already present in the RBTREE
2963 hammer2_chain_ref(chain);
2964 hammer2_spin_unex(&parent->core.spin);
2965 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2968 * Get chain for blockref element. _get returns NULL
2969 * on insertion race.
2972 hammer2_spin_unex(&parent->core.spin);
2973 chain = hammer2_chain_get(parent, generation, &bcopy);
2974 if (chain == NULL) {
2976 hammer2_spin_ex(&parent->core.spin);
2979 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2980 kprintf("REASON 2\n");
2982 hammer2_chain_drop(chain);
2983 hammer2_spin_ex(&parent->core.spin);
2986 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2990 * This is always live so if the chain has been deleted
2991 * we raced someone and we have to retry.
2993 * NOTE: Lookups can race delete-duplicate because
2994 * delete-duplicate does not lock the parent's core
2995 * (they just use the spinlock on the core). We must
2996 * check for races by comparing the DUPLICATED flag before
2997 * releasing the spinlock with the flag after locking the
3000 * (note reversed logic for this one)
3002 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3003 hammer2_chain_unlock(chain);
3004 hammer2_chain_drop(chain);
3009 * Shift the chain to the indirect block.
3011 * WARNING! No reason for us to load chain data, pass NOSTATS
3012 * to prevent delete/insert from trying to access
3013 * inode stats (and thus asserting if there is no
3014 * chain->data loaded).
3016 hammer2_chain_delete(parent, chain,
3017 HAMMER2_DELETE_NOSTATS);
3018 hammer2_chain_rename(NULL, &ichain, chain,
3019 HAMMER2_INSERT_NOSTATS);
3020 hammer2_chain_unlock(chain);
3021 hammer2_chain_drop(chain);
3022 KKASSERT(parent->refs > 0);
3025 hammer2_spin_ex(&parent->core.spin);
3026 next_key_spinlocked:
3027 if (--maxloops == 0)
3028 panic("hammer2_chain_create_indirect: maxloops");
3030 if (key_next == 0 || key_next > key_end)
3035 hammer2_spin_unex(&parent->core.spin);
3038 * Insert the new indirect block into the parent now that we've
3039 * cleared out some entries in the parent. We calculated a good
3040 * insertion index in the loop above (ichain->index).
3042 * We don't have to set UPDATE here because we mark ichain
3043 * modified down below (so the normal modified -> flush -> set-moved
3044 * sequence applies).
3046 * The insertion shouldn't race as this is a completely new block
3047 * and the parent is locked.
3049 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3050 hammer2_chain_insert(parent, ichain,
3051 HAMMER2_CHAIN_INSERT_SPIN |
3052 HAMMER2_CHAIN_INSERT_LIVE,
3056 * Make sure flushes propogate after our manual insertion.
3058 hammer2_chain_setflush(ichain);
3059 hammer2_chain_setflush(parent);
3062 * Figure out what to return.
3064 if (~(((hammer2_key_t)1 << keybits) - 1) &
3065 (create_key ^ key)) {
3067 * Key being created is outside the key range,
3068 * return the original parent.
3070 hammer2_chain_unlock(ichain);
3071 hammer2_chain_drop(ichain);
3074 * Otherwise its in the range, return the new parent.
3075 * (leave both the new and old parent locked).
3084 * Calculate the keybits and highside/lowside of the freemap node the
3085 * caller is creating.
3087 * This routine will specify the next higher-level freemap key/radix
3088 * representing the lowest-ordered set. By doing so, eventually all
3089 * low-ordered sets will be moved one level down.
3091 * We have to be careful here because the freemap reserves a limited
3092 * number of blocks for a limited number of levels. So we can't just
3093 * push indiscriminately.
3096 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3097 int keybits, hammer2_blockref_t *base, int count)
3099 hammer2_chain_t *chain;
3100 hammer2_blockref_t *bref;
3102 hammer2_key_t key_beg;
3103 hammer2_key_t key_end;
3104 hammer2_key_t key_next;
3108 int maxloops = 300000;
3116 * Calculate the range of keys in the array being careful to skip
3117 * slots which are overridden with a deletion.
3120 key_end = HAMMER2_KEY_MAX;
3122 hammer2_spin_ex(&parent->core.spin);
3125 if (--maxloops == 0) {
3126 panic("indkey_freemap shit %p %p:%d\n",
3127 parent, base, count);
3129 chain = hammer2_combined_find(parent, base, count,
3130 &cache_index, &key_next,
3141 * Skip deleted chains.
3143 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3144 if (key_next == 0 || key_next > key_end)
3151 * Use the full live (not deleted) element for the scan
3152 * iteration. HAMMER2 does not allow partial replacements.
3154 * XXX should be built into hammer2_combined_find().
3156 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3158 if (keybits > bref->keybits) {
3160 keybits = bref->keybits;
3161 } else if (keybits == bref->keybits && bref->key < key) {
3168 hammer2_spin_unex(&parent->core.spin);
3171 * Return the keybits for a higher-level FREEMAP_NODE covering
3175 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3176 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3178 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3179 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3181 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3182 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3184 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3185 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3187 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3188 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3190 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3191 panic("hammer2_chain_indkey_freemap: level too high");
3194 panic("hammer2_chain_indkey_freemap: bad radix");
3203 * Calculate the keybits and highside/lowside of the indirect block the
3204 * caller is creating.
3207 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3208 int keybits, hammer2_blockref_t *base, int count)
3210 hammer2_blockref_t *bref;
3211 hammer2_chain_t *chain;
3212 hammer2_key_t key_beg;
3213 hammer2_key_t key_end;
3214 hammer2_key_t key_next;
3220 int maxloops = 300000;
3227 * Calculate the range of keys in the array being careful to skip
3228 * slots which are overridden with a deletion. Once the scan
3229 * completes we will cut the key range in half and shift half the
3230 * range into the new indirect block.
3233 key_end = HAMMER2_KEY_MAX;
3235 hammer2_spin_ex(&parent->core.spin);
3238 if (--maxloops == 0) {
3239 panic("indkey_freemap shit %p %p:%d\n",
3240 parent, base, count);
3242 chain = hammer2_combined_find(parent, base, count,
3243 &cache_index, &key_next,
3254 * NOTE: No need to check DUPLICATED here because we do
3255 * not release the spinlock.
3257 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3258 if (key_next == 0 || key_next > key_end)
3265 * Use the full live (not deleted) element for the scan
3266 * iteration. HAMMER2 does not allow partial replacements.
3268 * XXX should be built into hammer2_combined_find().
3270 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3273 * Expand our calculated key range (key, keybits) to fit
3274 * the scanned key. nkeybits represents the full range
3275 * that we will later cut in half (two halves @ nkeybits - 1).
3278 if (nkeybits < bref->keybits) {
3279 if (bref->keybits > 64) {
3280 kprintf("bad bref chain %p bref %p\n",
3284 nkeybits = bref->keybits;
3286 while (nkeybits < 64 &&
3287 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3288 (key ^ bref->key)) != 0) {
3293 * If the new key range is larger we have to determine
3294 * which side of the new key range the existing keys fall
3295 * under by checking the high bit, then collapsing the
3296 * locount into the hicount or vise-versa.
3298 if (keybits != nkeybits) {
3299 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3310 * The newly scanned key will be in the lower half or the
3311 * upper half of the (new) key range.
3313 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3322 hammer2_spin_unex(&parent->core.spin);
3323 bref = NULL; /* now invalid (safety) */
3326 * Adjust keybits to represent half of the full range calculated
3327 * above (radix 63 max)
3332 * Select whichever half contains the most elements. Theoretically
3333 * we can select either side as long as it contains at least one
3334 * element (in order to ensure that a free slot is present to hold
3335 * the indirect block).
3337 if (hammer2_indirect_optimize) {
3339 * Insert node for least number of keys, this will arrange
3340 * the first few blocks of a large file or the first few
3341 * inodes in a directory with fewer indirect blocks when
3344 if (hicount < locount && hicount != 0)
3345 key |= (hammer2_key_t)1 << keybits;
3347 key &= ~(hammer2_key_t)1 << keybits;
3350 * Insert node for most number of keys, best for heavily
3353 if (hicount > locount)
3354 key |= (hammer2_key_t)1 << keybits;
3356 key &= ~(hammer2_key_t)1 << keybits;
3364 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3367 * Both parent and chain must be locked exclusively.
3369 * This function will modify the parent if the blockref requires removal
3370 * from the parent's block table.
3372 * This function is NOT recursive. Any entity already pushed into the
3373 * chain (such as an inode) may still need visibility into its contents,
3374 * as well as the ability to read and modify the contents. For example,
3375 * for an unlinked file which is still open.
3378 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3381 KKASSERT(hammer2_mtx_owned(&chain->lock));
3384 * Nothing to do if already marked.
3386 * We need the spinlock on the core whos RBTREE contains chain
3387 * to protect against races.
3389 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3390 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3391 chain->parent == parent);
3392 _hammer2_chain_delete_helper(parent, chain, flags);
3396 * To avoid losing track of a permanent deletion we add the chain
3397 * to the delayed flush queue. If were to flush it right now the
3398 * parent would end up in a modified state and generate I/O.
3399 * The delayed queue gives the parent a chance to be deleted to
3402 if (flags & HAMMER2_DELETE_PERMANENT) {
3403 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3404 hammer2_delayed_flush(chain);
3406 /* XXX might not be needed */
3407 hammer2_chain_setflush(chain);
3412 * Returns the index of the nearest element in the blockref array >= elm.
3413 * Returns (count) if no element could be found.
3415 * Sets *key_nextp to the next key for loop purposes but does not modify
3416 * it if the next key would be higher than the current value of *key_nextp.
3417 * Note that *key_nexp can overflow to 0, which should be tested by the
3420 * (*cache_indexp) is a heuristic and can be any value without effecting
3423 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3424 * held through the operation.
3427 hammer2_base_find(hammer2_chain_t *parent,
3428 hammer2_blockref_t *base, int count,
3429 int *cache_indexp, hammer2_key_t *key_nextp,
3430 hammer2_key_t key_beg, hammer2_key_t key_end)
3432 hammer2_blockref_t *scan;
3433 hammer2_key_t scan_end;
3438 * Require the live chain's already have their core's counted
3439 * so we can optimize operations.
3441 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3446 if (count == 0 || base == NULL)
3450 * Sequential optimization using *cache_indexp. This is the most
3453 * We can avoid trailing empty entries on live chains, otherwise
3454 * we might have to check the whole block array.
3458 limit = parent->core.live_zero;
3463 KKASSERT(i < count);
3469 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3476 * Search forwards, stop when we find a scan element which
3477 * encloses the key or until we know that there are no further
3481 if (scan->type != 0) {
3482 scan_end = scan->key +
3483 ((hammer2_key_t)1 << scan->keybits) - 1;
3484 if (scan->key > key_beg || scan_end >= key_beg)
3497 scan_end = scan->key +
3498 ((hammer2_key_t)1 << scan->keybits);
3499 if (scan_end && (*key_nextp > scan_end ||
3501 *key_nextp = scan_end;
3509 * Do a combined search and return the next match either from the blockref
3510 * array or from the in-memory chain. Sets *bresp to the returned bref in
3511 * both cases, or sets it to NULL if the search exhausted. Only returns
3512 * a non-NULL chain if the search matched from the in-memory chain.
3514 * When no in-memory chain has been found and a non-NULL bref is returned
3518 * The returned chain is not locked or referenced. Use the returned bref
3519 * to determine if the search exhausted or not. Iterate if the base find
3520 * is chosen but matches a deleted chain.
3522 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3523 * held through the operation.
3525 static hammer2_chain_t *
3526 hammer2_combined_find(hammer2_chain_t *parent,
3527 hammer2_blockref_t *base, int count,
3528 int *cache_indexp, hammer2_key_t *key_nextp,
3529 hammer2_key_t key_beg, hammer2_key_t key_end,
3530 hammer2_blockref_t **bresp)
3532 hammer2_blockref_t *bref;
3533 hammer2_chain_t *chain;
3537 * Lookup in block array and in rbtree.
3539 *key_nextp = key_end + 1;
3540 i = hammer2_base_find(parent, base, count, cache_indexp,
3541 key_nextp, key_beg, key_end);
3542 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3547 if (i == count && chain == NULL) {
3553 * Only chain matched.
3556 bref = &chain->bref;
3561 * Only blockref matched.
3563 if (chain == NULL) {
3569 * Both in-memory and blockref matched, select the nearer element.
3571 * If both are flush with the left-hand side or both are the
3572 * same distance away, select the chain. In this situation the
3573 * chain must have been loaded from the matching blockmap.
3575 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3576 chain->bref.key == base[i].key) {
3577 KKASSERT(chain->bref.key == base[i].key);
3578 bref = &chain->bref;
3583 * Select the nearer key
3585 if (chain->bref.key < base[i].key) {
3586 bref = &chain->bref;
3593 * If the bref is out of bounds we've exhausted our search.
3596 if (bref->key > key_end) {
3606 * Locate the specified block array element and delete it. The element
3609 * The spin lock on the related chain must be held.
3611 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3612 * need to be adjusted when we commit the media change.
3615 hammer2_base_delete(hammer2_chain_t *parent,
3616 hammer2_blockref_t *base, int count,
3617 int *cache_indexp, hammer2_chain_t *chain)
3619 hammer2_blockref_t *elm = &chain->bref;
3620 hammer2_key_t key_next;
3624 * Delete element. Expect the element to exist.
3626 * XXX see caller, flush code not yet sophisticated enough to prevent
3627 * re-flushed in some cases.
3629 key_next = 0; /* max range */
3630 i = hammer2_base_find(parent, base, count, cache_indexp,
3631 &key_next, elm->key, elm->key);
3632 if (i == count || base[i].type == 0 ||
3633 base[i].key != elm->key ||
3634 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3635 base[i].keybits != elm->keybits)) {
3636 hammer2_spin_unex(&parent->core.spin);
3637 panic("delete base %p element not found at %d/%d elm %p\n",
3638 base, i, count, elm);
3643 * Update stats and zero the entry
3645 parent->bref.data_count -= base[i].data_count;
3646 parent->bref.data_count -= (hammer2_off_t)1 <<
3647 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3648 parent->bref.inode_count -= base[i].inode_count;
3649 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3650 parent->bref.inode_count -= 1;
3652 bzero(&base[i], sizeof(*base));
3655 * We can only optimize parent->core.live_zero for live chains.
3657 if (parent->core.live_zero == i + 1) {
3658 while (--i >= 0 && base[i].type == 0)
3660 parent->core.live_zero = i + 1;
3664 * Clear appropriate blockmap flags in chain.
3666 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3667 HAMMER2_CHAIN_BMAPUPD);
3671 * Insert the specified element. The block array must not already have the
3672 * element and must have space available for the insertion.
3674 * The spin lock on the related chain must be held.
3676 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3677 * need to be adjusted when we commit the media change.
3680 hammer2_base_insert(hammer2_chain_t *parent,
3681 hammer2_blockref_t *base, int count,
3682 int *cache_indexp, hammer2_chain_t *chain)
3684 hammer2_blockref_t *elm = &chain->bref;
3685 hammer2_key_t key_next;
3694 * Insert new element. Expect the element to not already exist
3695 * unless we are replacing it.
3697 * XXX see caller, flush code not yet sophisticated enough to prevent
3698 * re-flushed in some cases.
3700 key_next = 0; /* max range */
3701 i = hammer2_base_find(parent, base, count, cache_indexp,
3702 &key_next, elm->key, elm->key);
3705 * Shortcut fill optimization, typical ordered insertion(s) may not
3708 KKASSERT(i >= 0 && i <= count);
3711 * Set appropriate blockmap flags in chain.
3713 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3716 * Update stats and zero the entry
3718 parent->bref.data_count += elm->data_count;
3719 parent->bref.data_count += (hammer2_off_t)1 <<
3720 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3721 parent->bref.inode_count += elm->inode_count;
3722 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3723 parent->bref.inode_count += 1;
3727 * We can only optimize parent->core.live_zero for live chains.
3729 if (i == count && parent->core.live_zero < count) {
3730 i = parent->core.live_zero++;
3735 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3736 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3737 hammer2_spin_unex(&parent->core.spin);
3738 panic("insert base %p overlapping elements at %d elm %p\n",
3743 * Try to find an empty slot before or after.
3747 while (j > 0 || k < count) {
3749 if (j >= 0 && base[j].type == 0) {
3753 bcopy(&base[j+1], &base[j],
3754 (i - j - 1) * sizeof(*base));
3760 if (k < count && base[k].type == 0) {
3761 bcopy(&base[i], &base[i+1],
3762 (k - i) * sizeof(hammer2_blockref_t));
3766 * We can only update parent->core.live_zero for live
3769 if (parent->core.live_zero <= k)
3770 parent->core.live_zero = k + 1;
3775 panic("hammer2_base_insert: no room!");
3782 for (l = 0; l < count; ++l) {
3784 key_next = base[l].key +
3785 ((hammer2_key_t)1 << base[l].keybits) - 1;
3789 while (++l < count) {
3791 if (base[l].key <= key_next)
3792 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3793 key_next = base[l].key +
3794 ((hammer2_key_t)1 << base[l].keybits) - 1;
3804 * Sort the blockref array for the chain. Used by the flush code to
3805 * sort the blockref[] array.
3807 * The chain must be exclusively locked AND spin-locked.
3809 typedef hammer2_blockref_t *hammer2_blockref_p;
3813 hammer2_base_sort_callback(const void *v1, const void *v2)
3815 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3816 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3819 * Make sure empty elements are placed at the end of the array
3821 if (bref1->type == 0) {
3822 if (bref2->type == 0)
3825 } else if (bref2->type == 0) {
3832 if (bref1->key < bref2->key)
3834 if (bref1->key > bref2->key)
3840 hammer2_base_sort(hammer2_chain_t *chain)
3842 hammer2_blockref_t *base;
3845 switch(chain->bref.type) {
3846 case HAMMER2_BREF_TYPE_INODE:
3848 * Special shortcut for embedded data returns the inode
3849 * itself. Callers must detect this condition and access
3850 * the embedded data (the strategy code does this for us).
3852 * This is only applicable to regular files and softlinks.
3854 if (chain->data->ipdata.meta.op_flags &
3855 HAMMER2_OPFLAG_DIRECTDATA) {
3858 base = &chain->data->ipdata.u.blockset.blockref[0];
3859 count = HAMMER2_SET_COUNT;
3861 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3862 case HAMMER2_BREF_TYPE_INDIRECT:
3864 * Optimize indirect blocks in the INITIAL state to avoid
3867 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3868 base = &chain->data->npdata[0];
3869 count = chain->bytes / sizeof(hammer2_blockref_t);
3871 case HAMMER2_BREF_TYPE_VOLUME:
3872 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3873 count = HAMMER2_SET_COUNT;
3875 case HAMMER2_BREF_TYPE_FREEMAP:
3876 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3877 count = HAMMER2_SET_COUNT;
3880 kprintf("hammer2_chain_lookup: unrecognized "
3881 "blockref(A) type: %d",
3884 tsleep(&base, 0, "dead", 0);
3885 panic("hammer2_chain_lookup: unrecognized "
3886 "blockref(A) type: %d",
3888 base = NULL; /* safety */
3889 count = 0; /* safety */
3891 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3897 * Chain memory management
3900 hammer2_chain_wait(hammer2_chain_t *chain)
3902 tsleep(chain, 0, "chnflw", 1);
3905 const hammer2_media_data_t *
3906 hammer2_chain_rdata(hammer2_chain_t *chain)
3908 KKASSERT(chain->data != NULL);
3909 return (chain->data);
3912 hammer2_media_data_t *
3913 hammer2_chain_wdata(hammer2_chain_t *chain)
3915 KKASSERT(chain->data != NULL);
3916 return (chain->data);
3920 * Set the check data for a chain. This can be a heavy-weight operation
3921 * and typically only runs on-flush. For file data check data is calculated
3922 * when the logical buffers are flushed.
3925 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3927 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3929 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3930 case HAMMER2_CHECK_NONE:
3932 case HAMMER2_CHECK_DISABLED:
3934 case HAMMER2_CHECK_ISCSI32:
3935 chain->bref.check.iscsi32.value =
3936 hammer2_icrc32(bdata, chain->bytes);
3938 case HAMMER2_CHECK_CRC64:
3939 chain->bref.check.crc64.value = 0;
3942 case HAMMER2_CHECK_SHA192:
3944 SHA256_CTX hash_ctx;
3946 uint8_t digest[SHA256_DIGEST_LENGTH];
3947 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3950 SHA256_Init(&hash_ctx);
3951 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3952 SHA256_Final(u.digest, &hash_ctx);
3953 u.digest64[2] ^= u.digest64[3];
3955 chain->bref.check.sha192.data,
3956 sizeof(chain->bref.check.sha192.data));
3959 case HAMMER2_CHECK_FREEMAP:
3960 chain->bref.check.freemap.icrc32 =
3961 hammer2_icrc32(bdata, chain->bytes);
3964 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3965 chain->bref.methods);
3971 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3975 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3978 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3979 case HAMMER2_CHECK_NONE:
3982 case HAMMER2_CHECK_DISABLED:
3985 case HAMMER2_CHECK_ISCSI32:
3986 r = (chain->bref.check.iscsi32.value ==
3987 hammer2_icrc32(bdata, chain->bytes));
3989 case HAMMER2_CHECK_CRC64:
3990 r = (chain->bref.check.crc64.value == 0);
3993 case HAMMER2_CHECK_SHA192:
3995 SHA256_CTX hash_ctx;
3997 uint8_t digest[SHA256_DIGEST_LENGTH];
3998 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4001 SHA256_Init(&hash_ctx);
4002 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4003 SHA256_Final(u.digest, &hash_ctx);
4004 u.digest64[2] ^= u.digest64[3];
4006 chain->bref.check.sha192.data,
4007 sizeof(chain->bref.check.sha192.data)) == 0) {
4014 case HAMMER2_CHECK_FREEMAP:
4015 r = (chain->bref.check.freemap.icrc32 ==
4016 hammer2_icrc32(bdata, chain->bytes));
4018 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4019 chain->bref.check.freemap.icrc32,
4020 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4022 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4023 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4028 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4029 chain->bref.methods);
4038 * The chain has been removed from the original directory and replaced
4039 * with a hardlink pointer. Move the chain to the specified parent
4040 * directory, change the filename to "0xINODENUMBER", and adjust the key.
4041 * The chain becomes our invisible hardlink target.
4043 * The original chain must be deleted on entry.
4045 * Caller is responsible for synchronizing ip->meta.name/name_len. This
4046 * routine may be called from a XOP, so modifying ip->meta directly is out.
4050 hammer2_chain_hardlink_shiftup(
4051 hammer2_chain_t *chain,
4053 hammer2_chain_t **dchainp,
4056 hammer2_inode_data_t *nipdata;
4057 hammer2_chain_t *xchain;
4058 hammer2_key_t key_dummy;
4060 hammer2_blockref_t bref;
4062 lhc = inum; /* bit 63 not set makes hardlinks invisible */
4063 KKASSERT((lhc & HAMMER2_DIRHASH_VISIBLE) == 0);
4066 * Locate the inode or indirect block to create the new
4067 * entry in. lhc represents the inode number so there is
4068 * no collision iteration.
4070 * There should be no key collisions with invisible inode keys.
4073 xchain = hammer2_chain_lookup(dchainp, &key_dummy, lhc, lhc, 0);
4075 hammer2_chain_unlock(xchain);
4076 hammer2_chain_drop(xchain);
4085 * Handle the error case
4089 KKASSERT(xchain == NULL);
4094 * Use xcluster as a placeholder for (lhc). Duplicate cluster to the
4095 * same target bref as xcluster and then delete xcluster. The
4096 * duplication occurs after xcluster in flush order even though
4097 * xcluster is deleted after the duplication. XXX
4099 * WARNING! Duplications (to a different parent) can cause indirect
4100 * blocks to be inserted, refactor xcluster.
4102 * WARNING! Only key and keybits is extracted from a passed-in bref.
4105 bref.key = lhc; /* invisible dir entry key */
4107 hammer2_chain_rename(&bref, dchainp, chain, 0);
4110 * cluster is now 'live' again.. adjust the filename.
4112 * Directory entries are inodes but this is a hidden hardlink
4113 * target. The name isn't used but to ease debugging give it
4114 * a name after its inode number.
4116 hammer2_chain_modify(chain, 0);
4117 nipdata = &chain->data->ipdata;
4118 ksnprintf(nipdata->filename, sizeof(nipdata->filename),
4119 "0x%016jx", (intmax_t)inum);
4122 * Warning: Caller must adjust ip->meta.name_lne, name_key,
4125 nipdata->meta.name_len = strlen(nipdata->filename);
4126 nipdata->meta.name_key = lhc;
4127 /*ip->meta.nlinks += nlinks;*/
4131 * Given an exclusively locked inode and cluster we consolidate the cluster
4132 * for hardlink creation, adding (nlinks) to the file's link count and
4133 * potentially relocating the inode to (cdip) which is a parent directory
4134 * common to both the current location of the inode and the intended new
4137 * Replaces (*clusterp) if consolidation occurred, unlocking the old cluster
4138 * and returning a new locked cluster.
4140 * NOTE! This function will also replace ip->cluster.
4143 hammer2_chain_hardlink_consolidate(
4144 hammer2_inode_t *ip,
4145 hammer2_chain_t **chainp,
4146 hammer2_inode_t *cdip,
4147 hammer2_chain_t *cdchain,
4150 hammer2_chain_t *chain;
4151 hammer2_chain_t *parent;
4155 if (nlinks == 0 && /* no hardlink needed */
4156 (ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE)) {
4160 if (hammer2_hardlink_enable == 0) { /* disallow hardlinks */
4161 hammer2_chain_unlock(chain);
4162 hammer2_chain_drop(chain);
4170 * If no change in the hardlink's target directory is required and
4171 * this is already a hardlink target, all we need to do is adjust
4174 if (cdip == ip->pip &&
4175 (ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE) == 0) {
4177 hammer2_inode_modify(ip);
4178 ip->meta.nlinks += nlinks;
4180 hammer2_cluster_modify(cluster, 0);
4181 wipdata = &hammer2_cluster_wdata(cluster)->ipdata;
4182 wipdata->meta.nlinks += nlinks;
4183 hammer2_cluster_modsync(cluster);
4192 * Cluster is the real inode. The originating directory is locked
4193 * by the caller so we can manipulate it without worrying about races
4194 * against other lookups.
4196 * If cluster is visible we need to delete it from the current
4197 * location and create a hardlink pointer in its place. If it is
4198 * not visible we need only delete it. Then later cluster will be
4199 * renamed to a parent directory and converted (if necessary) to
4200 * a hidden inode (via shiftup).
4202 * NOTE! We must hold cparent locked through the delete/create/rename
4203 * operation to ensure that other threads block resolving to
4204 * the same hardlink, otherwise the other threads may not see
4207 KKASSERT((cluster->focus->flags & HAMMER2_CHAIN_DELETED) == 0);
4208 cparent = hammer2_cluster_parent(cluster);
4210 hammer2_cluster_delete(cparent, cluster, 0);
4212 KKASSERT(ip->meta.type != HAMMER2_OBJTYPE_HARDLINK);
4213 if (ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE) {
4214 const hammer2_inode_data_t *ripdata;
4215 hammer2_inode_data_t *wipdata;
4216 hammer2_cluster_t *ncluster;
4220 lhc = cluster->focus->bref.key;
4221 error = hammer2_cluster_create(cparent, &ncluster,
4223 HAMMER2_BREF_TYPE_INODE,
4224 HAMMER2_INODE_BYTES,
4226 hammer2_cluster_modify(ncluster, 0);
4227 wipdata = &hammer2_cluster_wdata(ncluster)->ipdata;
4229 /* wipdata->meta.comp_algo = ip->meta.comp_algo; */
4230 wipdata->meta.comp_algo = 0;
4231 wipdata->meta.check_algo = 0;
4232 wipdata->meta.version = HAMMER2_INODE_VERSION_ONE;
4233 wipdata->meta.inum = ip->meta.inum;
4234 wipdata->meta.target_type = ip->meta.type;
4235 wipdata->meta.type = HAMMER2_OBJTYPE_HARDLINK;
4236 wipdata->meta.uflags = 0;
4237 wipdata->meta.rmajor = 0;
4238 wipdata->meta.rminor = 0;
4239 wipdata->meta.ctime = 0;
4240 wipdata->meta.mtime = 0;
4241 wipdata->meta.atime = 0;
4242 wipdata->meta.btime = 0;
4243 bzero(&wipdata->meta.uid, sizeof(wipdata->meta.uid));
4244 bzero(&wipdata->meta.gid, sizeof(wipdata->meta.gid));
4245 wipdata->meta.op_flags = HAMMER2_OPFLAG_DIRECTDATA;
4246 wipdata->meta.cap_flags = 0;
4247 wipdata->meta.mode = 0;
4248 wipdata->meta.size = 0;
4249 wipdata->meta.nlinks = 1;
4250 wipdata->meta.iparent = 0; /* XXX */
4251 wipdata->meta.pfs_type = 0;
4252 wipdata->meta.pfs_inum = 0;
4253 bzero(&wipdata->meta.pfs_clid, sizeof(wipdata->meta.pfs_clid));
4254 bzero(&wipdata->meta.pfs_fsid, sizeof(wipdata->meta.pfs_fsid));
4255 wipdata->meta.data_quota = 0;
4256 /* wipdata->data_count = 0; */
4257 wipdata->meta.inode_quota = 0;
4258 /* wipdata->inode_count = 0; */
4259 wipdata->meta.attr_tid = 0;
4260 wipdata->meta.dirent_tid = 0;
4261 bzero(&wipdata->u, sizeof(wipdata->u));
4262 ripdata = &hammer2_cluster_rdata(cluster)->ipdata;
4263 KKASSERT(ip->meta.name_len <= sizeof(wipdata->filename));
4264 bcopy(ripdata->filename, wipdata->filename,
4266 wipdata->meta.name_key = ncluster->focus->bref.key;
4267 wipdata->meta.name_len = ip->meta.name_len;
4268 /* XXX transaction ids */
4269 hammer2_cluster_modsync(ncluster);
4270 hammer2_cluster_unlock(ncluster);
4271 hammer2_cluster_drop(ncluster);
4275 * cluster represents the hardlink target and is now flagged deleted.
4276 * duplicate it to the parent directory and adjust nlinks.
4278 * WARNING! The shiftup() call can cause ncluster to be moved into
4279 * an indirect block, and our ncluster will wind up pointing
4280 * to the older/original version.
4282 KKASSERT(cluster->focus->flags & HAMMER2_CHAIN_DELETED);
4283 hammer2_chain_hardlink_shiftup(cluster, ip, cdip, cdcluster,
4287 hammer2_inode_repoint(ip, cdip, cluster);
4291 * Cleanup, cluster/ncluster already dealt with.
4293 * Return the shifted cluster in *clusterp.
4296 hammer2_cluster_unlock(cparent);
4297 hammer2_cluster_drop(cparent);
4299 *clusterp = cluster;
4305 * If (*ochainp) is non-NULL it points to the forward OBJTYPE_HARDLINK
4306 * inode while (*chainp) points to the resolved (hidden hardlink
4307 * target) inode. In this situation when nlinks is 1 we wish to
4308 * deconsolidate the hardlink, moving it back to the directory that now
4309 * represents the only remaining link.
4312 hammer2_chain_hardlink_deconsolidate(
4313 hammer2_inode_t *dip,
4314 hammer2_chain_t **chainp,
4315 hammer2_chain_t **ochainp)
4317 if (*ochainp == NULL)
4326 * The caller presents a shared-locked (parent, chain) where the chain
4327 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4328 * structure representing the inode locked to prevent
4329 * consolidation/deconsolidation races.
4331 * We locate the hardlink in the current or a common parent directory.
4333 * If we are unable to locate the hardlink, EIO is returned and
4334 * (*chainp) is unlocked and dropped.
4337 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4338 hammer2_chain_t **parentp,
4339 hammer2_chain_t **chainp)
4341 hammer2_chain_t *parent;
4342 hammer2_chain_t *rchain;
4343 hammer2_key_t key_dummy;
4345 int cache_index = -1;
4348 * Obtain the key for the hardlink from *chainp.
4351 lhc = rchain->data->ipdata.meta.inum;
4352 hammer2_chain_unlock(rchain);
4353 hammer2_chain_drop(rchain);
4358 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4361 HAMMER2_LOOKUP_SHARED);
4366 * Iterate parents, handle parent rename races by retrying
4374 parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4377 parent = parent->parent;
4380 hammer2_chain_ref(parent);
4381 hammer2_chain_unlock(*parentp);
4382 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4383 HAMMER2_RESOLVE_SHARED);
4384 if ((*parentp)->parent == parent) {
4385 hammer2_chain_drop(*parentp);
4388 hammer2_chain_unlock(parent);
4389 hammer2_chain_drop(parent);
4390 hammer2_chain_lock(*parentp,
4391 HAMMER2_RESOLVE_ALWAYS |
4392 HAMMER2_RESOLVE_SHARED);
4393 parent = NULL; /* safety */
4399 return (rchain ? EIO : 0);