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) == 0) {
873 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
874 switch(chain->bref.type) {
875 case HAMMER2_BREF_TYPE_DATA:
876 counterp = &hammer2_ioa_file_write;
878 case HAMMER2_BREF_TYPE_INODE:
879 counterp = &hammer2_ioa_meta_write;
881 case HAMMER2_BREF_TYPE_INDIRECT:
882 counterp = &hammer2_ioa_indr_write;
884 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
885 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
886 counterp = &hammer2_ioa_fmap_write;
889 counterp = &hammer2_ioa_volu_write;
892 *counterp += chain->bytes;
894 switch(chain->bref.type) {
895 case HAMMER2_BREF_TYPE_DATA:
896 counterp = &hammer2_iod_file_write;
898 case HAMMER2_BREF_TYPE_INODE:
899 counterp = &hammer2_iod_meta_write;
901 case HAMMER2_BREF_TYPE_INDIRECT:
902 counterp = &hammer2_iod_indr_write;
904 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
905 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
906 counterp = &hammer2_iod_fmap_write;
909 counterp = &hammer2_iod_volu_write;
912 *counterp += chain->bytes;
918 * If a device buffer was used for data be sure to destroy the
919 * buffer when we are done to avoid aliases (XXX what about the
920 * underlying VM pages?).
922 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
925 * NOTE: The isdirty check tracks whether we have to bdwrite() the
926 * buffer or not. The buffer might already be dirty. The
927 * flag is re-set when chain_modify() is called, even if
928 * MODIFIED is already set, allowing the OS to retire the
929 * buffer independent of a hammer2 flush.
932 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
933 hammer2_io_isdirty(chain->dio)) {
934 hammer2_io_bawrite(&chain->dio);
936 hammer2_io_bqrelse(&chain->dio);
938 hammer2_mtx_unlock(&chain->lock);
942 * This counts the number of live blockrefs in a block array and
943 * also calculates the point at which all remaining blockrefs are empty.
944 * This routine can only be called on a live chain (DUPLICATED flag not set).
946 * NOTE: Flag is not set until after the count is complete, allowing
947 * callers to test the flag without holding the spinlock.
949 * NOTE: If base is NULL the related chain is still in the INITIAL
950 * state and there are no blockrefs to count.
952 * NOTE: live_count may already have some counts accumulated due to
953 * creation and deletion and could even be initially negative.
956 hammer2_chain_countbrefs(hammer2_chain_t *chain,
957 hammer2_blockref_t *base, int count)
959 hammer2_spin_ex(&chain->core.spin);
960 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
962 while (--count >= 0) {
963 if (base[count].type)
966 chain->core.live_zero = count + 1;
968 if (base[count].type)
969 atomic_add_int(&chain->core.live_count,
974 chain->core.live_zero = 0;
976 /* else do not modify live_count */
977 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
979 hammer2_spin_unex(&chain->core.spin);
983 * Resize the chain's physical storage allocation in-place. This function does
984 * not adjust the data pointer and must be followed by (typically) a
985 * hammer2_chain_modify() call to copy any old data over and adjust the
988 * Chains can be resized smaller without reallocating the storage. Resizing
989 * larger will reallocate the storage. Excess or prior storage is reclaimed
990 * asynchronously at a later time.
992 * Must be passed an exclusively locked parent and chain.
994 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
995 * to avoid instantiating a device buffer that conflicts with the vnode data
996 * buffer. However, because H2 can compress or encrypt data, the chain may
997 * have a dio assigned to it in those situations, and they do not conflict.
999 * XXX return error if cannot resize.
1002 hammer2_chain_resize(hammer2_inode_t *ip,
1003 hammer2_chain_t *parent, hammer2_chain_t *chain,
1004 hammer2_tid_t mtid, int nradix, int flags)
1013 * Only data and indirect blocks can be resized for now.
1014 * (The volu root, inodes, and freemap elements use a fixed size).
1016 KKASSERT(chain != &hmp->vchain);
1017 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1018 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1019 KKASSERT(chain->parent == parent);
1022 * Nothing to do if the element is already the proper size
1024 obytes = chain->bytes;
1025 nbytes = 1U << nradix;
1026 if (obytes == nbytes)
1030 * Make sure the old data is instantiated so we can copy it. If this
1031 * is a data block, the device data may be superfluous since the data
1032 * might be in a logical block, but compressed or encrypted data is
1035 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1037 hammer2_chain_modify(chain, mtid, 0);
1040 * Relocate the block, even if making it smaller (because different
1041 * block sizes may be in different regions).
1043 * (data blocks only, we aren't copying the storage here).
1045 hammer2_freemap_alloc(chain, nbytes);
1046 chain->bytes = nbytes;
1047 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1050 * We don't want the followup chain_modify() to try to copy data
1051 * from the old (wrong-sized) buffer. It won't know how much to
1052 * copy. This case should only occur during writes when the
1053 * originator already has the data to write in-hand.
1056 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1057 hammer2_io_brelse(&chain->dio);
1063 * Set the chain modified so its data can be changed by the caller.
1065 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1066 * is a CLC (cluster level change) field and is not updated by parent
1067 * propagation during a flush.
1070 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid, int flags)
1072 hammer2_blockref_t obref;
1081 obref = chain->bref;
1082 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1085 * Data is not optional for freemap chains (we must always be sure
1086 * to copy the data on COW storage allocations).
1088 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1089 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1090 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1091 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1095 * Data must be resolved if already assigned, unless explicitly
1096 * flagged otherwise.
1098 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1099 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1100 hammer2_chain_load_data(chain);
1104 * Set MODIFIED to indicate that the chain has been modified.
1105 * Set UPDATE to ensure that the blockref is updated in the parent.
1107 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1108 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1109 hammer2_chain_ref(chain);
1110 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1115 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1116 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1117 hammer2_chain_ref(chain);
1121 * The modification or re-modification requires an allocation and
1124 * XXX can a chain already be marked MODIFIED without a data
1125 * assignment? If not, assert here instead of testing the case.
1127 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1128 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1131 hammer2_freemap_alloc(chain, chain->bytes);
1132 /* XXX failed allocation */
1137 * Update mirror_tid and modify_tid. modify_tid is only updated
1138 * if not passed as zero (during flushes, parent propagation passes
1141 * NOTE: chain->pmp could be the device spmp.
1143 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1145 chain->bref.modify_tid = mtid;
1148 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1149 * requires updating as well as to tell the delete code that the
1150 * chain's blockref might not exactly match (in terms of physical size
1151 * or block offset) the one in the parent's blocktable. The base key
1152 * of course will still match.
1154 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1155 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1158 * Short-cut data blocks which the caller does not need an actual
1159 * data reference to (aka OPTDATA), as long as the chain does not
1160 * already have a data pointer to the data. This generally means
1161 * that the modifications are being done via the logical buffer cache.
1162 * The INITIAL flag relates only to the device data buffer and thus
1163 * remains unchange in this situation.
1165 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1166 (flags & HAMMER2_MODIFY_OPTDATA) &&
1167 chain->data == NULL) {
1172 * Clearing the INITIAL flag (for indirect blocks) indicates that
1173 * we've processed the uninitialized storage allocation.
1175 * If this flag is already clear we are likely in a copy-on-write
1176 * situation but we have to be sure NOT to bzero the storage if
1177 * no data is present.
1179 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1180 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1187 * Instantiate data buffer and possibly execute COW operation
1189 switch(chain->bref.type) {
1190 case HAMMER2_BREF_TYPE_VOLUME:
1191 case HAMMER2_BREF_TYPE_FREEMAP:
1193 * The data is embedded, no copy-on-write operation is
1196 KKASSERT(chain->dio == NULL);
1198 case HAMMER2_BREF_TYPE_INODE:
1199 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1200 case HAMMER2_BREF_TYPE_DATA:
1201 case HAMMER2_BREF_TYPE_INDIRECT:
1202 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1204 * Perform the copy-on-write operation
1206 * zero-fill or copy-on-write depending on whether
1207 * chain->data exists or not and set the dirty state for
1208 * the new buffer. hammer2_io_new() will handle the
1211 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1214 error = hammer2_io_new(hmp, chain->bref.data_off,
1215 chain->bytes, &dio);
1217 error = hammer2_io_bread(hmp, chain->bref.data_off,
1218 chain->bytes, &dio);
1220 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1223 * If an I/O error occurs make sure callers cannot accidently
1224 * modify the old buffer's contents and corrupt the filesystem.
1227 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1229 chain->error = HAMMER2_ERROR_IO;
1230 hammer2_io_brelse(&dio);
1231 hammer2_io_brelse(&chain->dio);
1236 bdata = hammer2_io_data(dio, chain->bref.data_off);
1239 KKASSERT(chain->dio != NULL);
1240 if (chain->data != (void *)bdata) {
1241 bcopy(chain->data, bdata, chain->bytes);
1243 } else if (wasinitial == 0) {
1245 * We have a problem. We were asked to COW but
1246 * we don't have any data to COW with!
1248 panic("hammer2_chain_modify: having a COW %p\n",
1253 * Retire the old buffer, replace with the new. Dirty or
1254 * redirty the new buffer.
1256 * WARNING! The system buffer cache may have already flushed
1257 * the buffer, so we must be sure to [re]dirty it
1258 * for further modification.
1261 hammer2_io_brelse(&chain->dio);
1262 chain->data = (void *)bdata;
1264 hammer2_io_setdirty(dio); /* modified by bcopy above */
1267 panic("hammer2_chain_modify: illegal non-embedded type %d",
1274 * setflush on parent indicating that the parent must recurse down
1275 * to us. Do not call on chain itself which might already have it
1279 hammer2_chain_setflush(chain->parent);
1283 * Modify the chain associated with an inode.
1286 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1287 hammer2_tid_t mtid, int flags)
1289 hammer2_inode_modify(ip);
1290 hammer2_chain_modify(chain, mtid, flags);
1294 * Volume header data locks
1297 hammer2_voldata_lock(hammer2_dev_t *hmp)
1299 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1303 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1305 lockmgr(&hmp->vollk, LK_RELEASE);
1309 hammer2_voldata_modify(hammer2_dev_t *hmp)
1311 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1312 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1313 hammer2_chain_ref(&hmp->vchain);
1314 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1319 * This function returns the chain at the nearest key within the specified
1320 * range. The returned chain will be referenced but not locked.
1322 * This function will recurse through chain->rbtree as necessary and will
1323 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1324 * the iteration value is less than the current value of *key_nextp.
1326 * The caller should use (*key_nextp) to calculate the actual range of
1327 * the returned element, which will be (key_beg to *key_nextp - 1), because
1328 * there might be another element which is superior to the returned element
1331 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1332 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1333 * it will wind up being (key_end + 1).
1335 * WARNING! Must be called with child's spinlock held. Spinlock remains
1336 * held through the operation.
1338 struct hammer2_chain_find_info {
1339 hammer2_chain_t *best;
1340 hammer2_key_t key_beg;
1341 hammer2_key_t key_end;
1342 hammer2_key_t key_next;
1345 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1346 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1350 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1351 hammer2_key_t key_beg, hammer2_key_t key_end)
1353 struct hammer2_chain_find_info info;
1356 info.key_beg = key_beg;
1357 info.key_end = key_end;
1358 info.key_next = *key_nextp;
1360 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1361 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1363 *key_nextp = info.key_next;
1365 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1366 parent, key_beg, key_end, *key_nextp);
1374 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1376 struct hammer2_chain_find_info *info = data;
1377 hammer2_key_t child_beg;
1378 hammer2_key_t child_end;
1380 child_beg = child->bref.key;
1381 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1383 if (child_end < info->key_beg)
1385 if (child_beg > info->key_end)
1392 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1394 struct hammer2_chain_find_info *info = data;
1395 hammer2_chain_t *best;
1396 hammer2_key_t child_end;
1399 * WARNING! Do not discard DUPLICATED chains, it is possible that
1400 * we are catching an insertion half-way done. If a
1401 * duplicated chain turns out to be the best choice the
1402 * caller will re-check its flags after locking it.
1404 * WARNING! Layerq is scanned forwards, exact matches should keep
1405 * the existing info->best.
1407 if ((best = info->best) == NULL) {
1409 * No previous best. Assign best
1412 } else if (best->bref.key <= info->key_beg &&
1413 child->bref.key <= info->key_beg) {
1418 /*info->best = child;*/
1419 } else if (child->bref.key < best->bref.key) {
1421 * Child has a nearer key and best is not flush with key_beg.
1422 * Set best to child. Truncate key_next to the old best key.
1425 if (info->key_next > best->bref.key || info->key_next == 0)
1426 info->key_next = best->bref.key;
1427 } else if (child->bref.key == best->bref.key) {
1429 * If our current best is flush with the child then this
1430 * is an illegal overlap.
1432 * key_next will automatically be limited to the smaller of
1433 * the two end-points.
1439 * Keep the current best but truncate key_next to the child's
1442 * key_next will also automatically be limited to the smaller
1443 * of the two end-points (probably not necessary for this case
1444 * but we do it anyway).
1446 if (info->key_next > child->bref.key || info->key_next == 0)
1447 info->key_next = child->bref.key;
1451 * Always truncate key_next based on child's end-of-range.
1453 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1454 if (child_end && (info->key_next > child_end || info->key_next == 0))
1455 info->key_next = child_end;
1461 * Retrieve the specified chain from a media blockref, creating the
1462 * in-memory chain structure which reflects it.
1464 * To handle insertion races pass the INSERT_RACE flag along with the
1465 * generation number of the core. NULL will be returned if the generation
1466 * number changes before we have a chance to insert the chain. Insert
1467 * races can occur because the parent might be held shared.
1469 * Caller must hold the parent locked shared or exclusive since we may
1470 * need the parent's bref array to find our block.
1472 * WARNING! chain->pmp is always set to NULL for any chain representing
1473 * part of the super-root topology.
1476 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1477 hammer2_blockref_t *bref)
1479 hammer2_dev_t *hmp = parent->hmp;
1480 hammer2_chain_t *chain;
1484 * Allocate a chain structure representing the existing media
1485 * entry. Resulting chain has one ref and is not locked.
1487 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1488 chain = hammer2_chain_alloc(hmp, NULL, bref);
1490 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1491 /* ref'd chain returned */
1494 * Flag that the chain is in the parent's blockmap so delete/flush
1495 * knows what to do with it.
1497 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1500 * Link the chain into its parent. A spinlock is required to safely
1501 * access the RBTREE, and it is possible to collide with another
1502 * hammer2_chain_get() operation because the caller might only hold
1503 * a shared lock on the parent.
1505 KKASSERT(parent->refs > 0);
1506 error = hammer2_chain_insert(parent, chain,
1507 HAMMER2_CHAIN_INSERT_SPIN |
1508 HAMMER2_CHAIN_INSERT_RACE,
1511 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1512 kprintf("chain %p get race\n", chain);
1513 hammer2_chain_drop(chain);
1516 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1520 * Return our new chain referenced but not locked, or NULL if
1527 * Lookup initialization/completion API
1530 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1532 hammer2_chain_ref(parent);
1533 if (flags & HAMMER2_LOOKUP_SHARED) {
1534 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1535 HAMMER2_RESOLVE_SHARED);
1537 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1543 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1546 hammer2_chain_unlock(parent);
1547 hammer2_chain_drop(parent);
1552 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1554 hammer2_chain_t *oparent;
1555 hammer2_chain_t *nparent;
1558 * Be careful of order, oparent must be unlocked before nparent
1559 * is locked below to avoid a deadlock.
1562 hammer2_spin_ex(&oparent->core.spin);
1563 nparent = oparent->parent;
1564 hammer2_chain_ref(nparent);
1565 hammer2_spin_unex(&oparent->core.spin);
1567 hammer2_chain_unlock(oparent);
1568 hammer2_chain_drop(oparent);
1572 hammer2_chain_lock(nparent, how);
1579 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1580 * (*parentp) typically points to an inode but can also point to a related
1581 * indirect block and this function will recurse upwards and find the inode
1584 * (*parentp) must be exclusively locked and referenced and can be an inode
1585 * or an existing indirect block within the inode.
1587 * On return (*parentp) will be modified to point at the deepest parent chain
1588 * element encountered during the search, as a helper for an insertion or
1589 * deletion. The new (*parentp) will be locked and referenced and the old
1590 * will be unlocked and dereferenced (no change if they are both the same).
1592 * The matching chain will be returned exclusively locked. If NOLOCK is
1593 * requested the chain will be returned only referenced. Note that the
1594 * parent chain must always be locked shared or exclusive, matching the
1595 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1596 * when NOLOCK is specified but that complicates matters if *parentp must
1597 * inherit the chain.
1599 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1600 * data pointer or can otherwise be in flux.
1602 * NULL is returned if no match was found, but (*parentp) will still
1603 * potentially be adjusted.
1605 * If a fatal error occurs (typically an I/O error), a dummy chain is
1606 * returned with chain->error and error-identifying information set. This
1607 * chain will assert if you try to do anything fancy with it.
1609 * XXX Depending on where the error occurs we should allow continued iteration.
1611 * On return (*key_nextp) will point to an iterative value for key_beg.
1612 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1614 * This function will also recurse up the chain if the key is not within the
1615 * current parent's range. (*parentp) can never be set to NULL. An iteration
1616 * can simply allow (*parentp) to float inside the loop.
1618 * NOTE! chain->data is not always resolved. By default it will not be
1619 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1620 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1621 * BREF_TYPE_DATA as the device buffer can alias the logical file
1625 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1626 hammer2_key_t key_beg, hammer2_key_t key_end,
1627 int *cache_indexp, int flags)
1630 hammer2_chain_t *parent;
1631 hammer2_chain_t *chain;
1632 hammer2_blockref_t *base;
1633 hammer2_blockref_t *bref;
1634 hammer2_blockref_t bcopy;
1635 hammer2_key_t scan_beg;
1636 hammer2_key_t scan_end;
1638 int how_always = HAMMER2_RESOLVE_ALWAYS;
1639 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1642 int maxloops = 300000;
1644 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1645 how_maybe = how_always;
1646 how = HAMMER2_RESOLVE_ALWAYS;
1647 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1648 how = HAMMER2_RESOLVE_NEVER;
1650 how = HAMMER2_RESOLVE_MAYBE;
1652 if (flags & HAMMER2_LOOKUP_SHARED) {
1653 how_maybe |= HAMMER2_RESOLVE_SHARED;
1654 how_always |= HAMMER2_RESOLVE_SHARED;
1655 how |= HAMMER2_RESOLVE_SHARED;
1659 * Recurse (*parentp) upward if necessary until the parent completely
1660 * encloses the key range or we hit the inode.
1662 * This function handles races against the flusher doing a delete-
1663 * duplicate above us and re-homes the parent to the duplicate in
1664 * that case, otherwise we'd wind up recursing down a stale chain.
1669 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1670 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1671 scan_beg = parent->bref.key;
1672 scan_end = scan_beg +
1673 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1674 if (key_beg >= scan_beg && key_end <= scan_end)
1676 parent = hammer2_chain_getparent(parentp, how_maybe);
1680 if (--maxloops == 0)
1681 panic("hammer2_chain_lookup: maxloops");
1683 * Locate the blockref array. Currently we do a fully associative
1684 * search through the array.
1686 switch(parent->bref.type) {
1687 case HAMMER2_BREF_TYPE_INODE:
1689 * Special shortcut for embedded data returns the inode
1690 * itself. Callers must detect this condition and access
1691 * the embedded data (the strategy code does this for us).
1693 * This is only applicable to regular files and softlinks.
1695 if (parent->data->ipdata.meta.op_flags &
1696 HAMMER2_OPFLAG_DIRECTDATA) {
1697 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1699 *key_nextp = key_end + 1;
1702 hammer2_chain_ref(parent);
1703 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1704 hammer2_chain_lock(parent, how_always);
1705 *key_nextp = key_end + 1;
1708 base = &parent->data->ipdata.u.blockset.blockref[0];
1709 count = HAMMER2_SET_COUNT;
1711 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1712 case HAMMER2_BREF_TYPE_INDIRECT:
1714 * Handle MATCHIND on the parent
1716 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1717 scan_beg = parent->bref.key;
1718 scan_end = scan_beg +
1719 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1720 if (key_beg == scan_beg && key_end == scan_end) {
1722 hammer2_chain_ref(chain);
1723 hammer2_chain_lock(chain, how_maybe);
1724 *key_nextp = scan_end + 1;
1729 * Optimize indirect blocks in the INITIAL state to avoid
1732 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1735 if (parent->data == NULL)
1736 panic("parent->data is NULL");
1737 base = &parent->data->npdata[0];
1739 count = parent->bytes / sizeof(hammer2_blockref_t);
1741 case HAMMER2_BREF_TYPE_VOLUME:
1742 base = &parent->data->voldata.sroot_blockset.blockref[0];
1743 count = HAMMER2_SET_COUNT;
1745 case HAMMER2_BREF_TYPE_FREEMAP:
1746 base = &parent->data->blkset.blockref[0];
1747 count = HAMMER2_SET_COUNT;
1750 kprintf("hammer2_chain_lookup: unrecognized "
1751 "blockref(B) type: %d",
1754 tsleep(&base, 0, "dead", 0);
1755 panic("hammer2_chain_lookup: unrecognized "
1756 "blockref(B) type: %d",
1758 base = NULL; /* safety */
1759 count = 0; /* safety */
1763 * Merged scan to find next candidate.
1765 * hammer2_base_*() functions require the parent->core.live_* fields
1766 * to be synchronized.
1768 * We need to hold the spinlock to access the block array and RB tree
1769 * and to interlock chain creation.
1771 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1772 hammer2_chain_countbrefs(parent, base, count);
1777 hammer2_spin_ex(&parent->core.spin);
1778 chain = hammer2_combined_find(parent, base, count,
1779 cache_indexp, key_nextp,
1782 generation = parent->core.generation;
1785 * Exhausted parent chain, iterate.
1788 hammer2_spin_unex(&parent->core.spin);
1789 if (key_beg == key_end) /* short cut single-key case */
1793 * Stop if we reached the end of the iteration.
1795 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1796 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1801 * Calculate next key, stop if we reached the end of the
1802 * iteration, otherwise go up one level and loop.
1804 key_beg = parent->bref.key +
1805 ((hammer2_key_t)1 << parent->bref.keybits);
1806 if (key_beg == 0 || key_beg > key_end)
1808 parent = hammer2_chain_getparent(parentp, how_maybe);
1813 * Selected from blockref or in-memory chain.
1815 if (chain == NULL) {
1817 hammer2_spin_unex(&parent->core.spin);
1818 chain = hammer2_chain_get(parent, generation,
1820 if (chain == NULL) {
1821 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1822 parent, key_beg, key_end);
1825 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1826 hammer2_chain_drop(chain);
1830 hammer2_chain_ref(chain);
1831 hammer2_spin_unex(&parent->core.spin);
1835 * chain is referenced but not locked. We must lock the chain
1836 * to obtain definitive DUPLICATED/DELETED state
1838 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1839 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1840 hammer2_chain_lock(chain, how_maybe);
1842 hammer2_chain_lock(chain, how);
1846 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1848 * NOTE: Chain's key range is not relevant as there might be
1849 * one-offs within the range that are not deleted.
1851 * NOTE: Lookups can race delete-duplicate because
1852 * delete-duplicate does not lock the parent's core
1853 * (they just use the spinlock on the core). We must
1854 * check for races by comparing the DUPLICATED flag before
1855 * releasing the spinlock with the flag after locking the
1858 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1859 hammer2_chain_unlock(chain);
1860 hammer2_chain_drop(chain);
1861 key_beg = *key_nextp;
1862 if (key_beg == 0 || key_beg > key_end)
1868 * If the chain element is an indirect block it becomes the new
1869 * parent and we loop on it. We must maintain our top-down locks
1870 * to prevent the flusher from interfering (i.e. doing a
1871 * delete-duplicate and leaving us recursing down a deleted chain).
1873 * The parent always has to be locked with at least RESOLVE_MAYBE
1874 * so we can access its data. It might need a fixup if the caller
1875 * passed incompatible flags. Be careful not to cause a deadlock
1876 * as a data-load requires an exclusive lock.
1878 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1879 * range is within the requested key range we return the indirect
1880 * block and do NOT loop. This is usually only used to acquire
1883 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1884 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1885 hammer2_chain_unlock(parent);
1886 hammer2_chain_drop(parent);
1887 *parentp = parent = chain;
1892 * All done, return the chain.
1894 * If the caller does not want a locked chain, replace the lock with
1895 * a ref. Perhaps this can eventually be optimized to not obtain the
1896 * lock in the first place for situations where the data does not
1897 * need to be resolved.
1900 if (flags & HAMMER2_LOOKUP_NOLOCK)
1901 hammer2_chain_unlock(chain);
1908 * After having issued a lookup we can iterate all matching keys.
1910 * If chain is non-NULL we continue the iteration from just after it's index.
1912 * If chain is NULL we assume the parent was exhausted and continue the
1913 * iteration at the next parent.
1915 * If a fatal error occurs (typically an I/O error), a dummy chain is
1916 * returned with chain->error and error-identifying information set. This
1917 * chain will assert if you try to do anything fancy with it.
1919 * XXX Depending on where the error occurs we should allow continued iteration.
1921 * parent must be locked on entry and remains locked throughout. chain's
1922 * lock status must match flags. Chain is always at least referenced.
1924 * WARNING! The MATCHIND flag does not apply to this function.
1927 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1928 hammer2_key_t *key_nextp,
1929 hammer2_key_t key_beg, hammer2_key_t key_end,
1930 int *cache_indexp, int flags)
1932 hammer2_chain_t *parent;
1936 * Calculate locking flags for upward recursion.
1938 how_maybe = HAMMER2_RESOLVE_MAYBE;
1939 if (flags & HAMMER2_LOOKUP_SHARED)
1940 how_maybe |= HAMMER2_RESOLVE_SHARED;
1945 * Calculate the next index and recalculate the parent if necessary.
1948 key_beg = chain->bref.key +
1949 ((hammer2_key_t)1 << chain->bref.keybits);
1950 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1951 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1952 hammer2_chain_unlock(chain);
1954 hammer2_chain_drop(chain);
1957 * chain invalid past this point, but we can still do a
1958 * pointer comparison w/parent.
1960 * Any scan where the lookup returned degenerate data embedded
1961 * in the inode has an invalid index and must terminate.
1963 if (chain == parent)
1965 if (key_beg == 0 || key_beg > key_end)
1968 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1969 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1971 * We reached the end of the iteration.
1976 * Continue iteration with next parent unless the current
1977 * parent covers the range.
1979 key_beg = parent->bref.key +
1980 ((hammer2_key_t)1 << parent->bref.keybits);
1981 if (key_beg == 0 || key_beg > key_end)
1983 parent = hammer2_chain_getparent(parentp, how_maybe);
1989 return (hammer2_chain_lookup(parentp, key_nextp,
1991 cache_indexp, flags));
1995 * The raw scan function is similar to lookup/next but does not seek to a key.
1996 * Blockrefs are iterated via first_chain = (parent, NULL) and
1997 * next_chain = (parent, chain).
1999 * The passed-in parent must be locked and its data resolved. The returned
2000 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
2001 * under parent and then iterate with the passed-in chain (which this
2002 * function will unlock).
2005 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2006 int *cache_indexp, int flags)
2009 hammer2_blockref_t *base;
2010 hammer2_blockref_t *bref;
2011 hammer2_blockref_t bcopy;
2013 hammer2_key_t next_key;
2015 int how_always = HAMMER2_RESOLVE_ALWAYS;
2016 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2019 int maxloops = 300000;
2024 * Scan flags borrowed from lookup.
2026 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2027 how_maybe = how_always;
2028 how = HAMMER2_RESOLVE_ALWAYS;
2029 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2030 how = HAMMER2_RESOLVE_NEVER;
2032 how = HAMMER2_RESOLVE_MAYBE;
2034 if (flags & HAMMER2_LOOKUP_SHARED) {
2035 how_maybe |= HAMMER2_RESOLVE_SHARED;
2036 how_always |= HAMMER2_RESOLVE_SHARED;
2037 how |= HAMMER2_RESOLVE_SHARED;
2041 * Calculate key to locate first/next element, unlocking the previous
2042 * element as we go. Be careful, the key calculation can overflow.
2045 key = chain->bref.key +
2046 ((hammer2_key_t)1 << chain->bref.keybits);
2047 hammer2_chain_unlock(chain);
2048 hammer2_chain_drop(chain);
2057 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2058 if (--maxloops == 0)
2059 panic("hammer2_chain_scan: maxloops");
2061 * Locate the blockref array. Currently we do a fully associative
2062 * search through the array.
2064 switch(parent->bref.type) {
2065 case HAMMER2_BREF_TYPE_INODE:
2067 * An inode with embedded data has no sub-chains.
2069 * WARNING! Bulk scan code may pass a static chain marked
2070 * as BREF_TYPE_INODE with a copy of the volume
2071 * root blockset to snapshot the volume.
2073 if (parent->data->ipdata.meta.op_flags &
2074 HAMMER2_OPFLAG_DIRECTDATA) {
2077 base = &parent->data->ipdata.u.blockset.blockref[0];
2078 count = HAMMER2_SET_COUNT;
2080 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2081 case HAMMER2_BREF_TYPE_INDIRECT:
2083 * Optimize indirect blocks in the INITIAL state to avoid
2086 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2089 if (parent->data == NULL)
2090 panic("parent->data is NULL");
2091 base = &parent->data->npdata[0];
2093 count = parent->bytes / sizeof(hammer2_blockref_t);
2095 case HAMMER2_BREF_TYPE_VOLUME:
2096 base = &parent->data->voldata.sroot_blockset.blockref[0];
2097 count = HAMMER2_SET_COUNT;
2099 case HAMMER2_BREF_TYPE_FREEMAP:
2100 base = &parent->data->blkset.blockref[0];
2101 count = HAMMER2_SET_COUNT;
2104 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2106 base = NULL; /* safety */
2107 count = 0; /* safety */
2111 * Merged scan to find next candidate.
2113 * hammer2_base_*() functions require the parent->core.live_* fields
2114 * to be synchronized.
2116 * We need to hold the spinlock to access the block array and RB tree
2117 * and to interlock chain creation.
2119 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2120 hammer2_chain_countbrefs(parent, base, count);
2123 hammer2_spin_ex(&parent->core.spin);
2124 chain = hammer2_combined_find(parent, base, count,
2125 cache_indexp, &next_key,
2126 key, HAMMER2_KEY_MAX,
2128 generation = parent->core.generation;
2131 * Exhausted parent chain, we're done.
2134 hammer2_spin_unex(&parent->core.spin);
2135 KKASSERT(chain == NULL);
2140 * Selected from blockref or in-memory chain.
2142 if (chain == NULL) {
2144 hammer2_spin_unex(&parent->core.spin);
2145 chain = hammer2_chain_get(parent, generation, &bcopy);
2146 if (chain == NULL) {
2147 kprintf("retry scan parent %p keys %016jx\n",
2151 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2152 hammer2_chain_drop(chain);
2157 hammer2_chain_ref(chain);
2158 hammer2_spin_unex(&parent->core.spin);
2162 * chain is referenced but not locked. We must lock the chain
2163 * to obtain definitive DUPLICATED/DELETED state
2165 hammer2_chain_lock(chain, how);
2168 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2170 * NOTE: chain's key range is not relevant as there might be
2171 * one-offs within the range that are not deleted.
2173 * NOTE: XXX this could create problems with scans used in
2174 * situations other than mount-time recovery.
2176 * NOTE: Lookups can race delete-duplicate because
2177 * delete-duplicate does not lock the parent's core
2178 * (they just use the spinlock on the core). We must
2179 * check for races by comparing the DUPLICATED flag before
2180 * releasing the spinlock with the flag after locking the
2183 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2184 hammer2_chain_unlock(chain);
2185 hammer2_chain_drop(chain);
2196 * All done, return the chain or NULL
2202 * Create and return a new hammer2 system memory structure of the specified
2203 * key, type and size and insert it under (*parentp). This is a full
2204 * insertion, based on the supplied key/keybits, and may involve creating
2205 * indirect blocks and moving other chains around via delete/duplicate.
2207 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2208 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2209 * FULL. This typically means that the caller is creating the chain after
2210 * doing a hammer2_chain_lookup().
2212 * (*parentp) must be exclusive locked and may be replaced on return
2213 * depending on how much work the function had to do.
2215 * (*parentp) must not be errored or this function will assert.
2217 * (*chainp) usually starts out NULL and returns the newly created chain,
2218 * but if the caller desires the caller may allocate a disconnected chain
2219 * and pass it in instead.
2221 * This function should NOT be used to insert INDIRECT blocks. It is
2222 * typically used to create/insert inodes and data blocks.
2224 * Caller must pass-in an exclusively locked parent the new chain is to
2225 * be inserted under, and optionally pass-in a disconnected, exclusively
2226 * locked chain to insert (else we create a new chain). The function will
2227 * adjust (*parentp) as necessary, create or connect the chain, and
2228 * return an exclusively locked chain in *chainp.
2230 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2231 * and will be reassigned.
2234 hammer2_chain_create(hammer2_chain_t **parentp,
2235 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2236 hammer2_key_t key, int keybits, int type, size_t bytes,
2237 hammer2_tid_t mtid, int flags)
2240 hammer2_chain_t *chain;
2241 hammer2_chain_t *parent;
2242 hammer2_blockref_t *base;
2243 hammer2_blockref_t dummy;
2247 int maxloops = 300000;
2250 * Topology may be crossing a PFS boundary.
2253 KKASSERT(hammer2_mtx_owned(&parent->lock));
2254 KKASSERT(parent->error == 0);
2258 if (chain == NULL) {
2260 * First allocate media space and construct the dummy bref,
2261 * then allocate the in-memory chain structure. Set the
2262 * INITIAL flag for fresh chains which do not have embedded
2265 * XXX for now set the check mode of the child based on
2266 * the parent or, if the parent is an inode, the
2267 * specification in the inode.
2269 bzero(&dummy, sizeof(dummy));
2272 dummy.keybits = keybits;
2273 dummy.data_off = hammer2_getradix(bytes);
2274 dummy.methods = parent->bref.methods;
2275 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2277 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2278 dummy.methods |= HAMMER2_ENC_CHECK(
2279 parent->data->ipdata.meta.check_algo);
2282 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2285 * Lock the chain manually, chain_lock will load the chain
2286 * which we do NOT want to do. (note: chain->refs is set
2287 * to 1 by chain_alloc() for us, but lockcnt is not).
2290 hammer2_mtx_ex(&chain->lock);
2294 * Set INITIAL to optimize I/O. The flag will generally be
2295 * processed when we call hammer2_chain_modify().
2297 * Recalculate bytes to reflect the actual media block
2300 bytes = (hammer2_off_t)1 <<
2301 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2302 chain->bytes = bytes;
2305 case HAMMER2_BREF_TYPE_VOLUME:
2306 case HAMMER2_BREF_TYPE_FREEMAP:
2307 panic("hammer2_chain_create: called with volume type");
2309 case HAMMER2_BREF_TYPE_INDIRECT:
2310 panic("hammer2_chain_create: cannot be used to"
2311 "create indirect block");
2313 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2314 panic("hammer2_chain_create: cannot be used to"
2315 "create freemap root or node");
2317 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2318 KKASSERT(bytes == sizeof(chain->data->bmdata));
2320 case HAMMER2_BREF_TYPE_INODE:
2321 case HAMMER2_BREF_TYPE_DATA:
2324 * leave chain->data NULL, set INITIAL
2326 KKASSERT(chain->data == NULL);
2327 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2332 * We are reattaching a previously deleted chain, possibly
2333 * under a new parent and possibly with a new key/keybits.
2334 * The chain does not have to be in a modified state. The
2335 * UPDATE flag will be set later on in this routine.
2337 * Do NOT mess with the current state of the INITIAL flag.
2339 chain->bref.key = key;
2340 chain->bref.keybits = keybits;
2341 if (chain->flags & HAMMER2_CHAIN_DELETED)
2342 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2343 KKASSERT(chain->parent == NULL);
2345 if (flags & HAMMER2_INSERT_PFSROOT)
2346 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2348 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2351 * Calculate how many entries we have in the blockref array and
2352 * determine if an indirect block is required.
2355 if (--maxloops == 0)
2356 panic("hammer2_chain_create: maxloops");
2358 switch(parent->bref.type) {
2359 case HAMMER2_BREF_TYPE_INODE:
2360 KKASSERT((parent->data->ipdata.meta.op_flags &
2361 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2362 KKASSERT(parent->data != NULL);
2363 base = &parent->data->ipdata.u.blockset.blockref[0];
2364 count = HAMMER2_SET_COUNT;
2366 case HAMMER2_BREF_TYPE_INDIRECT:
2367 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2368 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2371 base = &parent->data->npdata[0];
2372 count = parent->bytes / sizeof(hammer2_blockref_t);
2374 case HAMMER2_BREF_TYPE_VOLUME:
2375 KKASSERT(parent->data != NULL);
2376 base = &parent->data->voldata.sroot_blockset.blockref[0];
2377 count = HAMMER2_SET_COUNT;
2379 case HAMMER2_BREF_TYPE_FREEMAP:
2380 KKASSERT(parent->data != NULL);
2381 base = &parent->data->blkset.blockref[0];
2382 count = HAMMER2_SET_COUNT;
2385 panic("hammer2_chain_create: unrecognized blockref type: %d",
2393 * Make sure we've counted the brefs
2395 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2396 hammer2_chain_countbrefs(parent, base, count);
2398 KKASSERT(parent->core.live_count >= 0 &&
2399 parent->core.live_count <= count);
2402 * If no free blockref could be found we must create an indirect
2403 * block and move a number of blockrefs into it. With the parent
2404 * locked we can safely lock each child in order to delete+duplicate
2405 * it without causing a deadlock.
2407 * This may return the new indirect block or the old parent depending
2408 * on where the key falls. NULL is returned on error.
2410 if (parent->core.live_count == count) {
2411 hammer2_chain_t *nparent;
2413 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2414 mtid, type, &error);
2415 if (nparent == NULL) {
2417 hammer2_chain_drop(chain);
2421 if (parent != nparent) {
2422 hammer2_chain_unlock(parent);
2423 hammer2_chain_drop(parent);
2424 parent = *parentp = nparent;
2430 * Link the chain into its parent.
2432 if (chain->parent != NULL)
2433 panic("hammer2: hammer2_chain_create: chain already connected");
2434 KKASSERT(chain->parent == NULL);
2435 hammer2_chain_insert(parent, chain,
2436 HAMMER2_CHAIN_INSERT_SPIN |
2437 HAMMER2_CHAIN_INSERT_LIVE,
2442 * Mark the newly created chain modified. This will cause
2443 * UPDATE to be set and process the INITIAL flag.
2445 * Device buffers are not instantiated for DATA elements
2446 * as these are handled by logical buffers.
2448 * Indirect and freemap node indirect blocks are handled
2449 * by hammer2_chain_create_indirect() and not by this
2452 * Data for all other bref types is expected to be
2453 * instantiated (INODE, LEAF).
2455 switch(chain->bref.type) {
2456 case HAMMER2_BREF_TYPE_DATA:
2457 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2458 case HAMMER2_BREF_TYPE_INODE:
2459 hammer2_chain_modify(chain, mtid,
2460 HAMMER2_MODIFY_OPTDATA);
2464 * Remaining types are not supported by this function.
2465 * In particular, INDIRECT and LEAF_NODE types are
2466 * handled by create_indirect().
2468 panic("hammer2_chain_create: bad type: %d",
2475 * When reconnecting a chain we must set UPDATE and
2476 * setflush so the flush recognizes that it must update
2477 * the bref in the parent.
2479 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2480 hammer2_chain_ref(chain);
2481 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2486 * We must setflush(parent) to ensure that it recurses through to
2487 * chain. setflush(chain) might not work because ONFLUSH is possibly
2488 * already set in the chain (so it won't recurse up to set it in the
2491 hammer2_chain_setflush(parent);
2500 * Move the chain from its old parent to a new parent. The chain must have
2501 * already been deleted or already disconnected (or never associated) with
2502 * a parent. The chain is reassociated with the new parent and the deleted
2503 * flag will be cleared (no longer deleted). The chain's modification state
2506 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2507 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2508 * FULL. This typically means that the caller is creating the chain after
2509 * doing a hammer2_chain_lookup().
2511 * A non-NULL bref is typically passed when key and keybits must be overridden.
2512 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2513 * from a passed-in bref and uses the old chain's bref for everything else.
2515 * Neither (parent) or (chain) can be errored.
2517 * If (parent) is non-NULL then the new duplicated chain is inserted under
2520 * If (parent) is NULL then the newly duplicated chain is not inserted
2521 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2522 * passing into hammer2_chain_create() after this function returns).
2524 * WARNING! This function calls create which means it can insert indirect
2525 * blocks. This can cause other unrelated chains in the parent to
2526 * be moved to a newly inserted indirect block in addition to the
2530 hammer2_chain_rename(hammer2_blockref_t *bref,
2531 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2532 hammer2_tid_t mtid, int flags)
2535 hammer2_chain_t *parent;
2539 * WARNING! We should never resolve DATA to device buffers
2540 * (XXX allow it if the caller did?), and since
2541 * we currently do not have the logical buffer cache
2542 * buffer in-hand to fix its cached physical offset
2543 * we also force the modify code to not COW it. XXX
2546 KKASSERT(chain->parent == NULL);
2547 KKASSERT(chain->error == 0);
2550 * Now create a duplicate of the chain structure, associating
2551 * it with the same core, making it the same size, pointing it
2552 * to the same bref (the same media block).
2555 bref = &chain->bref;
2556 bytes = (hammer2_off_t)1 <<
2557 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2560 * If parent is not NULL the duplicated chain will be entered under
2561 * the parent and the UPDATE bit set to tell flush to update
2564 * We must setflush(parent) to ensure that it recurses through to
2565 * chain. setflush(chain) might not work because ONFLUSH is possibly
2566 * already set in the chain (so it won't recurse up to set it in the
2569 * Having both chains locked is extremely important for atomicy.
2571 if (parentp && (parent = *parentp) != NULL) {
2572 KKASSERT(hammer2_mtx_owned(&parent->lock));
2573 KKASSERT(parent->refs > 0);
2574 KKASSERT(parent->error == 0);
2576 hammer2_chain_create(parentp, &chain, chain->pmp,
2577 bref->key, bref->keybits, bref->type,
2578 chain->bytes, mtid, flags);
2579 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2580 hammer2_chain_setflush(*parentp);
2585 * Helper function for deleting chains.
2587 * The chain is removed from the live view (the RBTREE) as well as the parent's
2588 * blockmap. Both chain and its parent must be locked.
2590 * parent may not be errored. chain can be errored.
2593 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2594 hammer2_tid_t mtid, int flags)
2598 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2599 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2600 KKASSERT(chain->parent == parent);
2603 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2605 * Chain is blockmapped, so there must be a parent.
2606 * Atomically remove the chain from the parent and remove
2607 * the blockmap entry.
2609 hammer2_blockref_t *base;
2612 KKASSERT(parent != NULL);
2613 KKASSERT(parent->error == 0);
2614 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2615 hammer2_chain_modify(parent, mtid, HAMMER2_MODIFY_OPTDATA);
2618 * Calculate blockmap pointer
2620 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2621 hammer2_spin_ex(&parent->core.spin);
2623 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2624 atomic_add_int(&parent->core.live_count, -1);
2625 ++parent->core.generation;
2626 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2627 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2628 --parent->core.chain_count;
2629 chain->parent = NULL;
2631 switch(parent->bref.type) {
2632 case HAMMER2_BREF_TYPE_INODE:
2634 * Access the inode's block array. However, there
2635 * is no block array if the inode is flagged
2636 * DIRECTDATA. The DIRECTDATA case typicaly only
2637 * occurs when a hardlink has been shifted up the
2638 * tree and the original inode gets replaced with
2639 * an OBJTYPE_HARDLINK placeholding inode.
2642 (parent->data->ipdata.meta.op_flags &
2643 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2645 &parent->data->ipdata.u.blockset.blockref[0];
2649 count = HAMMER2_SET_COUNT;
2651 case HAMMER2_BREF_TYPE_INDIRECT:
2652 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2654 base = &parent->data->npdata[0];
2657 count = parent->bytes / sizeof(hammer2_blockref_t);
2659 case HAMMER2_BREF_TYPE_VOLUME:
2660 base = &parent->data->voldata.
2661 sroot_blockset.blockref[0];
2662 count = HAMMER2_SET_COUNT;
2664 case HAMMER2_BREF_TYPE_FREEMAP:
2665 base = &parent->data->blkset.blockref[0];
2666 count = HAMMER2_SET_COUNT;
2671 panic("hammer2_flush_pass2: "
2672 "unrecognized blockref type: %d",
2677 * delete blockmapped chain from its parent.
2679 * The parent is not affected by any statistics in chain
2680 * which are pending synchronization. That is, there is
2681 * nothing to undo in the parent since they have not yet
2682 * been incorporated into the parent.
2684 * The parent is affected by statistics stored in inodes.
2685 * Those have already been synchronized, so they must be
2686 * undone. XXX split update possible w/delete in middle?
2689 int cache_index = -1;
2690 hammer2_base_delete(parent, base, count,
2691 &cache_index, chain);
2693 hammer2_spin_unex(&parent->core.spin);
2694 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2696 * Chain is not blockmapped but a parent is present.
2697 * Atomically remove the chain from the parent. There is
2698 * no blockmap entry to remove.
2700 * Because chain was associated with a parent but not
2701 * synchronized, the chain's *_count_up fields contain
2702 * inode adjustment statistics which must be undone.
2704 hammer2_spin_ex(&parent->core.spin);
2705 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2706 atomic_add_int(&parent->core.live_count, -1);
2707 ++parent->core.generation;
2708 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2709 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2710 --parent->core.chain_count;
2711 chain->parent = NULL;
2712 hammer2_spin_unex(&parent->core.spin);
2715 * Chain is not blockmapped and has no parent. This
2716 * is a degenerate case.
2718 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2723 * Create an indirect block that covers one or more of the elements in the
2724 * current parent. Either returns the existing parent with no locking or
2725 * ref changes or returns the new indirect block locked and referenced
2726 * and leaving the original parent lock/ref intact as well.
2728 * If an error occurs, NULL is returned and *errorp is set to the error.
2730 * The returned chain depends on where the specified key falls.
2732 * The key/keybits for the indirect mode only needs to follow three rules:
2734 * (1) That all elements underneath it fit within its key space and
2736 * (2) That all elements outside it are outside its key space.
2738 * (3) When creating the new indirect block any elements in the current
2739 * parent that fit within the new indirect block's keyspace must be
2740 * moved into the new indirect block.
2742 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2743 * keyspace the the current parent, but lookup/iteration rules will
2744 * ensure (and must ensure) that rule (2) for all parents leading up
2745 * to the nearest inode or the root volume header is adhered to. This
2746 * is accomplished by always recursing through matching keyspaces in
2747 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2749 * The current implementation calculates the current worst-case keyspace by
2750 * iterating the current parent and then divides it into two halves, choosing
2751 * whichever half has the most elements (not necessarily the half containing
2752 * the requested key).
2754 * We can also opt to use the half with the least number of elements. This
2755 * causes lower-numbered keys (aka logical file offsets) to recurse through
2756 * fewer indirect blocks and higher-numbered keys to recurse through more.
2757 * This also has the risk of not moving enough elements to the new indirect
2758 * block and being forced to create several indirect blocks before the element
2761 * Must be called with an exclusively locked parent.
2763 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2764 hammer2_key_t *keyp, int keybits,
2765 hammer2_blockref_t *base, int count);
2766 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2767 hammer2_key_t *keyp, int keybits,
2768 hammer2_blockref_t *base, int count);
2771 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2772 hammer2_key_t create_key, int create_bits,
2773 hammer2_tid_t mtid, int for_type, int *errorp)
2776 hammer2_blockref_t *base;
2777 hammer2_blockref_t *bref;
2778 hammer2_blockref_t bcopy;
2779 hammer2_chain_t *chain;
2780 hammer2_chain_t *ichain;
2781 hammer2_chain_t dummy;
2782 hammer2_key_t key = create_key;
2783 hammer2_key_t key_beg;
2784 hammer2_key_t key_end;
2785 hammer2_key_t key_next;
2786 int keybits = create_bits;
2793 int maxloops = 300000;
2796 * Calculate the base blockref pointer or NULL if the chain
2797 * is known to be empty. We need to calculate the array count
2798 * for RB lookups either way.
2802 KKASSERT(hammer2_mtx_owned(&parent->lock));
2804 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2805 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2808 switch(parent->bref.type) {
2809 case HAMMER2_BREF_TYPE_INODE:
2810 count = HAMMER2_SET_COUNT;
2812 case HAMMER2_BREF_TYPE_INDIRECT:
2813 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2814 count = parent->bytes / sizeof(hammer2_blockref_t);
2816 case HAMMER2_BREF_TYPE_VOLUME:
2817 count = HAMMER2_SET_COUNT;
2819 case HAMMER2_BREF_TYPE_FREEMAP:
2820 count = HAMMER2_SET_COUNT;
2823 panic("hammer2_chain_create_indirect: "
2824 "unrecognized blockref type: %d",
2830 switch(parent->bref.type) {
2831 case HAMMER2_BREF_TYPE_INODE:
2832 base = &parent->data->ipdata.u.blockset.blockref[0];
2833 count = HAMMER2_SET_COUNT;
2835 case HAMMER2_BREF_TYPE_INDIRECT:
2836 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2837 base = &parent->data->npdata[0];
2838 count = parent->bytes / sizeof(hammer2_blockref_t);
2840 case HAMMER2_BREF_TYPE_VOLUME:
2841 base = &parent->data->voldata.
2842 sroot_blockset.blockref[0];
2843 count = HAMMER2_SET_COUNT;
2845 case HAMMER2_BREF_TYPE_FREEMAP:
2846 base = &parent->data->blkset.blockref[0];
2847 count = HAMMER2_SET_COUNT;
2850 panic("hammer2_chain_create_indirect: "
2851 "unrecognized blockref type: %d",
2859 * dummy used in later chain allocation (no longer used for lookups).
2861 bzero(&dummy, sizeof(dummy));
2864 * When creating an indirect block for a freemap node or leaf
2865 * the key/keybits must be fitted to static radix levels because
2866 * particular radix levels use particular reserved blocks in the
2869 * This routine calculates the key/radix of the indirect block
2870 * we need to create, and whether it is on the high-side or the
2873 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2874 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2875 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2878 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2883 * Normalize the key for the radix being represented, keeping the
2884 * high bits and throwing away the low bits.
2886 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2889 * How big should our new indirect block be? It has to be at least
2890 * as large as its parent.
2892 * The freemap uses a specific indirect block size.
2894 * The first indirect block level down from an inode typically
2895 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2897 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2898 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2899 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2900 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2901 nbytes = HAMMER2_IND_BYTES_MIN;
2903 nbytes = HAMMER2_IND_BYTES_MAX;
2905 if (nbytes < count * sizeof(hammer2_blockref_t)) {
2906 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2907 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2908 nbytes = count * sizeof(hammer2_blockref_t);
2912 * Ok, create our new indirect block
2914 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2915 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2916 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2918 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2920 dummy.bref.key = key;
2921 dummy.bref.keybits = keybits;
2922 dummy.bref.data_off = hammer2_getradix(nbytes);
2923 dummy.bref.methods = parent->bref.methods;
2925 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2926 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2927 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2928 /* ichain has one ref at this point */
2931 * We have to mark it modified to allocate its block, but use
2932 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2933 * it won't be acted upon by the flush code.
2935 hammer2_chain_modify(ichain, mtid, HAMMER2_MODIFY_OPTDATA);
2938 * Iterate the original parent and move the matching brefs into
2939 * the new indirect block.
2941 * XXX handle flushes.
2944 key_end = HAMMER2_KEY_MAX;
2946 hammer2_spin_ex(&parent->core.spin);
2951 if (++loops > 100000) {
2952 hammer2_spin_unex(&parent->core.spin);
2953 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2954 reason, parent, base, count, key_next);
2958 * NOTE: spinlock stays intact, returned chain (if not NULL)
2959 * is not referenced or locked which means that we
2960 * cannot safely check its flagged / deletion status
2963 chain = hammer2_combined_find(parent, base, count,
2964 &cache_index, &key_next,
2967 generation = parent->core.generation;
2970 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2973 * Skip keys that are not within the key/radix of the new
2974 * indirect block. They stay in the parent.
2976 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2977 (key ^ bref->key)) != 0) {
2978 goto next_key_spinlocked;
2982 * Load the new indirect block by acquiring the related
2983 * chains (potentially from media as it might not be
2984 * in-memory). Then move it to the new parent (ichain)
2985 * via DELETE-DUPLICATE.
2987 * chain is referenced but not locked. We must lock the
2988 * chain to obtain definitive DUPLICATED/DELETED state
2992 * Use chain already present in the RBTREE
2994 hammer2_chain_ref(chain);
2995 hammer2_spin_unex(&parent->core.spin);
2996 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2999 * Get chain for blockref element. _get returns NULL
3000 * on insertion race.
3003 hammer2_spin_unex(&parent->core.spin);
3004 chain = hammer2_chain_get(parent, generation, &bcopy);
3005 if (chain == NULL) {
3007 hammer2_spin_ex(&parent->core.spin);
3010 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3011 kprintf("REASON 2\n");
3013 hammer2_chain_drop(chain);
3014 hammer2_spin_ex(&parent->core.spin);
3017 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3021 * This is always live so if the chain has been deleted
3022 * we raced someone and we have to retry.
3024 * NOTE: Lookups can race delete-duplicate because
3025 * delete-duplicate does not lock the parent's core
3026 * (they just use the spinlock on the core). We must
3027 * check for races by comparing the DUPLICATED flag before
3028 * releasing the spinlock with the flag after locking the
3031 * (note reversed logic for this one)
3033 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3034 hammer2_chain_unlock(chain);
3035 hammer2_chain_drop(chain);
3040 * Shift the chain to the indirect block.
3042 * WARNING! No reason for us to load chain data, pass NOSTATS
3043 * to prevent delete/insert from trying to access
3044 * inode stats (and thus asserting if there is no
3045 * chain->data loaded).
3047 hammer2_chain_delete(parent, chain, mtid, 0);
3048 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3049 hammer2_chain_unlock(chain);
3050 hammer2_chain_drop(chain);
3051 KKASSERT(parent->refs > 0);
3054 hammer2_spin_ex(&parent->core.spin);
3055 next_key_spinlocked:
3056 if (--maxloops == 0)
3057 panic("hammer2_chain_create_indirect: maxloops");
3059 if (key_next == 0 || key_next > key_end)
3064 hammer2_spin_unex(&parent->core.spin);
3067 * Insert the new indirect block into the parent now that we've
3068 * cleared out some entries in the parent. We calculated a good
3069 * insertion index in the loop above (ichain->index).
3071 * We don't have to set UPDATE here because we mark ichain
3072 * modified down below (so the normal modified -> flush -> set-moved
3073 * sequence applies).
3075 * The insertion shouldn't race as this is a completely new block
3076 * and the parent is locked.
3078 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3079 hammer2_chain_insert(parent, ichain,
3080 HAMMER2_CHAIN_INSERT_SPIN |
3081 HAMMER2_CHAIN_INSERT_LIVE,
3085 * Make sure flushes propogate after our manual insertion.
3087 hammer2_chain_setflush(ichain);
3088 hammer2_chain_setflush(parent);
3091 * Figure out what to return.
3093 if (~(((hammer2_key_t)1 << keybits) - 1) &
3094 (create_key ^ key)) {
3096 * Key being created is outside the key range,
3097 * return the original parent.
3099 hammer2_chain_unlock(ichain);
3100 hammer2_chain_drop(ichain);
3103 * Otherwise its in the range, return the new parent.
3104 * (leave both the new and old parent locked).
3113 * Calculate the keybits and highside/lowside of the freemap node the
3114 * caller is creating.
3116 * This routine will specify the next higher-level freemap key/radix
3117 * representing the lowest-ordered set. By doing so, eventually all
3118 * low-ordered sets will be moved one level down.
3120 * We have to be careful here because the freemap reserves a limited
3121 * number of blocks for a limited number of levels. So we can't just
3122 * push indiscriminately.
3125 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3126 int keybits, hammer2_blockref_t *base, int count)
3128 hammer2_chain_t *chain;
3129 hammer2_blockref_t *bref;
3131 hammer2_key_t key_beg;
3132 hammer2_key_t key_end;
3133 hammer2_key_t key_next;
3137 int maxloops = 300000;
3145 * Calculate the range of keys in the array being careful to skip
3146 * slots which are overridden with a deletion.
3149 key_end = HAMMER2_KEY_MAX;
3151 hammer2_spin_ex(&parent->core.spin);
3154 if (--maxloops == 0) {
3155 panic("indkey_freemap shit %p %p:%d\n",
3156 parent, base, count);
3158 chain = hammer2_combined_find(parent, base, count,
3159 &cache_index, &key_next,
3170 * Skip deleted chains.
3172 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3173 if (key_next == 0 || key_next > key_end)
3180 * Use the full live (not deleted) element for the scan
3181 * iteration. HAMMER2 does not allow partial replacements.
3183 * XXX should be built into hammer2_combined_find().
3185 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3187 if (keybits > bref->keybits) {
3189 keybits = bref->keybits;
3190 } else if (keybits == bref->keybits && bref->key < key) {
3197 hammer2_spin_unex(&parent->core.spin);
3200 * Return the keybits for a higher-level FREEMAP_NODE covering
3204 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3205 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3207 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3208 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3210 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3211 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3213 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3214 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3216 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3217 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3219 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3220 panic("hammer2_chain_indkey_freemap: level too high");
3223 panic("hammer2_chain_indkey_freemap: bad radix");
3232 * Calculate the keybits and highside/lowside of the indirect block the
3233 * caller is creating.
3236 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3237 int keybits, hammer2_blockref_t *base, int count)
3239 hammer2_blockref_t *bref;
3240 hammer2_chain_t *chain;
3241 hammer2_key_t key_beg;
3242 hammer2_key_t key_end;
3243 hammer2_key_t key_next;
3249 int maxloops = 300000;
3256 * Calculate the range of keys in the array being careful to skip
3257 * slots which are overridden with a deletion. Once the scan
3258 * completes we will cut the key range in half and shift half the
3259 * range into the new indirect block.
3262 key_end = HAMMER2_KEY_MAX;
3264 hammer2_spin_ex(&parent->core.spin);
3267 if (--maxloops == 0) {
3268 panic("indkey_freemap shit %p %p:%d\n",
3269 parent, base, count);
3271 chain = hammer2_combined_find(parent, base, count,
3272 &cache_index, &key_next,
3283 * NOTE: No need to check DUPLICATED here because we do
3284 * not release the spinlock.
3286 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3287 if (key_next == 0 || key_next > key_end)
3294 * Use the full live (not deleted) element for the scan
3295 * iteration. HAMMER2 does not allow partial replacements.
3297 * XXX should be built into hammer2_combined_find().
3299 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3302 * Expand our calculated key range (key, keybits) to fit
3303 * the scanned key. nkeybits represents the full range
3304 * that we will later cut in half (two halves @ nkeybits - 1).
3307 if (nkeybits < bref->keybits) {
3308 if (bref->keybits > 64) {
3309 kprintf("bad bref chain %p bref %p\n",
3313 nkeybits = bref->keybits;
3315 while (nkeybits < 64 &&
3316 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3317 (key ^ bref->key)) != 0) {
3322 * If the new key range is larger we have to determine
3323 * which side of the new key range the existing keys fall
3324 * under by checking the high bit, then collapsing the
3325 * locount into the hicount or vise-versa.
3327 if (keybits != nkeybits) {
3328 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3339 * The newly scanned key will be in the lower half or the
3340 * upper half of the (new) key range.
3342 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3351 hammer2_spin_unex(&parent->core.spin);
3352 bref = NULL; /* now invalid (safety) */
3355 * Adjust keybits to represent half of the full range calculated
3356 * above (radix 63 max)
3361 * Select whichever half contains the most elements. Theoretically
3362 * we can select either side as long as it contains at least one
3363 * element (in order to ensure that a free slot is present to hold
3364 * the indirect block).
3366 if (hammer2_indirect_optimize) {
3368 * Insert node for least number of keys, this will arrange
3369 * the first few blocks of a large file or the first few
3370 * inodes in a directory with fewer indirect blocks when
3373 if (hicount < locount && hicount != 0)
3374 key |= (hammer2_key_t)1 << keybits;
3376 key &= ~(hammer2_key_t)1 << keybits;
3379 * Insert node for most number of keys, best for heavily
3382 if (hicount > locount)
3383 key |= (hammer2_key_t)1 << keybits;
3385 key &= ~(hammer2_key_t)1 << keybits;
3393 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3396 * Both parent and chain must be locked exclusively.
3398 * This function will modify the parent if the blockref requires removal
3399 * from the parent's block table.
3401 * This function is NOT recursive. Any entity already pushed into the
3402 * chain (such as an inode) may still need visibility into its contents,
3403 * as well as the ability to read and modify the contents. For example,
3404 * for an unlinked file which is still open.
3407 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3408 hammer2_tid_t mtid, int flags)
3410 KKASSERT(hammer2_mtx_owned(&chain->lock));
3413 * Nothing to do if already marked.
3415 * We need the spinlock on the core whos RBTREE contains chain
3416 * to protect against races.
3418 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3419 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3420 chain->parent == parent);
3421 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3425 * To avoid losing track of a permanent deletion we add the chain
3426 * to the delayed flush queue. If were to flush it right now the
3427 * parent would end up in a modified state and generate I/O.
3428 * The delayed queue gives the parent a chance to be deleted to
3431 if (flags & HAMMER2_DELETE_PERMANENT) {
3432 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3433 hammer2_delayed_flush(chain);
3435 /* XXX might not be needed */
3436 hammer2_chain_setflush(chain);
3441 * Returns the index of the nearest element in the blockref array >= elm.
3442 * Returns (count) if no element could be found.
3444 * Sets *key_nextp to the next key for loop purposes but does not modify
3445 * it if the next key would be higher than the current value of *key_nextp.
3446 * Note that *key_nexp can overflow to 0, which should be tested by the
3449 * (*cache_indexp) is a heuristic and can be any value without effecting
3452 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3453 * held through the operation.
3456 hammer2_base_find(hammer2_chain_t *parent,
3457 hammer2_blockref_t *base, int count,
3458 int *cache_indexp, hammer2_key_t *key_nextp,
3459 hammer2_key_t key_beg, hammer2_key_t key_end)
3461 hammer2_blockref_t *scan;
3462 hammer2_key_t scan_end;
3467 * Require the live chain's already have their core's counted
3468 * so we can optimize operations.
3470 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3475 if (count == 0 || base == NULL)
3479 * Sequential optimization using *cache_indexp. This is the most
3482 * We can avoid trailing empty entries on live chains, otherwise
3483 * we might have to check the whole block array.
3487 limit = parent->core.live_zero;
3492 KKASSERT(i < count);
3498 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3505 * Search forwards, stop when we find a scan element which
3506 * encloses the key or until we know that there are no further
3510 if (scan->type != 0) {
3511 scan_end = scan->key +
3512 ((hammer2_key_t)1 << scan->keybits) - 1;
3513 if (scan->key > key_beg || scan_end >= key_beg)
3526 scan_end = scan->key +
3527 ((hammer2_key_t)1 << scan->keybits);
3528 if (scan_end && (*key_nextp > scan_end ||
3530 *key_nextp = scan_end;
3538 * Do a combined search and return the next match either from the blockref
3539 * array or from the in-memory chain. Sets *bresp to the returned bref in
3540 * both cases, or sets it to NULL if the search exhausted. Only returns
3541 * a non-NULL chain if the search matched from the in-memory chain.
3543 * When no in-memory chain has been found and a non-NULL bref is returned
3547 * The returned chain is not locked or referenced. Use the returned bref
3548 * to determine if the search exhausted or not. Iterate if the base find
3549 * is chosen but matches a deleted chain.
3551 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3552 * held through the operation.
3554 static hammer2_chain_t *
3555 hammer2_combined_find(hammer2_chain_t *parent,
3556 hammer2_blockref_t *base, int count,
3557 int *cache_indexp, hammer2_key_t *key_nextp,
3558 hammer2_key_t key_beg, hammer2_key_t key_end,
3559 hammer2_blockref_t **bresp)
3561 hammer2_blockref_t *bref;
3562 hammer2_chain_t *chain;
3566 * Lookup in block array and in rbtree.
3568 *key_nextp = key_end + 1;
3569 i = hammer2_base_find(parent, base, count, cache_indexp,
3570 key_nextp, key_beg, key_end);
3571 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3576 if (i == count && chain == NULL) {
3582 * Only chain matched.
3585 bref = &chain->bref;
3590 * Only blockref matched.
3592 if (chain == NULL) {
3598 * Both in-memory and blockref matched, select the nearer element.
3600 * If both are flush with the left-hand side or both are the
3601 * same distance away, select the chain. In this situation the
3602 * chain must have been loaded from the matching blockmap.
3604 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3605 chain->bref.key == base[i].key) {
3606 KKASSERT(chain->bref.key == base[i].key);
3607 bref = &chain->bref;
3612 * Select the nearer key
3614 if (chain->bref.key < base[i].key) {
3615 bref = &chain->bref;
3622 * If the bref is out of bounds we've exhausted our search.
3625 if (bref->key > key_end) {
3635 * Locate the specified block array element and delete it. The element
3638 * The spin lock on the related chain must be held.
3640 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3641 * need to be adjusted when we commit the media change.
3644 hammer2_base_delete(hammer2_chain_t *parent,
3645 hammer2_blockref_t *base, int count,
3646 int *cache_indexp, hammer2_chain_t *chain)
3648 hammer2_blockref_t *elm = &chain->bref;
3649 hammer2_key_t key_next;
3653 * Delete element. Expect the element to exist.
3655 * XXX see caller, flush code not yet sophisticated enough to prevent
3656 * re-flushed in some cases.
3658 key_next = 0; /* max range */
3659 i = hammer2_base_find(parent, base, count, cache_indexp,
3660 &key_next, elm->key, elm->key);
3661 if (i == count || base[i].type == 0 ||
3662 base[i].key != elm->key ||
3663 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3664 base[i].keybits != elm->keybits)) {
3665 hammer2_spin_unex(&parent->core.spin);
3666 panic("delete base %p element not found at %d/%d elm %p\n",
3667 base, i, count, elm);
3672 * Update stats and zero the entry
3674 parent->bref.data_count -= base[i].data_count;
3675 parent->bref.data_count -= (hammer2_off_t)1 <<
3676 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3677 parent->bref.inode_count -= base[i].inode_count;
3678 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3679 parent->bref.inode_count -= 1;
3681 bzero(&base[i], sizeof(*base));
3684 * We can only optimize parent->core.live_zero for live chains.
3686 if (parent->core.live_zero == i + 1) {
3687 while (--i >= 0 && base[i].type == 0)
3689 parent->core.live_zero = i + 1;
3693 * Clear appropriate blockmap flags in chain.
3695 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3696 HAMMER2_CHAIN_BMAPUPD);
3700 * Insert the specified element. The block array must not already have the
3701 * element and must have space available for the insertion.
3703 * The spin lock on the related chain must be held.
3705 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3706 * need to be adjusted when we commit the media change.
3709 hammer2_base_insert(hammer2_chain_t *parent,
3710 hammer2_blockref_t *base, int count,
3711 int *cache_indexp, hammer2_chain_t *chain)
3713 hammer2_blockref_t *elm = &chain->bref;
3714 hammer2_key_t key_next;
3723 * Insert new element. Expect the element to not already exist
3724 * unless we are replacing it.
3726 * XXX see caller, flush code not yet sophisticated enough to prevent
3727 * re-flushed in some cases.
3729 key_next = 0; /* max range */
3730 i = hammer2_base_find(parent, base, count, cache_indexp,
3731 &key_next, elm->key, elm->key);
3734 * Shortcut fill optimization, typical ordered insertion(s) may not
3737 KKASSERT(i >= 0 && i <= count);
3740 * Set appropriate blockmap flags in chain.
3742 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3745 * Update stats and zero the entry
3747 parent->bref.data_count += elm->data_count;
3748 parent->bref.data_count += (hammer2_off_t)1 <<
3749 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3750 parent->bref.inode_count += elm->inode_count;
3751 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3752 parent->bref.inode_count += 1;
3756 * We can only optimize parent->core.live_zero for live chains.
3758 if (i == count && parent->core.live_zero < count) {
3759 i = parent->core.live_zero++;
3764 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3765 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3766 hammer2_spin_unex(&parent->core.spin);
3767 panic("insert base %p overlapping elements at %d elm %p\n",
3772 * Try to find an empty slot before or after.
3776 while (j > 0 || k < count) {
3778 if (j >= 0 && base[j].type == 0) {
3782 bcopy(&base[j+1], &base[j],
3783 (i - j - 1) * sizeof(*base));
3789 if (k < count && base[k].type == 0) {
3790 bcopy(&base[i], &base[i+1],
3791 (k - i) * sizeof(hammer2_blockref_t));
3795 * We can only update parent->core.live_zero for live
3798 if (parent->core.live_zero <= k)
3799 parent->core.live_zero = k + 1;
3804 panic("hammer2_base_insert: no room!");
3811 for (l = 0; l < count; ++l) {
3813 key_next = base[l].key +
3814 ((hammer2_key_t)1 << base[l].keybits) - 1;
3818 while (++l < count) {
3820 if (base[l].key <= key_next)
3821 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3822 key_next = base[l].key +
3823 ((hammer2_key_t)1 << base[l].keybits) - 1;
3833 * Sort the blockref array for the chain. Used by the flush code to
3834 * sort the blockref[] array.
3836 * The chain must be exclusively locked AND spin-locked.
3838 typedef hammer2_blockref_t *hammer2_blockref_p;
3842 hammer2_base_sort_callback(const void *v1, const void *v2)
3844 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3845 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3848 * Make sure empty elements are placed at the end of the array
3850 if (bref1->type == 0) {
3851 if (bref2->type == 0)
3854 } else if (bref2->type == 0) {
3861 if (bref1->key < bref2->key)
3863 if (bref1->key > bref2->key)
3869 hammer2_base_sort(hammer2_chain_t *chain)
3871 hammer2_blockref_t *base;
3874 switch(chain->bref.type) {
3875 case HAMMER2_BREF_TYPE_INODE:
3877 * Special shortcut for embedded data returns the inode
3878 * itself. Callers must detect this condition and access
3879 * the embedded data (the strategy code does this for us).
3881 * This is only applicable to regular files and softlinks.
3883 if (chain->data->ipdata.meta.op_flags &
3884 HAMMER2_OPFLAG_DIRECTDATA) {
3887 base = &chain->data->ipdata.u.blockset.blockref[0];
3888 count = HAMMER2_SET_COUNT;
3890 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3891 case HAMMER2_BREF_TYPE_INDIRECT:
3893 * Optimize indirect blocks in the INITIAL state to avoid
3896 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3897 base = &chain->data->npdata[0];
3898 count = chain->bytes / sizeof(hammer2_blockref_t);
3900 case HAMMER2_BREF_TYPE_VOLUME:
3901 base = &chain->data->voldata.sroot_blockset.blockref[0];
3902 count = HAMMER2_SET_COUNT;
3904 case HAMMER2_BREF_TYPE_FREEMAP:
3905 base = &chain->data->blkset.blockref[0];
3906 count = HAMMER2_SET_COUNT;
3909 kprintf("hammer2_chain_lookup: unrecognized "
3910 "blockref(A) type: %d",
3913 tsleep(&base, 0, "dead", 0);
3914 panic("hammer2_chain_lookup: unrecognized "
3915 "blockref(A) type: %d",
3917 base = NULL; /* safety */
3918 count = 0; /* safety */
3920 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3926 * Chain memory management
3929 hammer2_chain_wait(hammer2_chain_t *chain)
3931 tsleep(chain, 0, "chnflw", 1);
3934 const hammer2_media_data_t *
3935 hammer2_chain_rdata(hammer2_chain_t *chain)
3937 KKASSERT(chain->data != NULL);
3938 return (chain->data);
3941 hammer2_media_data_t *
3942 hammer2_chain_wdata(hammer2_chain_t *chain)
3944 KKASSERT(chain->data != NULL);
3945 return (chain->data);
3949 * Set the check data for a chain. This can be a heavy-weight operation
3950 * and typically only runs on-flush. For file data check data is calculated
3951 * when the logical buffers are flushed.
3954 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3956 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3958 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3959 case HAMMER2_CHECK_NONE:
3961 case HAMMER2_CHECK_DISABLED:
3963 case HAMMER2_CHECK_ISCSI32:
3964 chain->bref.check.iscsi32.value =
3965 hammer2_icrc32(bdata, chain->bytes);
3967 case HAMMER2_CHECK_CRC64:
3968 chain->bref.check.crc64.value = 0;
3971 case HAMMER2_CHECK_SHA192:
3973 SHA256_CTX hash_ctx;
3975 uint8_t digest[SHA256_DIGEST_LENGTH];
3976 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3979 SHA256_Init(&hash_ctx);
3980 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3981 SHA256_Final(u.digest, &hash_ctx);
3982 u.digest64[2] ^= u.digest64[3];
3984 chain->bref.check.sha192.data,
3985 sizeof(chain->bref.check.sha192.data));
3988 case HAMMER2_CHECK_FREEMAP:
3989 chain->bref.check.freemap.icrc32 =
3990 hammer2_icrc32(bdata, chain->bytes);
3993 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3994 chain->bref.methods);
4000 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4004 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4007 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4008 case HAMMER2_CHECK_NONE:
4011 case HAMMER2_CHECK_DISABLED:
4014 case HAMMER2_CHECK_ISCSI32:
4015 r = (chain->bref.check.iscsi32.value ==
4016 hammer2_icrc32(bdata, chain->bytes));
4018 case HAMMER2_CHECK_CRC64:
4019 r = (chain->bref.check.crc64.value == 0);
4022 case HAMMER2_CHECK_SHA192:
4024 SHA256_CTX hash_ctx;
4026 uint8_t digest[SHA256_DIGEST_LENGTH];
4027 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4030 SHA256_Init(&hash_ctx);
4031 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4032 SHA256_Final(u.digest, &hash_ctx);
4033 u.digest64[2] ^= u.digest64[3];
4035 chain->bref.check.sha192.data,
4036 sizeof(chain->bref.check.sha192.data)) == 0) {
4043 case HAMMER2_CHECK_FREEMAP:
4044 r = (chain->bref.check.freemap.icrc32 ==
4045 hammer2_icrc32(bdata, chain->bytes));
4047 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4048 chain->bref.check.freemap.icrc32,
4049 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4051 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4052 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4057 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4058 chain->bref.methods);
4066 * The caller presents a shared-locked (parent, chain) where the chain
4067 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4068 * structure representing the inode locked to prevent
4069 * consolidation/deconsolidation races.
4071 * We locate the hardlink in the current or a common parent directory.
4073 * If we are unable to locate the hardlink, EIO is returned and
4074 * (*chainp) is unlocked and dropped.
4077 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4078 hammer2_chain_t **parentp,
4079 hammer2_chain_t **chainp,
4082 hammer2_chain_t *parent;
4083 hammer2_chain_t *rchain;
4084 hammer2_key_t key_dummy;
4086 int cache_index = -1;
4089 * Obtain the key for the hardlink from *chainp.
4092 lhc = rchain->data->ipdata.meta.inum;
4093 hammer2_chain_unlock(rchain);
4094 hammer2_chain_drop(rchain);
4099 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4101 &cache_index, flags);
4106 * Iterate parents, handle parent rename races by retrying
4114 parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4117 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4119 if (parent->parent == NULL)
4121 parent = parent->parent;
4122 hammer2_chain_ref(parent);
4123 hammer2_chain_unlock(*parentp);
4124 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4126 if ((*parentp)->parent == parent) {
4127 hammer2_chain_drop(*parentp);
4130 hammer2_chain_unlock(parent);
4131 hammer2_chain_drop(parent);
4132 hammer2_chain_lock(*parentp,
4133 HAMMER2_RESOLVE_ALWAYS |
4135 parent = NULL; /* safety */
4143 return (rchain ? EINVAL : 0);
4147 * Used by the bulkscan code to snapshot the synchronized storage for
4148 * a volume, allowing it to be scanned concurrently against normal
4152 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4154 hammer2_chain_t *copy;
4156 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4157 switch(chain->bref.type) {
4158 case HAMMER2_BREF_TYPE_VOLUME:
4159 copy->data = kmalloc(sizeof(copy->data->voldata),
4162 hammer2_spin_ex(&chain->core.spin);
4163 copy->data->voldata = chain->data->voldata;
4164 hammer2_spin_unex(&chain->core.spin);
4166 case HAMMER2_BREF_TYPE_FREEMAP:
4167 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4170 hammer2_spin_ex(&chain->core.spin);
4171 copy->data->blkset = chain->data->blkset;
4172 hammer2_spin_unex(&chain->core.spin);
4181 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4183 switch(copy->bref.type) {
4184 case HAMMER2_BREF_TYPE_VOLUME:
4185 case HAMMER2_BREF_TYPE_FREEMAP:
4186 KKASSERT(copy->data);
4187 kfree(copy->data, copy->hmp->mchain);
4192 hammer2_chain_drop(copy);
4196 * Create a snapshot of the specified {parent, ochain} with the specified
4197 * label. The originating hammer2_inode must be exclusively locked for
4200 * The ioctl code has already synced the filesystem.
4203 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4207 const hammer2_inode_data_t *ripdata;
4208 hammer2_inode_data_t *wipdata;
4209 hammer2_chain_t *nchain;
4210 hammer2_inode_t *nip;
4219 kprintf("snapshot %s\n", pmp->name);
4221 name_len = strlen(pmp->name);
4222 lhc = hammer2_dirhash(pmp->name, name_len);
4227 ripdata = &chain->data->ipdata;
4229 opfs_clid = ripdata->meta.pfs_clid;
4234 * Create the snapshot directory under the super-root
4236 * Set PFS type, generate a unique filesystem id, and generate
4237 * a cluster id. Use the same clid when snapshotting a PFS root,
4238 * which theoretically allows the snapshot to be used as part of
4239 * the same cluster (perhaps as a cache).
4241 * Copy the (flushed) blockref array. Theoretically we could use
4242 * chain_duplicate() but it becomes difficult to disentangle
4243 * the shared core so for now just brute-force it.
4248 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4249 pmp->name, name_len, 0,
4251 HAMMER2_INSERT_PFSROOT, &error);
4254 hammer2_inode_modify(nip);
4255 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4256 hammer2_chain_modify(nchain, mtid, 0);
4257 wipdata = &nchain->data->ipdata;
4259 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4260 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4261 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4262 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4265 * Give the snapshot its own private cluster id. As a
4266 * snapshot no further synchronization with the original
4267 * cluster will be done.
4270 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4271 nip->meta.pfs_clid = opfs_clid;
4273 kern_uuidgen(&nip->meta.pfs_clid, 1);
4275 kern_uuidgen(&nip->meta.pfs_clid, 1);
4276 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4278 /* XXX hack blockset copy */
4279 /* XXX doesn't work with real cluster */
4280 wipdata->meta = nip->meta;
4281 wipdata->u.blockset = ripdata->u.blockset;
4282 hammer2_flush(nchain, 1);
4283 hammer2_chain_unlock(nchain);
4284 hammer2_chain_drop(nchain);
4285 hammer2_inode_unlock(nip);