2 * Copyright (c) 2011-2015 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,
72 hammer2_tid_t mtid, int for_type, int *errorp);
73 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
74 static hammer2_chain_t *hammer2_combined_find(
75 hammer2_chain_t *parent,
76 hammer2_blockref_t *base, int count,
77 int *cache_indexp, hammer2_key_t *key_nextp,
78 hammer2_key_t key_beg, hammer2_key_t key_end,
79 hammer2_blockref_t **bresp);
82 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
83 * overlap in the RB trees. Deleted chains are moved from rbtree to either
86 * Chains in delete-duplicate sequences can always iterate through core_entry
87 * to locate the live version of the chain.
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
92 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
100 * Compare chains. Overlaps are not supposed to happen and catch
101 * any software issues early we count overlaps as a match.
103 c1_beg = chain1->bref.key;
104 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
105 c2_beg = chain2->bref.key;
106 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
108 if (c1_end < c2_beg) /* fully to the left */
110 if (c1_beg > c2_end) /* fully to the right */
112 return(0); /* overlap (must not cross edge boundary) */
117 hammer2_isclusterable(hammer2_chain_t *chain)
119 if (hammer2_cluster_enable) {
120 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
121 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
122 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
130 * Make a chain visible to the flusher. The flusher needs to be able to
131 * do flushes of subdirectory chains or single files so it does a top-down
132 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
133 * or UPDATE chains and flushes back up the chain to the volume root.
135 * This routine sets ONFLUSH upward until it hits the volume root. For
136 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
137 * Extra ONFLUSH flagging doesn't hurt the filesystem.
140 hammer2_chain_setflush(hammer2_chain_t *chain)
142 hammer2_chain_t *parent;
144 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 hammer2_spin_sh(&chain->core.spin);
146 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
147 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
148 if ((parent = chain->parent) == NULL)
150 hammer2_spin_sh(&parent->core.spin);
151 hammer2_spin_unsh(&chain->core.spin);
154 hammer2_spin_unsh(&chain->core.spin);
159 * Allocate a new disconnected chain element representing the specified
160 * bref. chain->refs is set to 1 and the passed bref is copied to
161 * chain->bref. chain->bytes is derived from the bref.
163 * chain->pmp inherits pmp unless the chain is an inode (other than the
166 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
169 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
170 hammer2_blockref_t *bref)
172 hammer2_chain_t *chain;
173 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
176 * Construct the appropriate system structure.
179 case HAMMER2_BREF_TYPE_INODE:
180 case HAMMER2_BREF_TYPE_INDIRECT:
181 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
182 case HAMMER2_BREF_TYPE_DATA:
183 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
185 * Chain's are really only associated with the hmp but we
186 * maintain a pmp association for per-mount memory tracking
187 * purposes. The pmp can be NULL.
189 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
191 case HAMMER2_BREF_TYPE_VOLUME:
192 case HAMMER2_BREF_TYPE_FREEMAP:
194 * Only hammer2_chain_bulksnap() calls this function with these
197 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
201 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
206 * Initialize the new chain structure. pmp must be set to NULL for
207 * chains belonging to the super-root topology of a device mount.
209 if (pmp == hmp->spmp)
215 chain->bytes = bytes;
217 chain->flags = HAMMER2_CHAIN_ALLOCATED;
220 * Set the PFS boundary flag if this chain represents a PFS root.
222 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
223 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
224 hammer2_chain_core_init(chain);
230 * Initialize a chain's core structure. This structure used to be allocated
231 * but is now embedded.
233 * The core is not locked. No additional refs on the chain are made.
234 * (trans) must not be NULL if (core) is not NULL.
237 hammer2_chain_core_init(hammer2_chain_t *chain)
240 * Fresh core under nchain (no multi-homing of ochain's
243 RB_INIT(&chain->core.rbtree); /* live chains */
244 hammer2_mtx_init(&chain->lock, "h2chain");
248 * Add a reference to a chain element, preventing its destruction.
250 * (can be called with spinlock held)
253 hammer2_chain_ref(hammer2_chain_t *chain)
255 atomic_add_int(&chain->refs, 1);
257 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
263 * Insert the chain in the core rbtree.
265 * Normal insertions are placed in the live rbtree. Insertion of a deleted
266 * chain is a special case used by the flush code that is placed on the
267 * unstaged deleted list to avoid confusing the live view.
269 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
270 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
271 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
275 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
276 int flags, int generation)
278 hammer2_chain_t *xchain;
281 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
282 hammer2_spin_ex(&parent->core.spin);
285 * Interlocked by spinlock, check for race
287 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
288 parent->core.generation != generation) {
296 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
297 KASSERT(xchain == NULL,
298 ("hammer2_chain_insert: collision %p %p", chain, xchain));
299 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
300 chain->parent = parent;
301 ++parent->core.chain_count;
302 ++parent->core.generation; /* XXX incs for _get() too, XXX */
305 * We have to keep track of the effective live-view blockref count
306 * so the create code knows when to push an indirect block.
308 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
309 atomic_add_int(&parent->core.live_count, 1);
311 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
312 hammer2_spin_unex(&parent->core.spin);
317 * Drop the caller's reference to the chain. When the ref count drops to
318 * zero this function will try to disassociate the chain from its parent and
319 * deallocate it, then recursely drop the parent using the implied ref
320 * from the chain's chain->parent.
322 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
325 hammer2_chain_drop(hammer2_chain_t *chain)
330 if (hammer2_debug & 0x200000)
333 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
337 if (chain->flags & HAMMER2_CHAIN_UPDATE)
339 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
341 KKASSERT(chain->refs > need);
349 chain = hammer2_chain_lastdrop(chain);
351 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
353 /* retry the same chain */
359 * Safe handling of the 1->0 transition on chain. Returns a chain for
360 * recursive drop or NULL, possibly returning the same chain if the atomic
363 * Whem two chains need to be recursively dropped we use the chain
364 * we would otherwise free to placehold the additional chain. It's a bit
365 * convoluted but we can't just recurse without potentially blowing out
368 * The chain cannot be freed if it has any children.
370 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
374 hammer2_chain_lastdrop(hammer2_chain_t *chain)
378 hammer2_chain_t *parent;
379 hammer2_chain_t *rdrop;
382 * Spinlock the core and check to see if it is empty. If it is
383 * not empty we leave chain intact with refs == 0. The elements
384 * in core->rbtree are associated with other chains contemporary
385 * with ours but not with our chain directly.
387 hammer2_spin_ex(&chain->core.spin);
390 * We can't free non-stale chains with children until we are
391 * able to free the children because there might be a flush
392 * dependency. Flushes of stale children (which should also
393 * have their deleted flag set) short-cut recursive flush
394 * dependencies and can be freed here. Any flushes which run
395 * through stale children due to the flush synchronization
396 * point should have a FLUSH_* bit set in the chain and not
397 * reach lastdrop at this time.
399 * NOTE: We return (chain) on failure to retry.
401 if (chain->core.chain_count) {
402 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
403 hammer2_spin_unex(&chain->core.spin);
404 chain = NULL; /* success */
406 hammer2_spin_unex(&chain->core.spin);
410 /* no chains left under us */
413 * chain->core has no children left so no accessors can get to our
414 * chain from there. Now we have to lock the parent core to interlock
415 * remaining possible accessors that might bump chain's refs before
416 * we can safely drop chain's refs with intent to free the chain.
419 pmp = chain->pmp; /* can be NULL */
423 * Spinlock the parent and try to drop the last ref on chain.
424 * On success remove chain from its parent, otherwise return NULL.
426 * (normal core locks are top-down recursive but we define core
427 * spinlocks as bottom-up recursive, so this is safe).
429 if ((parent = chain->parent) != NULL) {
430 hammer2_spin_ex(&parent->core.spin);
431 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
432 /* 1->0 transition failed */
433 hammer2_spin_unex(&parent->core.spin);
434 hammer2_spin_unex(&chain->core.spin);
435 return(chain); /* retry */
439 * 1->0 transition successful, remove chain from its
442 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
443 RB_REMOVE(hammer2_chain_tree,
444 &parent->core.rbtree, chain);
445 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
446 --parent->core.chain_count;
447 chain->parent = NULL;
451 * If our chain was the last chain in the parent's core the
452 * core is now empty and its parent might have to be
453 * re-dropped if it has 0 refs.
455 if (parent->core.chain_count == 0) {
457 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
461 hammer2_spin_unex(&parent->core.spin);
462 parent = NULL; /* safety */
466 * Successful 1->0 transition and the chain can be destroyed now.
468 * We still have the core spinlock, and core's chain_count is 0.
469 * Any parent spinlock is gone.
471 hammer2_spin_unex(&chain->core.spin);
472 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
473 chain->core.chain_count == 0);
476 * All spin locks are gone, finish freeing stuff.
478 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
479 HAMMER2_CHAIN_MODIFIED)) == 0);
480 hammer2_chain_drop_data(chain, 1);
482 KKASSERT(chain->dio == NULL);
485 * Once chain resources are gone we can use the now dead chain
486 * structure to placehold what might otherwise require a recursive
487 * drop, because we have potentially two things to drop and can only
488 * return one directly.
490 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
491 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
493 kfree(chain, hmp->mchain);
497 * Possible chaining loop when parent re-drop needed.
503 * On either last lock release or last drop
506 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
508 /*hammer2_dev_t *hmp = chain->hmp;*/
510 switch(chain->bref.type) {
511 case HAMMER2_BREF_TYPE_VOLUME:
512 case HAMMER2_BREF_TYPE_FREEMAP:
517 KKASSERT(chain->data == NULL);
523 * Lock a referenced chain element, acquiring its data with I/O if necessary,
524 * and specify how you would like the data to be resolved.
526 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
528 * The lock is allowed to recurse, multiple locking ops will aggregate
529 * the requested resolve types. Once data is assigned it will not be
530 * removed until the last unlock.
532 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
533 * (typically used to avoid device/logical buffer
536 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
537 * the INITIAL-create state (indirect blocks only).
539 * Do not resolve data elements for DATA chains.
540 * (typically used to avoid device/logical buffer
543 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
545 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
546 * it will be locked exclusive.
548 * NOTE: Embedded elements (volume header, inodes) are always resolved
551 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
552 * element will instantiate and zero its buffer, and flush it on
555 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
556 * so as not to instantiate a device buffer, which could alias against
557 * a logical file buffer. However, if ALWAYS is specified the
558 * device buffer will be instantiated anyway.
560 * WARNING! This function blocks on I/O if data needs to be fetched. This
561 * blocking can run concurrent with other compatible lock holders
562 * who do not need data returning. The lock is not upgraded to
563 * exclusive during a data fetch, a separate bit is used to
564 * interlock I/O. However, an exclusive lock holder can still count
565 * on being interlocked against an I/O fetch managed by a shared
569 hammer2_chain_lock(hammer2_chain_t *chain, int how)
572 * Ref and lock the element. Recursive locks are allowed.
574 KKASSERT(chain->refs > 0);
575 atomic_add_int(&chain->lockcnt, 1);
578 * Get the appropriate lock.
580 if (how & HAMMER2_RESOLVE_SHARED)
581 hammer2_mtx_sh(&chain->lock);
583 hammer2_mtx_ex(&chain->lock);
586 * If we already have a valid data pointer no further action is
593 * Do we have to resolve the data?
595 switch(how & HAMMER2_RESOLVE_MASK) {
596 case HAMMER2_RESOLVE_NEVER:
598 case HAMMER2_RESOLVE_MAYBE:
599 if (chain->flags & HAMMER2_CHAIN_INITIAL)
601 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
604 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
606 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
610 case HAMMER2_RESOLVE_ALWAYS:
616 * Caller requires data
618 hammer2_chain_load_data(chain);
622 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
623 * may be of any type.
625 * Once chain->data is set it cannot be disposed of until all locks are
629 hammer2_chain_load_data(hammer2_chain_t *chain)
631 hammer2_blockref_t *bref;
637 * Degenerate case, data already present.
643 KKASSERT(hmp != NULL);
646 * Gain the IOINPROG bit, interlocked block.
652 oflags = chain->flags;
654 if (oflags & HAMMER2_CHAIN_IOINPROG) {
655 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
656 tsleep_interlock(&chain->flags, 0);
657 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
658 tsleep(&chain->flags, PINTERLOCKED,
663 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
664 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
672 * We own CHAIN_IOINPROG
674 * Degenerate case if we raced another load.
680 * We must resolve to a device buffer, either by issuing I/O or
681 * by creating a zero-fill element. We do not mark the buffer
682 * dirty when creating a zero-fill element (the hammer2_chain_modify()
683 * API must still be used to do that).
685 * The device buffer is variable-sized in powers of 2 down
686 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
687 * chunk always contains buffers of the same size. (XXX)
689 * The minimum physical IO size may be larger than the variable
695 * The getblk() optimization can only be used on newly created
696 * elements if the physical block size matches the request.
698 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
699 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
702 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
704 hammer2_adjreadcounter(&chain->bref, chain->bytes);
707 chain->error = HAMMER2_ERROR_IO;
708 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
709 (intmax_t)bref->data_off, error);
710 hammer2_io_bqrelse(&chain->dio);
716 * NOTE: A locked chain's data cannot be modified without first
717 * calling hammer2_chain_modify().
721 * Clear INITIAL. In this case we used io_new() and the buffer has
722 * been zero'd and marked dirty.
724 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
725 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
726 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
727 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
728 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
730 * check data not currently synchronized due to
731 * modification. XXX assumes data stays in the buffer
732 * cache, which might not be true (need biodep on flush
733 * to calculate crc? or simple crc?).
736 if (hammer2_chain_testcheck(chain, bdata) == 0) {
737 kprintf("chain %016jx.%02x meth=%02x "
738 "CHECK FAIL %08x (flags=%08x)\n",
739 chain->bref.data_off,
742 hammer2_icrc32(bdata, chain->bytes),
744 chain->error = HAMMER2_ERROR_CHECK;
749 * Setup the data pointer, either pointing it to an embedded data
750 * structure and copying the data from the buffer, or pointing it
753 * The buffer is not retained when copying to an embedded data
754 * structure in order to avoid potential deadlocks or recursions
755 * on the same physical buffer.
757 * WARNING! Other threads can start using the data the instant we
758 * set chain->data non-NULL.
760 switch (bref->type) {
761 case HAMMER2_BREF_TYPE_VOLUME:
762 case HAMMER2_BREF_TYPE_FREEMAP:
764 * Copy data from bp to embedded buffer
766 panic("hammer2_chain_lock: called on unresolved volume header");
768 case HAMMER2_BREF_TYPE_INODE:
769 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
770 case HAMMER2_BREF_TYPE_INDIRECT:
771 case HAMMER2_BREF_TYPE_DATA:
772 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
775 * Point data at the device buffer and leave dio intact.
777 chain->data = (void *)bdata;
782 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
789 oflags = chain->flags;
790 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
791 HAMMER2_CHAIN_IOSIGNAL);
792 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
793 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
794 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
795 wakeup(&chain->flags);
802 * Unlock and deref a chain element.
804 * On the last lock release any non-embedded data (chain->dio) will be
808 hammer2_chain_unlock(hammer2_chain_t *chain)
810 hammer2_mtx_state_t ostate;
815 * If multiple locks are present (or being attempted) on this
816 * particular chain we can just unlock, drop refs, and return.
818 * Otherwise fall-through on the 1->0 transition.
821 lockcnt = chain->lockcnt;
822 KKASSERT(lockcnt > 0);
825 if (atomic_cmpset_int(&chain->lockcnt,
826 lockcnt, lockcnt - 1)) {
827 hammer2_mtx_unlock(&chain->lock);
831 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
838 * On the 1->0 transition we upgrade the core lock (if necessary)
839 * to exclusive for terminal processing. If after upgrading we find
840 * that lockcnt is non-zero, another thread is racing us and will
841 * handle the unload for us later on, so just cleanup and return
842 * leaving the data/io intact
844 * Otherwise if lockcnt is still 0 it is possible for it to become
845 * non-zero and race, but since we hold the core->lock exclusively
846 * all that will happen is that the chain will be reloaded after we
849 ostate = hammer2_mtx_upgrade(&chain->lock);
850 if (chain->lockcnt) {
851 hammer2_mtx_unlock(&chain->lock);
856 * Shortcut the case if the data is embedded or not resolved.
858 * Do NOT NULL out chain->data (e.g. inode data), it might be
861 if (chain->dio == NULL) {
862 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
863 hammer2_chain_drop_data(chain, 0);
864 hammer2_mtx_unlock(&chain->lock);
871 if (hammer2_io_isdirty(chain->dio)) {
872 switch(chain->bref.type) {
873 case HAMMER2_BREF_TYPE_DATA:
874 counterp = &hammer2_iod_file_write;
876 case HAMMER2_BREF_TYPE_INODE:
877 counterp = &hammer2_iod_meta_write;
879 case HAMMER2_BREF_TYPE_INDIRECT:
880 counterp = &hammer2_iod_indr_write;
882 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
883 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
884 counterp = &hammer2_iod_fmap_write;
887 counterp = &hammer2_iod_volu_write;
890 *counterp += chain->bytes;
896 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
900 hammer2_io_bqrelse(&chain->dio);
901 hammer2_mtx_unlock(&chain->lock);
905 * This counts the number of live blockrefs in a block array and
906 * also calculates the point at which all remaining blockrefs are empty.
907 * This routine can only be called on a live chain (DUPLICATED flag not set).
909 * NOTE: Flag is not set until after the count is complete, allowing
910 * callers to test the flag without holding the spinlock.
912 * NOTE: If base is NULL the related chain is still in the INITIAL
913 * state and there are no blockrefs to count.
915 * NOTE: live_count may already have some counts accumulated due to
916 * creation and deletion and could even be initially negative.
919 hammer2_chain_countbrefs(hammer2_chain_t *chain,
920 hammer2_blockref_t *base, int count)
922 hammer2_spin_ex(&chain->core.spin);
923 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
925 while (--count >= 0) {
926 if (base[count].type)
929 chain->core.live_zero = count + 1;
931 if (base[count].type)
932 atomic_add_int(&chain->core.live_count,
937 chain->core.live_zero = 0;
939 /* else do not modify live_count */
940 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
942 hammer2_spin_unex(&chain->core.spin);
946 * Resize the chain's physical storage allocation in-place. This function does
947 * not adjust the data pointer and must be followed by (typically) a
948 * hammer2_chain_modify() call to copy any old data over and adjust the
951 * Chains can be resized smaller without reallocating the storage. Resizing
952 * larger will reallocate the storage. Excess or prior storage is reclaimed
953 * asynchronously at a later time.
955 * Must be passed an exclusively locked parent and chain.
957 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
958 * to avoid instantiating a device buffer that conflicts with the vnode data
959 * buffer. However, because H2 can compress or encrypt data, the chain may
960 * have a dio assigned to it in those situations, and they do not conflict.
962 * XXX return error if cannot resize.
965 hammer2_chain_resize(hammer2_inode_t *ip,
966 hammer2_chain_t *parent, hammer2_chain_t *chain,
967 hammer2_tid_t mtid, hammer2_off_t dedup_off,
968 int nradix, int flags)
977 * Only data and indirect blocks can be resized for now.
978 * (The volu root, inodes, and freemap elements use a fixed size).
980 KKASSERT(chain != &hmp->vchain);
981 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
982 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
983 KKASSERT(chain->parent == parent);
986 * Nothing to do if the element is already the proper size
988 obytes = chain->bytes;
989 nbytes = 1U << nradix;
990 if (obytes == nbytes)
994 * Make sure the old data is instantiated so we can copy it. If this
995 * is a data block, the device data may be superfluous since the data
996 * might be in a logical block, but compressed or encrypted data is
999 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1001 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1004 * Relocate the block, even if making it smaller (because different
1005 * block sizes may be in different regions).
1007 * (data blocks only, we aren't copying the storage here).
1009 hammer2_freemap_alloc(chain, nbytes);
1010 chain->bytes = nbytes;
1011 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1014 * We don't want the followup chain_modify() to try to copy data
1015 * from the old (wrong-sized) buffer. It won't know how much to
1016 * copy. This case should only occur during writes when the
1017 * originator already has the data to write in-hand.
1020 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1021 hammer2_io_brelse(&chain->dio);
1027 * Set the chain modified so its data can be changed by the caller.
1029 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1030 * is a CLC (cluster level change) field and is not updated by parent
1031 * propagation during a flush.
1033 * If the caller passes a non-zero dedup_off we assign data_off to that
1034 * instead of allocating a ne block. Caller must not modify the data already
1035 * present at the target offset.
1038 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1039 hammer2_off_t dedup_off, int flags)
1041 hammer2_blockref_t obref;
1050 obref = chain->bref;
1051 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1054 * Data is not optional for freemap chains (we must always be sure
1055 * to copy the data on COW storage allocations).
1057 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1058 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1059 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1060 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1064 * Data must be resolved if already assigned, unless explicitly
1065 * flagged otherwise.
1067 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1068 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1069 hammer2_chain_load_data(chain);
1073 * Set MODIFIED to indicate that the chain has been modified.
1074 * Set UPDATE to ensure that the blockref is updated in the parent.
1076 if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1077 (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1079 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1080 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1081 hammer2_chain_ref(chain);
1082 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1087 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1088 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1089 hammer2_chain_ref(chain);
1091 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1094 * The modification or re-modification requires an allocation and
1097 * If dedup_off is non-zero, caller already has a data offset
1098 * containing the caller's desired data. The dedup offset is
1099 * allowed to be in a partially free state and we must be sure
1100 * to reset it to a fully allocated state to force two bulkfree
1101 * passes to free it again.
1103 * XXX can a chain already be marked MODIFIED without a data
1104 * assignment? If not, assert here instead of testing the case.
1106 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1107 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1111 chain->bref.data_off = dedup_off;
1112 atomic_set_int(&chain->flags,
1113 HAMMER2_CHAIN_DEDUP);
1114 hammer2_freemap_adjust(hmp, &chain->bref,
1115 HAMMER2_FREEMAP_DORECOVER);
1117 hammer2_freemap_alloc(chain, chain->bytes);
1119 /* XXX failed allocation */
1124 * Update mirror_tid and modify_tid. modify_tid is only updated
1125 * if not passed as zero (during flushes, parent propagation passes
1128 * NOTE: chain->pmp could be the device spmp.
1130 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1132 chain->bref.modify_tid = mtid;
1135 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1136 * requires updating as well as to tell the delete code that the
1137 * chain's blockref might not exactly match (in terms of physical size
1138 * or block offset) the one in the parent's blocktable. The base key
1139 * of course will still match.
1141 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1142 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1145 * Short-cut data blocks which the caller does not need an actual
1146 * data reference to (aka OPTDATA), as long as the chain does not
1147 * already have a data pointer to the data. This generally means
1148 * that the modifications are being done via the logical buffer cache.
1149 * The INITIAL flag relates only to the device data buffer and thus
1150 * remains unchange in this situation.
1152 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1153 (flags & HAMMER2_MODIFY_OPTDATA) &&
1154 chain->data == NULL) {
1159 * Clearing the INITIAL flag (for indirect blocks) indicates that
1160 * we've processed the uninitialized storage allocation.
1162 * If this flag is already clear we are likely in a copy-on-write
1163 * situation but we have to be sure NOT to bzero the storage if
1164 * no data is present.
1166 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1167 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1174 * Instantiate data buffer and possibly execute COW operation
1176 switch(chain->bref.type) {
1177 case HAMMER2_BREF_TYPE_VOLUME:
1178 case HAMMER2_BREF_TYPE_FREEMAP:
1180 * The data is embedded, no copy-on-write operation is
1183 KKASSERT(chain->dio == NULL);
1185 case HAMMER2_BREF_TYPE_INODE:
1186 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1187 case HAMMER2_BREF_TYPE_DATA:
1188 case HAMMER2_BREF_TYPE_INDIRECT:
1189 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1191 * Perform the copy-on-write operation
1193 * zero-fill or copy-on-write depending on whether
1194 * chain->data exists or not and set the dirty state for
1195 * the new buffer. hammer2_io_new() will handle the
1198 * If a dedup_off was supplied this is an existing block
1199 * and no COW, copy, or further modification is required.
1201 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1203 if (wasinitial && dedup_off == 0) {
1204 error = hammer2_io_new(hmp, chain->bref.data_off,
1205 chain->bytes, &dio);
1207 error = hammer2_io_bread(hmp, chain->bref.data_off,
1208 chain->bytes, &dio);
1210 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1213 * If an I/O error occurs make sure callers cannot accidently
1214 * modify the old buffer's contents and corrupt the filesystem.
1217 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1219 chain->error = HAMMER2_ERROR_IO;
1220 hammer2_io_brelse(&dio);
1221 hammer2_io_brelse(&chain->dio);
1226 bdata = hammer2_io_data(dio, chain->bref.data_off);
1230 * COW (unless a dedup).
1232 KKASSERT(chain->dio != NULL);
1233 if (chain->data != (void *)bdata && dedup_off == 0) {
1234 bcopy(chain->data, bdata, chain->bytes);
1236 } else if (wasinitial == 0) {
1238 * We have a problem. We were asked to COW but
1239 * we don't have any data to COW with!
1241 panic("hammer2_chain_modify: having a COW %p\n",
1246 * Retire the old buffer, replace with the new. Dirty or
1247 * redirty the new buffer.
1249 * WARNING! The system buffer cache may have already flushed
1250 * the buffer, so we must be sure to [re]dirty it
1251 * for further modification.
1253 * If dedup_off was supplied, the caller is not
1254 * expected to make any further modification to the
1258 hammer2_io_bqrelse(&chain->dio);
1259 chain->data = (void *)bdata;
1262 hammer2_io_setdirty(dio);
1265 panic("hammer2_chain_modify: illegal non-embedded type %d",
1272 * setflush on parent indicating that the parent must recurse down
1273 * to us. Do not call on chain itself which might already have it
1277 hammer2_chain_setflush(chain->parent);
1281 * Modify the chain associated with an inode.
1284 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1285 hammer2_tid_t mtid, int flags)
1287 hammer2_inode_modify(ip);
1288 hammer2_chain_modify(chain, mtid, 0, flags);
1292 * Volume header data locks
1295 hammer2_voldata_lock(hammer2_dev_t *hmp)
1297 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1301 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1303 lockmgr(&hmp->vollk, LK_RELEASE);
1307 hammer2_voldata_modify(hammer2_dev_t *hmp)
1309 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1310 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1311 hammer2_chain_ref(&hmp->vchain);
1312 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1317 * This function returns the chain at the nearest key within the specified
1318 * range. The returned chain will be referenced but not locked.
1320 * This function will recurse through chain->rbtree as necessary and will
1321 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1322 * the iteration value is less than the current value of *key_nextp.
1324 * The caller should use (*key_nextp) to calculate the actual range of
1325 * the returned element, which will be (key_beg to *key_nextp - 1), because
1326 * there might be another element which is superior to the returned element
1329 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1330 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1331 * it will wind up being (key_end + 1).
1333 * WARNING! Must be called with child's spinlock held. Spinlock remains
1334 * held through the operation.
1336 struct hammer2_chain_find_info {
1337 hammer2_chain_t *best;
1338 hammer2_key_t key_beg;
1339 hammer2_key_t key_end;
1340 hammer2_key_t key_next;
1343 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1344 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1348 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1349 hammer2_key_t key_beg, hammer2_key_t key_end)
1351 struct hammer2_chain_find_info info;
1354 info.key_beg = key_beg;
1355 info.key_end = key_end;
1356 info.key_next = *key_nextp;
1358 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1359 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1361 *key_nextp = info.key_next;
1363 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1364 parent, key_beg, key_end, *key_nextp);
1372 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1374 struct hammer2_chain_find_info *info = data;
1375 hammer2_key_t child_beg;
1376 hammer2_key_t child_end;
1378 child_beg = child->bref.key;
1379 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1381 if (child_end < info->key_beg)
1383 if (child_beg > info->key_end)
1390 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1392 struct hammer2_chain_find_info *info = data;
1393 hammer2_chain_t *best;
1394 hammer2_key_t child_end;
1397 * WARNING! Do not discard DUPLICATED chains, it is possible that
1398 * we are catching an insertion half-way done. If a
1399 * duplicated chain turns out to be the best choice the
1400 * caller will re-check its flags after locking it.
1402 * WARNING! Layerq is scanned forwards, exact matches should keep
1403 * the existing info->best.
1405 if ((best = info->best) == NULL) {
1407 * No previous best. Assign best
1410 } else if (best->bref.key <= info->key_beg &&
1411 child->bref.key <= info->key_beg) {
1416 /*info->best = child;*/
1417 } else if (child->bref.key < best->bref.key) {
1419 * Child has a nearer key and best is not flush with key_beg.
1420 * Set best to child. Truncate key_next to the old best key.
1423 if (info->key_next > best->bref.key || info->key_next == 0)
1424 info->key_next = best->bref.key;
1425 } else if (child->bref.key == best->bref.key) {
1427 * If our current best is flush with the child then this
1428 * is an illegal overlap.
1430 * key_next will automatically be limited to the smaller of
1431 * the two end-points.
1437 * Keep the current best but truncate key_next to the child's
1440 * key_next will also automatically be limited to the smaller
1441 * of the two end-points (probably not necessary for this case
1442 * but we do it anyway).
1444 if (info->key_next > child->bref.key || info->key_next == 0)
1445 info->key_next = child->bref.key;
1449 * Always truncate key_next based on child's end-of-range.
1451 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1452 if (child_end && (info->key_next > child_end || info->key_next == 0))
1453 info->key_next = child_end;
1459 * Retrieve the specified chain from a media blockref, creating the
1460 * in-memory chain structure which reflects it.
1462 * To handle insertion races pass the INSERT_RACE flag along with the
1463 * generation number of the core. NULL will be returned if the generation
1464 * number changes before we have a chance to insert the chain. Insert
1465 * races can occur because the parent might be held shared.
1467 * Caller must hold the parent locked shared or exclusive since we may
1468 * need the parent's bref array to find our block.
1470 * WARNING! chain->pmp is always set to NULL for any chain representing
1471 * part of the super-root topology.
1474 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1475 hammer2_blockref_t *bref)
1477 hammer2_dev_t *hmp = parent->hmp;
1478 hammer2_chain_t *chain;
1482 * Allocate a chain structure representing the existing media
1483 * entry. Resulting chain has one ref and is not locked.
1485 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1486 chain = hammer2_chain_alloc(hmp, NULL, bref);
1488 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1489 /* ref'd chain returned */
1492 * Flag that the chain is in the parent's blockmap so delete/flush
1493 * knows what to do with it.
1495 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1498 * Link the chain into its parent. A spinlock is required to safely
1499 * access the RBTREE, and it is possible to collide with another
1500 * hammer2_chain_get() operation because the caller might only hold
1501 * a shared lock on the parent.
1503 KKASSERT(parent->refs > 0);
1504 error = hammer2_chain_insert(parent, chain,
1505 HAMMER2_CHAIN_INSERT_SPIN |
1506 HAMMER2_CHAIN_INSERT_RACE,
1509 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1510 kprintf("chain %p get race\n", chain);
1511 hammer2_chain_drop(chain);
1514 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1518 * Return our new chain referenced but not locked, or NULL if
1525 * Lookup initialization/completion API
1528 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1530 hammer2_chain_ref(parent);
1531 if (flags & HAMMER2_LOOKUP_SHARED) {
1532 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1533 HAMMER2_RESOLVE_SHARED);
1535 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1541 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1544 hammer2_chain_unlock(parent);
1545 hammer2_chain_drop(parent);
1550 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1552 hammer2_chain_t *oparent;
1553 hammer2_chain_t *nparent;
1556 * Be careful of order, oparent must be unlocked before nparent
1557 * is locked below to avoid a deadlock.
1560 hammer2_spin_ex(&oparent->core.spin);
1561 nparent = oparent->parent;
1562 hammer2_chain_ref(nparent);
1563 hammer2_spin_unex(&oparent->core.spin);
1565 hammer2_chain_unlock(oparent);
1566 hammer2_chain_drop(oparent);
1570 hammer2_chain_lock(nparent, how);
1577 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1578 * (*parentp) typically points to an inode but can also point to a related
1579 * indirect block and this function will recurse upwards and find the inode
1582 * (*parentp) must be exclusively locked and referenced and can be an inode
1583 * or an existing indirect block within the inode.
1585 * On return (*parentp) will be modified to point at the deepest parent chain
1586 * element encountered during the search, as a helper for an insertion or
1587 * deletion. The new (*parentp) will be locked and referenced and the old
1588 * will be unlocked and dereferenced (no change if they are both the same).
1590 * The matching chain will be returned exclusively locked. If NOLOCK is
1591 * requested the chain will be returned only referenced. Note that the
1592 * parent chain must always be locked shared or exclusive, matching the
1593 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1594 * when NOLOCK is specified but that complicates matters if *parentp must
1595 * inherit the chain.
1597 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1598 * data pointer or can otherwise be in flux.
1600 * NULL is returned if no match was found, but (*parentp) will still
1601 * potentially be adjusted.
1603 * If a fatal error occurs (typically an I/O error), a dummy chain is
1604 * returned with chain->error and error-identifying information set. This
1605 * chain will assert if you try to do anything fancy with it.
1607 * XXX Depending on where the error occurs we should allow continued iteration.
1609 * On return (*key_nextp) will point to an iterative value for key_beg.
1610 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1612 * This function will also recurse up the chain if the key is not within the
1613 * current parent's range. (*parentp) can never be set to NULL. An iteration
1614 * can simply allow (*parentp) to float inside the loop.
1616 * NOTE! chain->data is not always resolved. By default it will not be
1617 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1618 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1619 * BREF_TYPE_DATA as the device buffer can alias the logical file
1623 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1624 hammer2_key_t key_beg, hammer2_key_t key_end,
1625 int *cache_indexp, int flags)
1628 hammer2_chain_t *parent;
1629 hammer2_chain_t *chain;
1630 hammer2_blockref_t *base;
1631 hammer2_blockref_t *bref;
1632 hammer2_blockref_t bcopy;
1633 hammer2_key_t scan_beg;
1634 hammer2_key_t scan_end;
1636 int how_always = HAMMER2_RESOLVE_ALWAYS;
1637 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1640 int maxloops = 300000;
1642 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1643 how_maybe = how_always;
1644 how = HAMMER2_RESOLVE_ALWAYS;
1645 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1646 how = HAMMER2_RESOLVE_NEVER;
1648 how = HAMMER2_RESOLVE_MAYBE;
1650 if (flags & HAMMER2_LOOKUP_SHARED) {
1651 how_maybe |= HAMMER2_RESOLVE_SHARED;
1652 how_always |= HAMMER2_RESOLVE_SHARED;
1653 how |= HAMMER2_RESOLVE_SHARED;
1657 * Recurse (*parentp) upward if necessary until the parent completely
1658 * encloses the key range or we hit the inode.
1660 * This function handles races against the flusher doing a delete-
1661 * duplicate above us and re-homes the parent to the duplicate in
1662 * that case, otherwise we'd wind up recursing down a stale chain.
1667 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1668 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1669 scan_beg = parent->bref.key;
1670 scan_end = scan_beg +
1671 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1672 if (key_beg >= scan_beg && key_end <= scan_end)
1674 parent = hammer2_chain_getparent(parentp, how_maybe);
1678 if (--maxloops == 0)
1679 panic("hammer2_chain_lookup: maxloops");
1681 * Locate the blockref array. Currently we do a fully associative
1682 * search through the array.
1684 switch(parent->bref.type) {
1685 case HAMMER2_BREF_TYPE_INODE:
1687 * Special shortcut for embedded data returns the inode
1688 * itself. Callers must detect this condition and access
1689 * the embedded data (the strategy code does this for us).
1691 * This is only applicable to regular files and softlinks.
1693 if (parent->data->ipdata.meta.op_flags &
1694 HAMMER2_OPFLAG_DIRECTDATA) {
1695 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1697 *key_nextp = key_end + 1;
1700 hammer2_chain_ref(parent);
1701 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1702 hammer2_chain_lock(parent, how_always);
1703 *key_nextp = key_end + 1;
1706 base = &parent->data->ipdata.u.blockset.blockref[0];
1707 count = HAMMER2_SET_COUNT;
1709 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1710 case HAMMER2_BREF_TYPE_INDIRECT:
1712 * Handle MATCHIND on the parent
1714 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1715 scan_beg = parent->bref.key;
1716 scan_end = scan_beg +
1717 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1718 if (key_beg == scan_beg && key_end == scan_end) {
1720 hammer2_chain_ref(chain);
1721 hammer2_chain_lock(chain, how_maybe);
1722 *key_nextp = scan_end + 1;
1727 * Optimize indirect blocks in the INITIAL state to avoid
1730 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1733 if (parent->data == NULL)
1734 panic("parent->data is NULL");
1735 base = &parent->data->npdata[0];
1737 count = parent->bytes / sizeof(hammer2_blockref_t);
1739 case HAMMER2_BREF_TYPE_VOLUME:
1740 base = &parent->data->voldata.sroot_blockset.blockref[0];
1741 count = HAMMER2_SET_COUNT;
1743 case HAMMER2_BREF_TYPE_FREEMAP:
1744 base = &parent->data->blkset.blockref[0];
1745 count = HAMMER2_SET_COUNT;
1748 kprintf("hammer2_chain_lookup: unrecognized "
1749 "blockref(B) type: %d",
1752 tsleep(&base, 0, "dead", 0);
1753 panic("hammer2_chain_lookup: unrecognized "
1754 "blockref(B) type: %d",
1756 base = NULL; /* safety */
1757 count = 0; /* safety */
1761 * Merged scan to find next candidate.
1763 * hammer2_base_*() functions require the parent->core.live_* fields
1764 * to be synchronized.
1766 * We need to hold the spinlock to access the block array and RB tree
1767 * and to interlock chain creation.
1769 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1770 hammer2_chain_countbrefs(parent, base, count);
1775 hammer2_spin_ex(&parent->core.spin);
1776 chain = hammer2_combined_find(parent, base, count,
1777 cache_indexp, key_nextp,
1780 generation = parent->core.generation;
1783 * Exhausted parent chain, iterate.
1786 hammer2_spin_unex(&parent->core.spin);
1787 if (key_beg == key_end) /* short cut single-key case */
1791 * Stop if we reached the end of the iteration.
1793 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1794 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1799 * Calculate next key, stop if we reached the end of the
1800 * iteration, otherwise go up one level and loop.
1802 key_beg = parent->bref.key +
1803 ((hammer2_key_t)1 << parent->bref.keybits);
1804 if (key_beg == 0 || key_beg > key_end)
1806 parent = hammer2_chain_getparent(parentp, how_maybe);
1811 * Selected from blockref or in-memory chain.
1813 if (chain == NULL) {
1815 hammer2_spin_unex(&parent->core.spin);
1816 chain = hammer2_chain_get(parent, generation,
1818 if (chain == NULL) {
1819 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1820 parent, key_beg, key_end);
1823 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1824 hammer2_chain_drop(chain);
1828 hammer2_chain_ref(chain);
1829 hammer2_spin_unex(&parent->core.spin);
1833 * chain is referenced but not locked. We must lock the chain
1834 * to obtain definitive DUPLICATED/DELETED state
1836 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1837 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1838 hammer2_chain_lock(chain, how_maybe);
1840 hammer2_chain_lock(chain, how);
1844 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1846 * NOTE: Chain's key range is not relevant as there might be
1847 * one-offs within the range that are not deleted.
1849 * NOTE: Lookups can race delete-duplicate because
1850 * delete-duplicate does not lock the parent's core
1851 * (they just use the spinlock on the core). We must
1852 * check for races by comparing the DUPLICATED flag before
1853 * releasing the spinlock with the flag after locking the
1856 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1857 hammer2_chain_unlock(chain);
1858 hammer2_chain_drop(chain);
1859 key_beg = *key_nextp;
1860 if (key_beg == 0 || key_beg > key_end)
1866 * If the chain element is an indirect block it becomes the new
1867 * parent and we loop on it. We must maintain our top-down locks
1868 * to prevent the flusher from interfering (i.e. doing a
1869 * delete-duplicate and leaving us recursing down a deleted chain).
1871 * The parent always has to be locked with at least RESOLVE_MAYBE
1872 * so we can access its data. It might need a fixup if the caller
1873 * passed incompatible flags. Be careful not to cause a deadlock
1874 * as a data-load requires an exclusive lock.
1876 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1877 * range is within the requested key range we return the indirect
1878 * block and do NOT loop. This is usually only used to acquire
1881 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1882 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1883 hammer2_chain_unlock(parent);
1884 hammer2_chain_drop(parent);
1885 *parentp = parent = chain;
1890 * All done, return the chain.
1892 * If the caller does not want a locked chain, replace the lock with
1893 * a ref. Perhaps this can eventually be optimized to not obtain the
1894 * lock in the first place for situations where the data does not
1895 * need to be resolved.
1898 if (flags & HAMMER2_LOOKUP_NOLOCK)
1899 hammer2_chain_unlock(chain);
1906 * After having issued a lookup we can iterate all matching keys.
1908 * If chain is non-NULL we continue the iteration from just after it's index.
1910 * If chain is NULL we assume the parent was exhausted and continue the
1911 * iteration at the next parent.
1913 * If a fatal error occurs (typically an I/O error), a dummy chain is
1914 * returned with chain->error and error-identifying information set. This
1915 * chain will assert if you try to do anything fancy with it.
1917 * XXX Depending on where the error occurs we should allow continued iteration.
1919 * parent must be locked on entry and remains locked throughout. chain's
1920 * lock status must match flags. Chain is always at least referenced.
1922 * WARNING! The MATCHIND flag does not apply to this function.
1925 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1926 hammer2_key_t *key_nextp,
1927 hammer2_key_t key_beg, hammer2_key_t key_end,
1928 int *cache_indexp, int flags)
1930 hammer2_chain_t *parent;
1934 * Calculate locking flags for upward recursion.
1936 how_maybe = HAMMER2_RESOLVE_MAYBE;
1937 if (flags & HAMMER2_LOOKUP_SHARED)
1938 how_maybe |= HAMMER2_RESOLVE_SHARED;
1943 * Calculate the next index and recalculate the parent if necessary.
1946 key_beg = chain->bref.key +
1947 ((hammer2_key_t)1 << chain->bref.keybits);
1948 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1949 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1950 hammer2_chain_unlock(chain);
1952 hammer2_chain_drop(chain);
1955 * chain invalid past this point, but we can still do a
1956 * pointer comparison w/parent.
1958 * Any scan where the lookup returned degenerate data embedded
1959 * in the inode has an invalid index and must terminate.
1961 if (chain == parent)
1963 if (key_beg == 0 || key_beg > key_end)
1966 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1967 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1969 * We reached the end of the iteration.
1974 * Continue iteration with next parent unless the current
1975 * parent covers the range.
1977 key_beg = parent->bref.key +
1978 ((hammer2_key_t)1 << parent->bref.keybits);
1979 if (key_beg == 0 || key_beg > key_end)
1981 parent = hammer2_chain_getparent(parentp, how_maybe);
1987 return (hammer2_chain_lookup(parentp, key_nextp,
1989 cache_indexp, flags));
1993 * The raw scan function is similar to lookup/next but does not seek to a key.
1994 * Blockrefs are iterated via first_bref = (parent, NULL) and
1995 * next_chain = (parent, bref).
1997 * The passed-in parent must be locked and its data resolved. The function
1998 * nominally returns a locked and referenced *chainp != NULL for chains
1999 * the caller might need to recurse on (and will dipose of any *chainp passed
2000 * in). The caller must check the chain->bref.type either way.
2002 * *chainp is not set for leaf elements.
2004 * This function takes a pointer to a stack-based bref structure whos
2005 * contents is updated for each iteration. The same pointer is returned,
2006 * or NULL when the iteration is complete. *firstp must be set to 1 for
2007 * the first ieration. This function will set it to 0.
2009 hammer2_blockref_t *
2010 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2011 hammer2_blockref_t *bref, int *firstp,
2012 int *cache_indexp, int flags)
2015 hammer2_blockref_t *base;
2016 hammer2_blockref_t *bref_ptr;
2018 hammer2_key_t next_key;
2019 hammer2_chain_t *chain = NULL;
2021 int how_always = HAMMER2_RESOLVE_ALWAYS;
2022 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2025 int maxloops = 300000;
2030 * Scan flags borrowed from lookup.
2032 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2033 how_maybe = how_always;
2034 how = HAMMER2_RESOLVE_ALWAYS;
2035 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2036 how = HAMMER2_RESOLVE_NEVER;
2038 how = HAMMER2_RESOLVE_MAYBE;
2040 if (flags & HAMMER2_LOOKUP_SHARED) {
2041 how_maybe |= HAMMER2_RESOLVE_SHARED;
2042 how_always |= HAMMER2_RESOLVE_SHARED;
2043 how |= HAMMER2_RESOLVE_SHARED;
2047 * Calculate key to locate first/next element, unlocking the previous
2048 * element as we go. Be careful, the key calculation can overflow.
2050 * (also reset bref to NULL)
2056 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2057 if ((chain = *chainp) != NULL) {
2059 hammer2_chain_unlock(chain);
2060 hammer2_chain_drop(chain);
2070 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2071 if (--maxloops == 0)
2072 panic("hammer2_chain_scan: maxloops");
2074 * Locate the blockref array. Currently we do a fully associative
2075 * search through the array.
2077 switch(parent->bref.type) {
2078 case HAMMER2_BREF_TYPE_INODE:
2080 * An inode with embedded data has no sub-chains.
2082 * WARNING! Bulk scan code may pass a static chain marked
2083 * as BREF_TYPE_INODE with a copy of the volume
2084 * root blockset to snapshot the volume.
2086 if (parent->data->ipdata.meta.op_flags &
2087 HAMMER2_OPFLAG_DIRECTDATA) {
2091 base = &parent->data->ipdata.u.blockset.blockref[0];
2092 count = HAMMER2_SET_COUNT;
2094 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2095 case HAMMER2_BREF_TYPE_INDIRECT:
2097 * Optimize indirect blocks in the INITIAL state to avoid
2100 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2103 if (parent->data == NULL)
2104 panic("parent->data is NULL");
2105 base = &parent->data->npdata[0];
2107 count = parent->bytes / sizeof(hammer2_blockref_t);
2109 case HAMMER2_BREF_TYPE_VOLUME:
2110 base = &parent->data->voldata.sroot_blockset.blockref[0];
2111 count = HAMMER2_SET_COUNT;
2113 case HAMMER2_BREF_TYPE_FREEMAP:
2114 base = &parent->data->blkset.blockref[0];
2115 count = HAMMER2_SET_COUNT;
2118 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2120 base = NULL; /* safety */
2121 count = 0; /* safety */
2125 * Merged scan to find next candidate.
2127 * hammer2_base_*() functions require the parent->core.live_* fields
2128 * to be synchronized.
2130 * We need to hold the spinlock to access the block array and RB tree
2131 * and to interlock chain creation.
2133 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2134 hammer2_chain_countbrefs(parent, base, count);
2138 hammer2_spin_ex(&parent->core.spin);
2139 chain = hammer2_combined_find(parent, base, count,
2140 cache_indexp, &next_key,
2141 key, HAMMER2_KEY_MAX,
2143 generation = parent->core.generation;
2146 * Exhausted parent chain, we're done.
2148 if (bref_ptr == NULL) {
2149 hammer2_spin_unex(&parent->core.spin);
2150 KKASSERT(chain == NULL);
2156 * Copy into the supplied stack-based blockref.
2161 * Selected from blockref or in-memory chain.
2163 if (chain == NULL) {
2164 switch(bref->type) {
2165 case HAMMER2_BREF_TYPE_INODE:
2166 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2167 case HAMMER2_BREF_TYPE_INDIRECT:
2168 case HAMMER2_BREF_TYPE_VOLUME:
2169 case HAMMER2_BREF_TYPE_FREEMAP:
2171 * Recursion, always get the chain
2173 hammer2_spin_unex(&parent->core.spin);
2174 chain = hammer2_chain_get(parent, generation, bref);
2175 if (chain == NULL) {
2176 kprintf("retry scan parent %p keys %016jx\n",
2180 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2181 hammer2_chain_drop(chain);
2188 * No recursion, do not waste time instantiating
2189 * a chain, just iterate using the bref.
2191 hammer2_spin_unex(&parent->core.spin);
2196 * Recursion or not we need the chain in order to supply
2199 hammer2_chain_ref(chain);
2200 hammer2_spin_unex(&parent->core.spin);
2204 * chain is referenced but not locked. We must lock the chain
2205 * to obtain definitive DUPLICATED/DELETED state
2208 hammer2_chain_lock(chain, how);
2211 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2213 * NOTE: chain's key range is not relevant as there might be
2214 * one-offs within the range that are not deleted.
2216 * NOTE: XXX this could create problems with scans used in
2217 * situations other than mount-time recovery.
2219 * NOTE: Lookups can race delete-duplicate because
2220 * delete-duplicate does not lock the parent's core
2221 * (they just use the spinlock on the core). We must
2222 * check for races by comparing the DUPLICATED flag before
2223 * releasing the spinlock with the flag after locking the
2226 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2227 hammer2_chain_unlock(chain);
2228 hammer2_chain_drop(chain);
2241 * All done, return the bref or NULL, supply chain if necessary.
2249 * Create and return a new hammer2 system memory structure of the specified
2250 * key, type and size and insert it under (*parentp). This is a full
2251 * insertion, based on the supplied key/keybits, and may involve creating
2252 * indirect blocks and moving other chains around via delete/duplicate.
2254 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2255 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2256 * FULL. This typically means that the caller is creating the chain after
2257 * doing a hammer2_chain_lookup().
2259 * (*parentp) must be exclusive locked and may be replaced on return
2260 * depending on how much work the function had to do.
2262 * (*parentp) must not be errored or this function will assert.
2264 * (*chainp) usually starts out NULL and returns the newly created chain,
2265 * but if the caller desires the caller may allocate a disconnected chain
2266 * and pass it in instead.
2268 * This function should NOT be used to insert INDIRECT blocks. It is
2269 * typically used to create/insert inodes and data blocks.
2271 * Caller must pass-in an exclusively locked parent the new chain is to
2272 * be inserted under, and optionally pass-in a disconnected, exclusively
2273 * locked chain to insert (else we create a new chain). The function will
2274 * adjust (*parentp) as necessary, create or connect the chain, and
2275 * return an exclusively locked chain in *chainp.
2277 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2278 * and will be reassigned.
2281 hammer2_chain_create(hammer2_chain_t **parentp,
2282 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2283 hammer2_key_t key, int keybits, int type, size_t bytes,
2284 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2287 hammer2_chain_t *chain;
2288 hammer2_chain_t *parent;
2289 hammer2_blockref_t *base;
2290 hammer2_blockref_t dummy;
2294 int maxloops = 300000;
2297 * Topology may be crossing a PFS boundary.
2300 KKASSERT(hammer2_mtx_owned(&parent->lock));
2301 KKASSERT(parent->error == 0);
2305 if (chain == NULL) {
2307 * First allocate media space and construct the dummy bref,
2308 * then allocate the in-memory chain structure. Set the
2309 * INITIAL flag for fresh chains which do not have embedded
2312 * XXX for now set the check mode of the child based on
2313 * the parent or, if the parent is an inode, the
2314 * specification in the inode.
2316 bzero(&dummy, sizeof(dummy));
2319 dummy.keybits = keybits;
2320 dummy.data_off = hammer2_getradix(bytes);
2321 dummy.methods = parent->bref.methods;
2322 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2324 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2325 dummy.methods |= HAMMER2_ENC_CHECK(
2326 parent->data->ipdata.meta.check_algo);
2329 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2332 * Lock the chain manually, chain_lock will load the chain
2333 * which we do NOT want to do. (note: chain->refs is set
2334 * to 1 by chain_alloc() for us, but lockcnt is not).
2337 hammer2_mtx_ex(&chain->lock);
2341 * Set INITIAL to optimize I/O. The flag will generally be
2342 * processed when we call hammer2_chain_modify().
2344 * Recalculate bytes to reflect the actual media block
2347 bytes = (hammer2_off_t)1 <<
2348 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2349 chain->bytes = bytes;
2352 case HAMMER2_BREF_TYPE_VOLUME:
2353 case HAMMER2_BREF_TYPE_FREEMAP:
2354 panic("hammer2_chain_create: called with volume type");
2356 case HAMMER2_BREF_TYPE_INDIRECT:
2357 panic("hammer2_chain_create: cannot be used to"
2358 "create indirect block");
2360 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2361 panic("hammer2_chain_create: cannot be used to"
2362 "create freemap root or node");
2364 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2365 KKASSERT(bytes == sizeof(chain->data->bmdata));
2367 case HAMMER2_BREF_TYPE_INODE:
2368 case HAMMER2_BREF_TYPE_DATA:
2371 * leave chain->data NULL, set INITIAL
2373 KKASSERT(chain->data == NULL);
2374 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2379 * We are reattaching a previously deleted chain, possibly
2380 * under a new parent and possibly with a new key/keybits.
2381 * The chain does not have to be in a modified state. The
2382 * UPDATE flag will be set later on in this routine.
2384 * Do NOT mess with the current state of the INITIAL flag.
2386 chain->bref.key = key;
2387 chain->bref.keybits = keybits;
2388 if (chain->flags & HAMMER2_CHAIN_DELETED)
2389 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2390 KKASSERT(chain->parent == NULL);
2392 if (flags & HAMMER2_INSERT_PFSROOT)
2393 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2395 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2398 * Calculate how many entries we have in the blockref array and
2399 * determine if an indirect block is required.
2402 if (--maxloops == 0)
2403 panic("hammer2_chain_create: maxloops");
2405 switch(parent->bref.type) {
2406 case HAMMER2_BREF_TYPE_INODE:
2407 KKASSERT((parent->data->ipdata.meta.op_flags &
2408 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2409 KKASSERT(parent->data != NULL);
2410 base = &parent->data->ipdata.u.blockset.blockref[0];
2411 count = HAMMER2_SET_COUNT;
2413 case HAMMER2_BREF_TYPE_INDIRECT:
2414 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2415 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2418 base = &parent->data->npdata[0];
2419 count = parent->bytes / sizeof(hammer2_blockref_t);
2421 case HAMMER2_BREF_TYPE_VOLUME:
2422 KKASSERT(parent->data != NULL);
2423 base = &parent->data->voldata.sroot_blockset.blockref[0];
2424 count = HAMMER2_SET_COUNT;
2426 case HAMMER2_BREF_TYPE_FREEMAP:
2427 KKASSERT(parent->data != NULL);
2428 base = &parent->data->blkset.blockref[0];
2429 count = HAMMER2_SET_COUNT;
2432 panic("hammer2_chain_create: unrecognized blockref type: %d",
2440 * Make sure we've counted the brefs
2442 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2443 hammer2_chain_countbrefs(parent, base, count);
2445 KKASSERT(parent->core.live_count >= 0 &&
2446 parent->core.live_count <= count);
2449 * If no free blockref could be found we must create an indirect
2450 * block and move a number of blockrefs into it. With the parent
2451 * locked we can safely lock each child in order to delete+duplicate
2452 * it without causing a deadlock.
2454 * This may return the new indirect block or the old parent depending
2455 * on where the key falls. NULL is returned on error.
2457 if (parent->core.live_count == count) {
2458 hammer2_chain_t *nparent;
2460 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2461 mtid, type, &error);
2462 if (nparent == NULL) {
2464 hammer2_chain_drop(chain);
2468 if (parent != nparent) {
2469 hammer2_chain_unlock(parent);
2470 hammer2_chain_drop(parent);
2471 parent = *parentp = nparent;
2477 * Link the chain into its parent.
2479 if (chain->parent != NULL)
2480 panic("hammer2: hammer2_chain_create: chain already connected");
2481 KKASSERT(chain->parent == NULL);
2482 hammer2_chain_insert(parent, chain,
2483 HAMMER2_CHAIN_INSERT_SPIN |
2484 HAMMER2_CHAIN_INSERT_LIVE,
2489 * Mark the newly created chain modified. This will cause
2490 * UPDATE to be set and process the INITIAL flag.
2492 * Device buffers are not instantiated for DATA elements
2493 * as these are handled by logical buffers.
2495 * Indirect and freemap node indirect blocks are handled
2496 * by hammer2_chain_create_indirect() and not by this
2499 * Data for all other bref types is expected to be
2500 * instantiated (INODE, LEAF).
2502 switch(chain->bref.type) {
2503 case HAMMER2_BREF_TYPE_DATA:
2504 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2505 case HAMMER2_BREF_TYPE_INODE:
2506 hammer2_chain_modify(chain, mtid, dedup_off,
2507 HAMMER2_MODIFY_OPTDATA);
2511 * Remaining types are not supported by this function.
2512 * In particular, INDIRECT and LEAF_NODE types are
2513 * handled by create_indirect().
2515 panic("hammer2_chain_create: bad type: %d",
2522 * When reconnecting a chain we must set UPDATE and
2523 * setflush so the flush recognizes that it must update
2524 * the bref in the parent.
2526 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2527 hammer2_chain_ref(chain);
2528 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2533 * We must setflush(parent) to ensure that it recurses through to
2534 * chain. setflush(chain) might not work because ONFLUSH is possibly
2535 * already set in the chain (so it won't recurse up to set it in the
2538 hammer2_chain_setflush(parent);
2547 * Move the chain from its old parent to a new parent. The chain must have
2548 * already been deleted or already disconnected (or never associated) with
2549 * a parent. The chain is reassociated with the new parent and the deleted
2550 * flag will be cleared (no longer deleted). The chain's modification state
2553 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2554 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2555 * FULL. This typically means that the caller is creating the chain after
2556 * doing a hammer2_chain_lookup().
2558 * A non-NULL bref is typically passed when key and keybits must be overridden.
2559 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2560 * from a passed-in bref and uses the old chain's bref for everything else.
2562 * Neither (parent) or (chain) can be errored.
2564 * If (parent) is non-NULL then the new duplicated chain is inserted under
2567 * If (parent) is NULL then the newly duplicated chain is not inserted
2568 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2569 * passing into hammer2_chain_create() after this function returns).
2571 * WARNING! This function calls create which means it can insert indirect
2572 * blocks. This can cause other unrelated chains in the parent to
2573 * be moved to a newly inserted indirect block in addition to the
2577 hammer2_chain_rename(hammer2_blockref_t *bref,
2578 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2579 hammer2_tid_t mtid, int flags)
2582 hammer2_chain_t *parent;
2586 * WARNING! We should never resolve DATA to device buffers
2587 * (XXX allow it if the caller did?), and since
2588 * we currently do not have the logical buffer cache
2589 * buffer in-hand to fix its cached physical offset
2590 * we also force the modify code to not COW it. XXX
2593 KKASSERT(chain->parent == NULL);
2594 KKASSERT(chain->error == 0);
2597 * Now create a duplicate of the chain structure, associating
2598 * it with the same core, making it the same size, pointing it
2599 * to the same bref (the same media block).
2602 bref = &chain->bref;
2603 bytes = (hammer2_off_t)1 <<
2604 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2607 * If parent is not NULL the duplicated chain will be entered under
2608 * the parent and the UPDATE bit set to tell flush to update
2611 * We must setflush(parent) to ensure that it recurses through to
2612 * chain. setflush(chain) might not work because ONFLUSH is possibly
2613 * already set in the chain (so it won't recurse up to set it in the
2616 * Having both chains locked is extremely important for atomicy.
2618 if (parentp && (parent = *parentp) != NULL) {
2619 KKASSERT(hammer2_mtx_owned(&parent->lock));
2620 KKASSERT(parent->refs > 0);
2621 KKASSERT(parent->error == 0);
2623 hammer2_chain_create(parentp, &chain, chain->pmp,
2624 bref->key, bref->keybits, bref->type,
2625 chain->bytes, mtid, 0, flags);
2626 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2627 hammer2_chain_setflush(*parentp);
2632 * Helper function for deleting chains.
2634 * The chain is removed from the live view (the RBTREE) as well as the parent's
2635 * blockmap. Both chain and its parent must be locked.
2637 * parent may not be errored. chain can be errored.
2640 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2641 hammer2_tid_t mtid, int flags)
2645 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2646 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2647 KKASSERT(chain->parent == parent);
2650 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2652 * Chain is blockmapped, so there must be a parent.
2653 * Atomically remove the chain from the parent and remove
2654 * the blockmap entry.
2656 hammer2_blockref_t *base;
2659 KKASSERT(parent != NULL);
2660 KKASSERT(parent->error == 0);
2661 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2662 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2665 * Calculate blockmap pointer
2667 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2668 hammer2_spin_ex(&parent->core.spin);
2670 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2671 atomic_add_int(&parent->core.live_count, -1);
2672 ++parent->core.generation;
2673 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2674 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2675 --parent->core.chain_count;
2676 chain->parent = NULL;
2678 switch(parent->bref.type) {
2679 case HAMMER2_BREF_TYPE_INODE:
2681 * Access the inode's block array. However, there
2682 * is no block array if the inode is flagged
2683 * DIRECTDATA. The DIRECTDATA case typicaly only
2684 * occurs when a hardlink has been shifted up the
2685 * tree and the original inode gets replaced with
2686 * an OBJTYPE_HARDLINK placeholding inode.
2689 (parent->data->ipdata.meta.op_flags &
2690 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2692 &parent->data->ipdata.u.blockset.blockref[0];
2696 count = HAMMER2_SET_COUNT;
2698 case HAMMER2_BREF_TYPE_INDIRECT:
2699 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2701 base = &parent->data->npdata[0];
2704 count = parent->bytes / sizeof(hammer2_blockref_t);
2706 case HAMMER2_BREF_TYPE_VOLUME:
2707 base = &parent->data->voldata.
2708 sroot_blockset.blockref[0];
2709 count = HAMMER2_SET_COUNT;
2711 case HAMMER2_BREF_TYPE_FREEMAP:
2712 base = &parent->data->blkset.blockref[0];
2713 count = HAMMER2_SET_COUNT;
2718 panic("hammer2_flush_pass2: "
2719 "unrecognized blockref type: %d",
2724 * delete blockmapped chain from its parent.
2726 * The parent is not affected by any statistics in chain
2727 * which are pending synchronization. That is, there is
2728 * nothing to undo in the parent since they have not yet
2729 * been incorporated into the parent.
2731 * The parent is affected by statistics stored in inodes.
2732 * Those have already been synchronized, so they must be
2733 * undone. XXX split update possible w/delete in middle?
2736 int cache_index = -1;
2737 hammer2_base_delete(parent, base, count,
2738 &cache_index, chain);
2740 hammer2_spin_unex(&parent->core.spin);
2741 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2743 * Chain is not blockmapped but a parent is present.
2744 * Atomically remove the chain from the parent. There is
2745 * no blockmap entry to remove.
2747 * Because chain was associated with a parent but not
2748 * synchronized, the chain's *_count_up fields contain
2749 * inode adjustment statistics which must be undone.
2751 hammer2_spin_ex(&parent->core.spin);
2752 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2753 atomic_add_int(&parent->core.live_count, -1);
2754 ++parent->core.generation;
2755 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2756 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2757 --parent->core.chain_count;
2758 chain->parent = NULL;
2759 hammer2_spin_unex(&parent->core.spin);
2762 * Chain is not blockmapped and has no parent. This
2763 * is a degenerate case.
2765 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2770 * Create an indirect block that covers one or more of the elements in the
2771 * current parent. Either returns the existing parent with no locking or
2772 * ref changes or returns the new indirect block locked and referenced
2773 * and leaving the original parent lock/ref intact as well.
2775 * If an error occurs, NULL is returned and *errorp is set to the error.
2777 * The returned chain depends on where the specified key falls.
2779 * The key/keybits for the indirect mode only needs to follow three rules:
2781 * (1) That all elements underneath it fit within its key space and
2783 * (2) That all elements outside it are outside its key space.
2785 * (3) When creating the new indirect block any elements in the current
2786 * parent that fit within the new indirect block's keyspace must be
2787 * moved into the new indirect block.
2789 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2790 * keyspace the the current parent, but lookup/iteration rules will
2791 * ensure (and must ensure) that rule (2) for all parents leading up
2792 * to the nearest inode or the root volume header is adhered to. This
2793 * is accomplished by always recursing through matching keyspaces in
2794 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2796 * The current implementation calculates the current worst-case keyspace by
2797 * iterating the current parent and then divides it into two halves, choosing
2798 * whichever half has the most elements (not necessarily the half containing
2799 * the requested key).
2801 * We can also opt to use the half with the least number of elements. This
2802 * causes lower-numbered keys (aka logical file offsets) to recurse through
2803 * fewer indirect blocks and higher-numbered keys to recurse through more.
2804 * This also has the risk of not moving enough elements to the new indirect
2805 * block and being forced to create several indirect blocks before the element
2808 * Must be called with an exclusively locked parent.
2810 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2811 hammer2_key_t *keyp, int keybits,
2812 hammer2_blockref_t *base, int count);
2813 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2814 hammer2_key_t *keyp, int keybits,
2815 hammer2_blockref_t *base, int count);
2818 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2819 hammer2_key_t create_key, int create_bits,
2820 hammer2_tid_t mtid, int for_type, int *errorp)
2823 hammer2_blockref_t *base;
2824 hammer2_blockref_t *bref;
2825 hammer2_blockref_t bcopy;
2826 hammer2_chain_t *chain;
2827 hammer2_chain_t *ichain;
2828 hammer2_chain_t dummy;
2829 hammer2_key_t key = create_key;
2830 hammer2_key_t key_beg;
2831 hammer2_key_t key_end;
2832 hammer2_key_t key_next;
2833 int keybits = create_bits;
2840 int maxloops = 300000;
2843 * Calculate the base blockref pointer or NULL if the chain
2844 * is known to be empty. We need to calculate the array count
2845 * for RB lookups either way.
2849 KKASSERT(hammer2_mtx_owned(&parent->lock));
2851 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2852 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2855 switch(parent->bref.type) {
2856 case HAMMER2_BREF_TYPE_INODE:
2857 count = HAMMER2_SET_COUNT;
2859 case HAMMER2_BREF_TYPE_INDIRECT:
2860 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2861 count = parent->bytes / sizeof(hammer2_blockref_t);
2863 case HAMMER2_BREF_TYPE_VOLUME:
2864 count = HAMMER2_SET_COUNT;
2866 case HAMMER2_BREF_TYPE_FREEMAP:
2867 count = HAMMER2_SET_COUNT;
2870 panic("hammer2_chain_create_indirect: "
2871 "unrecognized blockref type: %d",
2877 switch(parent->bref.type) {
2878 case HAMMER2_BREF_TYPE_INODE:
2879 base = &parent->data->ipdata.u.blockset.blockref[0];
2880 count = HAMMER2_SET_COUNT;
2882 case HAMMER2_BREF_TYPE_INDIRECT:
2883 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2884 base = &parent->data->npdata[0];
2885 count = parent->bytes / sizeof(hammer2_blockref_t);
2887 case HAMMER2_BREF_TYPE_VOLUME:
2888 base = &parent->data->voldata.
2889 sroot_blockset.blockref[0];
2890 count = HAMMER2_SET_COUNT;
2892 case HAMMER2_BREF_TYPE_FREEMAP:
2893 base = &parent->data->blkset.blockref[0];
2894 count = HAMMER2_SET_COUNT;
2897 panic("hammer2_chain_create_indirect: "
2898 "unrecognized blockref type: %d",
2906 * dummy used in later chain allocation (no longer used for lookups).
2908 bzero(&dummy, sizeof(dummy));
2911 * When creating an indirect block for a freemap node or leaf
2912 * the key/keybits must be fitted to static radix levels because
2913 * particular radix levels use particular reserved blocks in the
2916 * This routine calculates the key/radix of the indirect block
2917 * we need to create, and whether it is on the high-side or the
2920 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2921 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2922 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2925 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2930 * Normalize the key for the radix being represented, keeping the
2931 * high bits and throwing away the low bits.
2933 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2936 * How big should our new indirect block be? It has to be at least
2937 * as large as its parent.
2939 * The freemap uses a specific indirect block size.
2941 * The first indirect block level down from an inode typically
2942 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2944 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2945 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2946 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2947 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2948 nbytes = HAMMER2_IND_BYTES_MIN;
2950 nbytes = HAMMER2_IND_BYTES_MAX;
2952 if (nbytes < count * sizeof(hammer2_blockref_t)) {
2953 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2954 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2955 nbytes = count * sizeof(hammer2_blockref_t);
2959 * Ok, create our new indirect block
2961 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2962 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2963 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2965 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2967 dummy.bref.key = key;
2968 dummy.bref.keybits = keybits;
2969 dummy.bref.data_off = hammer2_getradix(nbytes);
2970 dummy.bref.methods = parent->bref.methods;
2972 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2973 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2974 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2975 /* ichain has one ref at this point */
2978 * We have to mark it modified to allocate its block, but use
2979 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2980 * it won't be acted upon by the flush code.
2982 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2985 * Iterate the original parent and move the matching brefs into
2986 * the new indirect block.
2988 * XXX handle flushes.
2991 key_end = HAMMER2_KEY_MAX;
2993 hammer2_spin_ex(&parent->core.spin);
2998 if (++loops > 100000) {
2999 hammer2_spin_unex(&parent->core.spin);
3000 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3001 reason, parent, base, count, key_next);
3005 * NOTE: spinlock stays intact, returned chain (if not NULL)
3006 * is not referenced or locked which means that we
3007 * cannot safely check its flagged / deletion status
3010 chain = hammer2_combined_find(parent, base, count,
3011 &cache_index, &key_next,
3014 generation = parent->core.generation;
3017 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3020 * Skip keys that are not within the key/radix of the new
3021 * indirect block. They stay in the parent.
3023 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3024 (key ^ bref->key)) != 0) {
3025 goto next_key_spinlocked;
3029 * Load the new indirect block by acquiring the related
3030 * chains (potentially from media as it might not be
3031 * in-memory). Then move it to the new parent (ichain)
3032 * via DELETE-DUPLICATE.
3034 * chain is referenced but not locked. We must lock the
3035 * chain to obtain definitive DUPLICATED/DELETED state
3039 * Use chain already present in the RBTREE
3041 hammer2_chain_ref(chain);
3042 hammer2_spin_unex(&parent->core.spin);
3043 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3046 * Get chain for blockref element. _get returns NULL
3047 * on insertion race.
3050 hammer2_spin_unex(&parent->core.spin);
3051 chain = hammer2_chain_get(parent, generation, &bcopy);
3052 if (chain == NULL) {
3054 hammer2_spin_ex(&parent->core.spin);
3057 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3058 kprintf("REASON 2\n");
3060 hammer2_chain_drop(chain);
3061 hammer2_spin_ex(&parent->core.spin);
3064 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3068 * This is always live so if the chain has been deleted
3069 * we raced someone and we have to retry.
3071 * NOTE: Lookups can race delete-duplicate because
3072 * delete-duplicate does not lock the parent's core
3073 * (they just use the spinlock on the core). We must
3074 * check for races by comparing the DUPLICATED flag before
3075 * releasing the spinlock with the flag after locking the
3078 * (note reversed logic for this one)
3080 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3081 hammer2_chain_unlock(chain);
3082 hammer2_chain_drop(chain);
3087 * Shift the chain to the indirect block.
3089 * WARNING! No reason for us to load chain data, pass NOSTATS
3090 * to prevent delete/insert from trying to access
3091 * inode stats (and thus asserting if there is no
3092 * chain->data loaded).
3094 hammer2_chain_delete(parent, chain, mtid, 0);
3095 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3096 hammer2_chain_unlock(chain);
3097 hammer2_chain_drop(chain);
3098 KKASSERT(parent->refs > 0);
3101 hammer2_spin_ex(&parent->core.spin);
3102 next_key_spinlocked:
3103 if (--maxloops == 0)
3104 panic("hammer2_chain_create_indirect: maxloops");
3106 if (key_next == 0 || key_next > key_end)
3111 hammer2_spin_unex(&parent->core.spin);
3114 * Insert the new indirect block into the parent now that we've
3115 * cleared out some entries in the parent. We calculated a good
3116 * insertion index in the loop above (ichain->index).
3118 * We don't have to set UPDATE here because we mark ichain
3119 * modified down below (so the normal modified -> flush -> set-moved
3120 * sequence applies).
3122 * The insertion shouldn't race as this is a completely new block
3123 * and the parent is locked.
3125 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3126 hammer2_chain_insert(parent, ichain,
3127 HAMMER2_CHAIN_INSERT_SPIN |
3128 HAMMER2_CHAIN_INSERT_LIVE,
3132 * Make sure flushes propogate after our manual insertion.
3134 hammer2_chain_setflush(ichain);
3135 hammer2_chain_setflush(parent);
3138 * Figure out what to return.
3140 if (~(((hammer2_key_t)1 << keybits) - 1) &
3141 (create_key ^ key)) {
3143 * Key being created is outside the key range,
3144 * return the original parent.
3146 hammer2_chain_unlock(ichain);
3147 hammer2_chain_drop(ichain);
3150 * Otherwise its in the range, return the new parent.
3151 * (leave both the new and old parent locked).
3160 * Calculate the keybits and highside/lowside of the freemap node the
3161 * caller is creating.
3163 * This routine will specify the next higher-level freemap key/radix
3164 * representing the lowest-ordered set. By doing so, eventually all
3165 * low-ordered sets will be moved one level down.
3167 * We have to be careful here because the freemap reserves a limited
3168 * number of blocks for a limited number of levels. So we can't just
3169 * push indiscriminately.
3172 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3173 int keybits, hammer2_blockref_t *base, int count)
3175 hammer2_chain_t *chain;
3176 hammer2_blockref_t *bref;
3178 hammer2_key_t key_beg;
3179 hammer2_key_t key_end;
3180 hammer2_key_t key_next;
3184 int maxloops = 300000;
3192 * Calculate the range of keys in the array being careful to skip
3193 * slots which are overridden with a deletion.
3196 key_end = HAMMER2_KEY_MAX;
3198 hammer2_spin_ex(&parent->core.spin);
3201 if (--maxloops == 0) {
3202 panic("indkey_freemap shit %p %p:%d\n",
3203 parent, base, count);
3205 chain = hammer2_combined_find(parent, base, count,
3206 &cache_index, &key_next,
3217 * Skip deleted chains.
3219 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3220 if (key_next == 0 || key_next > key_end)
3227 * Use the full live (not deleted) element for the scan
3228 * iteration. HAMMER2 does not allow partial replacements.
3230 * XXX should be built into hammer2_combined_find().
3232 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3234 if (keybits > bref->keybits) {
3236 keybits = bref->keybits;
3237 } else if (keybits == bref->keybits && bref->key < key) {
3244 hammer2_spin_unex(&parent->core.spin);
3247 * Return the keybits for a higher-level FREEMAP_NODE covering
3251 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3252 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3254 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3255 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3257 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3258 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3260 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3261 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3263 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3264 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3266 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3267 panic("hammer2_chain_indkey_freemap: level too high");
3270 panic("hammer2_chain_indkey_freemap: bad radix");
3279 * Calculate the keybits and highside/lowside of the indirect block the
3280 * caller is creating.
3283 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3284 int keybits, hammer2_blockref_t *base, int count)
3286 hammer2_blockref_t *bref;
3287 hammer2_chain_t *chain;
3288 hammer2_key_t key_beg;
3289 hammer2_key_t key_end;
3290 hammer2_key_t key_next;
3296 int maxloops = 300000;
3303 * Calculate the range of keys in the array being careful to skip
3304 * slots which are overridden with a deletion. Once the scan
3305 * completes we will cut the key range in half and shift half the
3306 * range into the new indirect block.
3309 key_end = HAMMER2_KEY_MAX;
3311 hammer2_spin_ex(&parent->core.spin);
3314 if (--maxloops == 0) {
3315 panic("indkey_freemap shit %p %p:%d\n",
3316 parent, base, count);
3318 chain = hammer2_combined_find(parent, base, count,
3319 &cache_index, &key_next,
3330 * NOTE: No need to check DUPLICATED here because we do
3331 * not release the spinlock.
3333 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3334 if (key_next == 0 || key_next > key_end)
3341 * Use the full live (not deleted) element for the scan
3342 * iteration. HAMMER2 does not allow partial replacements.
3344 * XXX should be built into hammer2_combined_find().
3346 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3349 * Expand our calculated key range (key, keybits) to fit
3350 * the scanned key. nkeybits represents the full range
3351 * that we will later cut in half (two halves @ nkeybits - 1).
3354 if (nkeybits < bref->keybits) {
3355 if (bref->keybits > 64) {
3356 kprintf("bad bref chain %p bref %p\n",
3360 nkeybits = bref->keybits;
3362 while (nkeybits < 64 &&
3363 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3364 (key ^ bref->key)) != 0) {
3369 * If the new key range is larger we have to determine
3370 * which side of the new key range the existing keys fall
3371 * under by checking the high bit, then collapsing the
3372 * locount into the hicount or vise-versa.
3374 if (keybits != nkeybits) {
3375 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3386 * The newly scanned key will be in the lower half or the
3387 * upper half of the (new) key range.
3389 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3398 hammer2_spin_unex(&parent->core.spin);
3399 bref = NULL; /* now invalid (safety) */
3402 * Adjust keybits to represent half of the full range calculated
3403 * above (radix 63 max)
3408 * Select whichever half contains the most elements. Theoretically
3409 * we can select either side as long as it contains at least one
3410 * element (in order to ensure that a free slot is present to hold
3411 * the indirect block).
3413 if (hammer2_indirect_optimize) {
3415 * Insert node for least number of keys, this will arrange
3416 * the first few blocks of a large file or the first few
3417 * inodes in a directory with fewer indirect blocks when
3420 if (hicount < locount && hicount != 0)
3421 key |= (hammer2_key_t)1 << keybits;
3423 key &= ~(hammer2_key_t)1 << keybits;
3426 * Insert node for most number of keys, best for heavily
3429 if (hicount > locount)
3430 key |= (hammer2_key_t)1 << keybits;
3432 key &= ~(hammer2_key_t)1 << keybits;
3440 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3443 * Both parent and chain must be locked exclusively.
3445 * This function will modify the parent if the blockref requires removal
3446 * from the parent's block table.
3448 * This function is NOT recursive. Any entity already pushed into the
3449 * chain (such as an inode) may still need visibility into its contents,
3450 * as well as the ability to read and modify the contents. For example,
3451 * for an unlinked file which is still open.
3454 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3455 hammer2_tid_t mtid, int flags)
3457 KKASSERT(hammer2_mtx_owned(&chain->lock));
3460 * Nothing to do if already marked.
3462 * We need the spinlock on the core whos RBTREE contains chain
3463 * to protect against races.
3465 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3466 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3467 chain->parent == parent);
3468 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3472 * To avoid losing track of a permanent deletion we add the chain
3473 * to the delayed flush queue. If were to flush it right now the
3474 * parent would end up in a modified state and generate I/O.
3475 * The delayed queue gives the parent a chance to be deleted to
3478 if (flags & HAMMER2_DELETE_PERMANENT) {
3479 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3480 hammer2_delayed_flush(chain);
3482 /* XXX might not be needed */
3483 hammer2_chain_setflush(chain);
3488 * Returns the index of the nearest element in the blockref array >= elm.
3489 * Returns (count) if no element could be found.
3491 * Sets *key_nextp to the next key for loop purposes but does not modify
3492 * it if the next key would be higher than the current value of *key_nextp.
3493 * Note that *key_nexp can overflow to 0, which should be tested by the
3496 * (*cache_indexp) is a heuristic and can be any value without effecting
3499 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3500 * held through the operation.
3503 hammer2_base_find(hammer2_chain_t *parent,
3504 hammer2_blockref_t *base, int count,
3505 int *cache_indexp, hammer2_key_t *key_nextp,
3506 hammer2_key_t key_beg, hammer2_key_t key_end)
3508 hammer2_blockref_t *scan;
3509 hammer2_key_t scan_end;
3514 * Require the live chain's already have their core's counted
3515 * so we can optimize operations.
3517 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3522 if (count == 0 || base == NULL)
3526 * Sequential optimization using *cache_indexp. This is the most
3529 * We can avoid trailing empty entries on live chains, otherwise
3530 * we might have to check the whole block array.
3534 limit = parent->core.live_zero;
3539 KKASSERT(i < count);
3545 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3552 * Search forwards, stop when we find a scan element which
3553 * encloses the key or until we know that there are no further
3557 if (scan->type != 0) {
3558 scan_end = scan->key +
3559 ((hammer2_key_t)1 << scan->keybits) - 1;
3560 if (scan->key > key_beg || scan_end >= key_beg)
3573 scan_end = scan->key +
3574 ((hammer2_key_t)1 << scan->keybits);
3575 if (scan_end && (*key_nextp > scan_end ||
3577 *key_nextp = scan_end;
3585 * Do a combined search and return the next match either from the blockref
3586 * array or from the in-memory chain. Sets *bresp to the returned bref in
3587 * both cases, or sets it to NULL if the search exhausted. Only returns
3588 * a non-NULL chain if the search matched from the in-memory chain.
3590 * When no in-memory chain has been found and a non-NULL bref is returned
3594 * The returned chain is not locked or referenced. Use the returned bref
3595 * to determine if the search exhausted or not. Iterate if the base find
3596 * is chosen but matches a deleted chain.
3598 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3599 * held through the operation.
3601 static hammer2_chain_t *
3602 hammer2_combined_find(hammer2_chain_t *parent,
3603 hammer2_blockref_t *base, int count,
3604 int *cache_indexp, hammer2_key_t *key_nextp,
3605 hammer2_key_t key_beg, hammer2_key_t key_end,
3606 hammer2_blockref_t **bresp)
3608 hammer2_blockref_t *bref;
3609 hammer2_chain_t *chain;
3613 * Lookup in block array and in rbtree.
3615 *key_nextp = key_end + 1;
3616 i = hammer2_base_find(parent, base, count, cache_indexp,
3617 key_nextp, key_beg, key_end);
3618 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3623 if (i == count && chain == NULL) {
3629 * Only chain matched.
3632 bref = &chain->bref;
3637 * Only blockref matched.
3639 if (chain == NULL) {
3645 * Both in-memory and blockref matched, select the nearer element.
3647 * If both are flush with the left-hand side or both are the
3648 * same distance away, select the chain. In this situation the
3649 * chain must have been loaded from the matching blockmap.
3651 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3652 chain->bref.key == base[i].key) {
3653 KKASSERT(chain->bref.key == base[i].key);
3654 bref = &chain->bref;
3659 * Select the nearer key
3661 if (chain->bref.key < base[i].key) {
3662 bref = &chain->bref;
3669 * If the bref is out of bounds we've exhausted our search.
3672 if (bref->key > key_end) {
3682 * Locate the specified block array element and delete it. The element
3685 * The spin lock on the related chain must be held.
3687 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3688 * need to be adjusted when we commit the media change.
3691 hammer2_base_delete(hammer2_chain_t *parent,
3692 hammer2_blockref_t *base, int count,
3693 int *cache_indexp, hammer2_chain_t *chain)
3695 hammer2_blockref_t *elm = &chain->bref;
3696 hammer2_key_t key_next;
3700 * Delete element. Expect the element to exist.
3702 * XXX see caller, flush code not yet sophisticated enough to prevent
3703 * re-flushed in some cases.
3705 key_next = 0; /* max range */
3706 i = hammer2_base_find(parent, base, count, cache_indexp,
3707 &key_next, elm->key, elm->key);
3708 if (i == count || base[i].type == 0 ||
3709 base[i].key != elm->key ||
3710 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3711 base[i].keybits != elm->keybits)) {
3712 hammer2_spin_unex(&parent->core.spin);
3713 panic("delete base %p element not found at %d/%d elm %p\n",
3714 base, i, count, elm);
3719 * Update stats and zero the entry
3721 parent->bref.data_count -= base[i].data_count;
3722 parent->bref.data_count -= (hammer2_off_t)1 <<
3723 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3724 parent->bref.inode_count -= base[i].inode_count;
3725 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3726 parent->bref.inode_count -= 1;
3728 bzero(&base[i], sizeof(*base));
3731 * We can only optimize parent->core.live_zero for live chains.
3733 if (parent->core.live_zero == i + 1) {
3734 while (--i >= 0 && base[i].type == 0)
3736 parent->core.live_zero = i + 1;
3740 * Clear appropriate blockmap flags in chain.
3742 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3743 HAMMER2_CHAIN_BMAPUPD);
3747 * Insert the specified element. The block array must not already have the
3748 * element and must have space available for the insertion.
3750 * The spin lock on the related chain must be held.
3752 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3753 * need to be adjusted when we commit the media change.
3756 hammer2_base_insert(hammer2_chain_t *parent,
3757 hammer2_blockref_t *base, int count,
3758 int *cache_indexp, hammer2_chain_t *chain)
3760 hammer2_blockref_t *elm = &chain->bref;
3761 hammer2_key_t key_next;
3770 * Insert new element. Expect the element to not already exist
3771 * unless we are replacing it.
3773 * XXX see caller, flush code not yet sophisticated enough to prevent
3774 * re-flushed in some cases.
3776 key_next = 0; /* max range */
3777 i = hammer2_base_find(parent, base, count, cache_indexp,
3778 &key_next, elm->key, elm->key);
3781 * Shortcut fill optimization, typical ordered insertion(s) may not
3784 KKASSERT(i >= 0 && i <= count);
3787 * Set appropriate blockmap flags in chain.
3789 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3792 * Update stats and zero the entry
3794 parent->bref.data_count += elm->data_count;
3795 parent->bref.data_count += (hammer2_off_t)1 <<
3796 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3797 parent->bref.inode_count += elm->inode_count;
3798 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3799 parent->bref.inode_count += 1;
3803 * We can only optimize parent->core.live_zero for live chains.
3805 if (i == count && parent->core.live_zero < count) {
3806 i = parent->core.live_zero++;
3811 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3812 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3813 hammer2_spin_unex(&parent->core.spin);
3814 panic("insert base %p overlapping elements at %d elm %p\n",
3819 * Try to find an empty slot before or after.
3823 while (j > 0 || k < count) {
3825 if (j >= 0 && base[j].type == 0) {
3829 bcopy(&base[j+1], &base[j],
3830 (i - j - 1) * sizeof(*base));
3836 if (k < count && base[k].type == 0) {
3837 bcopy(&base[i], &base[i+1],
3838 (k - i) * sizeof(hammer2_blockref_t));
3842 * We can only update parent->core.live_zero for live
3845 if (parent->core.live_zero <= k)
3846 parent->core.live_zero = k + 1;
3851 panic("hammer2_base_insert: no room!");
3858 for (l = 0; l < count; ++l) {
3860 key_next = base[l].key +
3861 ((hammer2_key_t)1 << base[l].keybits) - 1;
3865 while (++l < count) {
3867 if (base[l].key <= key_next)
3868 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3869 key_next = base[l].key +
3870 ((hammer2_key_t)1 << base[l].keybits) - 1;
3880 * Sort the blockref array for the chain. Used by the flush code to
3881 * sort the blockref[] array.
3883 * The chain must be exclusively locked AND spin-locked.
3885 typedef hammer2_blockref_t *hammer2_blockref_p;
3889 hammer2_base_sort_callback(const void *v1, const void *v2)
3891 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3892 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3895 * Make sure empty elements are placed at the end of the array
3897 if (bref1->type == 0) {
3898 if (bref2->type == 0)
3901 } else if (bref2->type == 0) {
3908 if (bref1->key < bref2->key)
3910 if (bref1->key > bref2->key)
3916 hammer2_base_sort(hammer2_chain_t *chain)
3918 hammer2_blockref_t *base;
3921 switch(chain->bref.type) {
3922 case HAMMER2_BREF_TYPE_INODE:
3924 * Special shortcut for embedded data returns the inode
3925 * itself. Callers must detect this condition and access
3926 * the embedded data (the strategy code does this for us).
3928 * This is only applicable to regular files and softlinks.
3930 if (chain->data->ipdata.meta.op_flags &
3931 HAMMER2_OPFLAG_DIRECTDATA) {
3934 base = &chain->data->ipdata.u.blockset.blockref[0];
3935 count = HAMMER2_SET_COUNT;
3937 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3938 case HAMMER2_BREF_TYPE_INDIRECT:
3940 * Optimize indirect blocks in the INITIAL state to avoid
3943 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3944 base = &chain->data->npdata[0];
3945 count = chain->bytes / sizeof(hammer2_blockref_t);
3947 case HAMMER2_BREF_TYPE_VOLUME:
3948 base = &chain->data->voldata.sroot_blockset.blockref[0];
3949 count = HAMMER2_SET_COUNT;
3951 case HAMMER2_BREF_TYPE_FREEMAP:
3952 base = &chain->data->blkset.blockref[0];
3953 count = HAMMER2_SET_COUNT;
3956 kprintf("hammer2_chain_lookup: unrecognized "
3957 "blockref(A) type: %d",
3960 tsleep(&base, 0, "dead", 0);
3961 panic("hammer2_chain_lookup: unrecognized "
3962 "blockref(A) type: %d",
3964 base = NULL; /* safety */
3965 count = 0; /* safety */
3967 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3973 * Chain memory management
3976 hammer2_chain_wait(hammer2_chain_t *chain)
3978 tsleep(chain, 0, "chnflw", 1);
3981 const hammer2_media_data_t *
3982 hammer2_chain_rdata(hammer2_chain_t *chain)
3984 KKASSERT(chain->data != NULL);
3985 return (chain->data);
3988 hammer2_media_data_t *
3989 hammer2_chain_wdata(hammer2_chain_t *chain)
3991 KKASSERT(chain->data != NULL);
3992 return (chain->data);
3996 * Set the check data for a chain. This can be a heavy-weight operation
3997 * and typically only runs on-flush. For file data check data is calculated
3998 * when the logical buffers are flushed.
4001 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4003 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4005 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4006 case HAMMER2_CHECK_NONE:
4008 case HAMMER2_CHECK_DISABLED:
4010 case HAMMER2_CHECK_ISCSI32:
4011 chain->bref.check.iscsi32.value =
4012 hammer2_icrc32(bdata, chain->bytes);
4014 case HAMMER2_CHECK_CRC64:
4015 chain->bref.check.crc64.value = 0;
4018 case HAMMER2_CHECK_SHA192:
4020 SHA256_CTX hash_ctx;
4022 uint8_t digest[SHA256_DIGEST_LENGTH];
4023 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4026 SHA256_Init(&hash_ctx);
4027 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4028 SHA256_Final(u.digest, &hash_ctx);
4029 u.digest64[2] ^= u.digest64[3];
4031 chain->bref.check.sha192.data,
4032 sizeof(chain->bref.check.sha192.data));
4035 case HAMMER2_CHECK_FREEMAP:
4036 chain->bref.check.freemap.icrc32 =
4037 hammer2_icrc32(bdata, chain->bytes);
4040 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4041 chain->bref.methods);
4047 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4051 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4054 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4055 case HAMMER2_CHECK_NONE:
4058 case HAMMER2_CHECK_DISABLED:
4061 case HAMMER2_CHECK_ISCSI32:
4062 r = (chain->bref.check.iscsi32.value ==
4063 hammer2_icrc32(bdata, chain->bytes));
4065 case HAMMER2_CHECK_CRC64:
4066 r = (chain->bref.check.crc64.value == 0);
4069 case HAMMER2_CHECK_SHA192:
4071 SHA256_CTX hash_ctx;
4073 uint8_t digest[SHA256_DIGEST_LENGTH];
4074 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4077 SHA256_Init(&hash_ctx);
4078 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4079 SHA256_Final(u.digest, &hash_ctx);
4080 u.digest64[2] ^= u.digest64[3];
4082 chain->bref.check.sha192.data,
4083 sizeof(chain->bref.check.sha192.data)) == 0) {
4090 case HAMMER2_CHECK_FREEMAP:
4091 r = (chain->bref.check.freemap.icrc32 ==
4092 hammer2_icrc32(bdata, chain->bytes));
4094 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4095 chain->bref.check.freemap.icrc32,
4096 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4098 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4099 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4104 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4105 chain->bref.methods);
4113 * The caller presents a shared-locked (parent, chain) where the chain
4114 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4115 * structure representing the inode locked to prevent
4116 * consolidation/deconsolidation races.
4118 * We locate the hardlink in the current or a common parent directory.
4120 * If we are unable to locate the hardlink, EIO is returned and
4121 * (*chainp) is unlocked and dropped.
4124 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4125 hammer2_chain_t **parentp,
4126 hammer2_chain_t **chainp,
4129 hammer2_chain_t *parent;
4130 hammer2_chain_t *rchain;
4131 hammer2_key_t key_dummy;
4133 int cache_index = -1;
4136 * Obtain the key for the hardlink from *chainp.
4139 lhc = rchain->data->ipdata.meta.inum;
4140 hammer2_chain_unlock(rchain);
4141 hammer2_chain_drop(rchain);
4146 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4148 &cache_index, flags);
4153 * Iterate parents, handle parent rename races by retrying
4161 parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4164 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4166 if (parent->parent == NULL)
4168 parent = parent->parent;
4169 hammer2_chain_ref(parent);
4170 hammer2_chain_unlock(*parentp);
4171 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4173 if ((*parentp)->parent == parent) {
4174 hammer2_chain_drop(*parentp);
4177 hammer2_chain_unlock(parent);
4178 hammer2_chain_drop(parent);
4179 hammer2_chain_lock(*parentp,
4180 HAMMER2_RESOLVE_ALWAYS |
4182 parent = NULL; /* safety */
4190 return (rchain ? EINVAL : 0);
4194 * Used by the bulkscan code to snapshot the synchronized storage for
4195 * a volume, allowing it to be scanned concurrently against normal
4199 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4201 hammer2_chain_t *copy;
4203 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4204 switch(chain->bref.type) {
4205 case HAMMER2_BREF_TYPE_VOLUME:
4206 copy->data = kmalloc(sizeof(copy->data->voldata),
4209 hammer2_spin_ex(&chain->core.spin);
4210 copy->data->voldata = chain->data->voldata;
4211 hammer2_spin_unex(&chain->core.spin);
4213 case HAMMER2_BREF_TYPE_FREEMAP:
4214 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4217 hammer2_spin_ex(&chain->core.spin);
4218 copy->data->blkset = chain->data->blkset;
4219 hammer2_spin_unex(&chain->core.spin);
4228 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4230 switch(copy->bref.type) {
4231 case HAMMER2_BREF_TYPE_VOLUME:
4232 case HAMMER2_BREF_TYPE_FREEMAP:
4233 KKASSERT(copy->data);
4234 kfree(copy->data, copy->hmp->mchain);
4239 hammer2_chain_drop(copy);
4243 * Create a snapshot of the specified {parent, ochain} with the specified
4244 * label. The originating hammer2_inode must be exclusively locked for
4247 * The ioctl code has already synced the filesystem.
4250 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4254 const hammer2_inode_data_t *ripdata;
4255 hammer2_inode_data_t *wipdata;
4256 hammer2_chain_t *nchain;
4257 hammer2_inode_t *nip;
4266 kprintf("snapshot %s\n", pmp->name);
4268 name_len = strlen(pmp->name);
4269 lhc = hammer2_dirhash(pmp->name, name_len);
4274 ripdata = &chain->data->ipdata;
4276 opfs_clid = ripdata->meta.pfs_clid;
4281 * Create the snapshot directory under the super-root
4283 * Set PFS type, generate a unique filesystem id, and generate
4284 * a cluster id. Use the same clid when snapshotting a PFS root,
4285 * which theoretically allows the snapshot to be used as part of
4286 * the same cluster (perhaps as a cache).
4288 * Copy the (flushed) blockref array. Theoretically we could use
4289 * chain_duplicate() but it becomes difficult to disentangle
4290 * the shared core so for now just brute-force it.
4295 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4296 pmp->name, name_len, 0,
4298 HAMMER2_INSERT_PFSROOT, &error);
4301 hammer2_inode_modify(nip);
4302 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4303 hammer2_chain_modify(nchain, mtid, 0, 0);
4304 wipdata = &nchain->data->ipdata;
4306 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4307 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4308 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4309 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4312 * Give the snapshot its own private cluster id. As a
4313 * snapshot no further synchronization with the original
4314 * cluster will be done.
4317 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4318 nip->meta.pfs_clid = opfs_clid;
4320 kern_uuidgen(&nip->meta.pfs_clid, 1);
4322 kern_uuidgen(&nip->meta.pfs_clid, 1);
4323 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4325 /* XXX hack blockset copy */
4326 /* XXX doesn't work with real cluster */
4327 wipdata->meta = nip->meta;
4328 wipdata->u.blockset = ripdata->u.blockset;
4329 hammer2_flush(nchain, 1);
4330 hammer2_chain_unlock(nchain);
4331 hammer2_chain_drop(nchain);
4332 hammer2_inode_unlock(nip);