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 hammer2_chain_modify(hammer2_chain_t *chain,
1064 hammer2_tid_t mtid, int flags)
1066 hammer2_blockref_t obref;
1075 obref = chain->bref;
1076 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1079 * Data is not optional for freemap chains (we must always be sure
1080 * to copy the data on COW storage allocations).
1082 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1083 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1084 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1085 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1089 * Data must be resolved if already assigned, unless explicitly
1090 * flagged otherwise.
1092 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1093 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1094 hammer2_chain_load_data(chain);
1098 * Set MODIFIED to indicate that the chain has been modified.
1099 * Set UPDATE to ensure that the blockref is updated in the parent.
1101 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1102 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1103 hammer2_chain_ref(chain);
1104 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1109 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1110 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1111 hammer2_chain_ref(chain);
1115 * The modification or re-modification requires an allocation and
1118 * We normally always allocate new storage here. If storage exists
1119 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1121 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1122 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1123 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1125 hammer2_freemap_alloc(chain, chain->bytes);
1126 /* XXX failed allocation */
1131 * Update mirror_tid and modify_tid. modify_tid is only updated
1132 * automatically by this function when used from the frontend.
1133 * Flushes and synchronization adjust the flag manually.
1135 * NOTE: chain->pmp could be the device spmp.
1137 KKASSERT(mtid != 0);
1138 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1139 chain->bref.modify_tid = mtid;
1142 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1143 * requires updating as well as to tell the delete code that the
1144 * chain's blockref might not exactly match (in terms of physical size
1145 * or block offset) the one in the parent's blocktable. The base key
1146 * of course will still match.
1148 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1149 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1152 * Short-cut data blocks which the caller does not need an actual
1153 * data reference to (aka OPTDATA), as long as the chain does not
1154 * already have a data pointer to the data. This generally means
1155 * that the modifications are being done via the logical buffer cache.
1156 * The INITIAL flag relates only to the device data buffer and thus
1157 * remains unchange in this situation.
1159 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1160 (flags & HAMMER2_MODIFY_OPTDATA) &&
1161 chain->data == NULL) {
1166 * Clearing the INITIAL flag (for indirect blocks) indicates that
1167 * we've processed the uninitialized storage allocation.
1169 * If this flag is already clear we are likely in a copy-on-write
1170 * situation but we have to be sure NOT to bzero the storage if
1171 * no data is present.
1173 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1174 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1181 * Instantiate data buffer and possibly execute COW operation
1183 switch(chain->bref.type) {
1184 case HAMMER2_BREF_TYPE_VOLUME:
1185 case HAMMER2_BREF_TYPE_FREEMAP:
1187 * The data is embedded, no copy-on-write operation is
1190 KKASSERT(chain->dio == NULL);
1192 case HAMMER2_BREF_TYPE_INODE:
1193 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1194 case HAMMER2_BREF_TYPE_DATA:
1195 case HAMMER2_BREF_TYPE_INDIRECT:
1196 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1198 * Perform the copy-on-write operation
1200 * zero-fill or copy-on-write depending on whether
1201 * chain->data exists or not and set the dirty state for
1202 * the new buffer. hammer2_io_new() will handle the
1205 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1208 error = hammer2_io_new(hmp, chain->bref.data_off,
1209 chain->bytes, &dio);
1211 error = hammer2_io_bread(hmp, chain->bref.data_off,
1212 chain->bytes, &dio);
1214 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1217 * If an I/O error occurs make sure callers cannot accidently
1218 * modify the old buffer's contents and corrupt the filesystem.
1221 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1223 chain->error = HAMMER2_ERROR_IO;
1224 hammer2_io_brelse(&dio);
1225 hammer2_io_brelse(&chain->dio);
1230 bdata = hammer2_io_data(dio, chain->bref.data_off);
1233 KKASSERT(chain->dio != NULL);
1234 if (chain->data != (void *)bdata) {
1235 bcopy(chain->data, bdata, chain->bytes);
1237 } else if (wasinitial == 0) {
1239 * We have a problem. We were asked to COW but
1240 * we don't have any data to COW with!
1242 panic("hammer2_chain_modify: having a COW %p\n",
1247 * Retire the old buffer, replace with the new. Dirty or
1248 * redirty the new buffer.
1250 * WARNING! The system buffer cache may have already flushed
1251 * the buffer, so we must be sure to [re]dirty it
1252 * for further modification.
1255 hammer2_io_brelse(&chain->dio);
1256 chain->data = (void *)bdata;
1258 hammer2_io_setdirty(dio); /* modified by bcopy above */
1261 panic("hammer2_chain_modify: illegal non-embedded type %d",
1268 * setflush on parent indicating that the parent must recurse down
1269 * to us. Do not call on chain itself which might already have it
1273 hammer2_chain_setflush(chain->parent);
1277 * Modify the chain associated with an inode.
1280 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1281 hammer2_tid_t mtid, int flags)
1283 hammer2_inode_modify(ip);
1284 hammer2_chain_modify(chain, mtid, flags);
1288 * Volume header data locks
1291 hammer2_voldata_lock(hammer2_dev_t *hmp)
1293 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1297 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1299 lockmgr(&hmp->vollk, LK_RELEASE);
1303 hammer2_voldata_modify(hammer2_dev_t *hmp)
1305 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1306 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1307 hammer2_chain_ref(&hmp->vchain);
1308 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1313 * This function returns the chain at the nearest key within the specified
1314 * range. The returned chain will be referenced but not locked.
1316 * This function will recurse through chain->rbtree as necessary and will
1317 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1318 * the iteration value is less than the current value of *key_nextp.
1320 * The caller should use (*key_nextp) to calculate the actual range of
1321 * the returned element, which will be (key_beg to *key_nextp - 1), because
1322 * there might be another element which is superior to the returned element
1325 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1326 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1327 * it will wind up being (key_end + 1).
1329 * WARNING! Must be called with child's spinlock held. Spinlock remains
1330 * held through the operation.
1332 struct hammer2_chain_find_info {
1333 hammer2_chain_t *best;
1334 hammer2_key_t key_beg;
1335 hammer2_key_t key_end;
1336 hammer2_key_t key_next;
1339 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1340 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1344 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1345 hammer2_key_t key_beg, hammer2_key_t key_end)
1347 struct hammer2_chain_find_info info;
1350 info.key_beg = key_beg;
1351 info.key_end = key_end;
1352 info.key_next = *key_nextp;
1354 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1355 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1357 *key_nextp = info.key_next;
1359 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1360 parent, key_beg, key_end, *key_nextp);
1368 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1370 struct hammer2_chain_find_info *info = data;
1371 hammer2_key_t child_beg;
1372 hammer2_key_t child_end;
1374 child_beg = child->bref.key;
1375 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1377 if (child_end < info->key_beg)
1379 if (child_beg > info->key_end)
1386 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1388 struct hammer2_chain_find_info *info = data;
1389 hammer2_chain_t *best;
1390 hammer2_key_t child_end;
1393 * WARNING! Do not discard DUPLICATED chains, it is possible that
1394 * we are catching an insertion half-way done. If a
1395 * duplicated chain turns out to be the best choice the
1396 * caller will re-check its flags after locking it.
1398 * WARNING! Layerq is scanned forwards, exact matches should keep
1399 * the existing info->best.
1401 if ((best = info->best) == NULL) {
1403 * No previous best. Assign best
1406 } else if (best->bref.key <= info->key_beg &&
1407 child->bref.key <= info->key_beg) {
1412 /*info->best = child;*/
1413 } else if (child->bref.key < best->bref.key) {
1415 * Child has a nearer key and best is not flush with key_beg.
1416 * Set best to child. Truncate key_next to the old best key.
1419 if (info->key_next > best->bref.key || info->key_next == 0)
1420 info->key_next = best->bref.key;
1421 } else if (child->bref.key == best->bref.key) {
1423 * If our current best is flush with the child then this
1424 * is an illegal overlap.
1426 * key_next will automatically be limited to the smaller of
1427 * the two end-points.
1433 * Keep the current best but truncate key_next to the child's
1436 * key_next will also automatically be limited to the smaller
1437 * of the two end-points (probably not necessary for this case
1438 * but we do it anyway).
1440 if (info->key_next > child->bref.key || info->key_next == 0)
1441 info->key_next = child->bref.key;
1445 * Always truncate key_next based on child's end-of-range.
1447 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1448 if (child_end && (info->key_next > child_end || info->key_next == 0))
1449 info->key_next = child_end;
1455 * Retrieve the specified chain from a media blockref, creating the
1456 * in-memory chain structure which reflects it.
1458 * To handle insertion races pass the INSERT_RACE flag along with the
1459 * generation number of the core. NULL will be returned if the generation
1460 * number changes before we have a chance to insert the chain. Insert
1461 * races can occur because the parent might be held shared.
1463 * Caller must hold the parent locked shared or exclusive since we may
1464 * need the parent's bref array to find our block.
1466 * WARNING! chain->pmp is always set to NULL for any chain representing
1467 * part of the super-root topology.
1470 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1471 hammer2_blockref_t *bref)
1473 hammer2_dev_t *hmp = parent->hmp;
1474 hammer2_chain_t *chain;
1478 * Allocate a chain structure representing the existing media
1479 * entry. Resulting chain has one ref and is not locked.
1481 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1482 chain = hammer2_chain_alloc(hmp, NULL, bref);
1484 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1485 /* ref'd chain returned */
1488 * Flag that the chain is in the parent's blockmap so delete/flush
1489 * knows what to do with it.
1491 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1494 * Link the chain into its parent. A spinlock is required to safely
1495 * access the RBTREE, and it is possible to collide with another
1496 * hammer2_chain_get() operation because the caller might only hold
1497 * a shared lock on the parent.
1499 KKASSERT(parent->refs > 0);
1500 error = hammer2_chain_insert(parent, chain,
1501 HAMMER2_CHAIN_INSERT_SPIN |
1502 HAMMER2_CHAIN_INSERT_RACE,
1505 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1506 kprintf("chain %p get race\n", chain);
1507 hammer2_chain_drop(chain);
1510 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1514 * Return our new chain referenced but not locked, or NULL if
1521 * Lookup initialization/completion API
1524 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1526 hammer2_chain_ref(parent);
1527 if (flags & HAMMER2_LOOKUP_SHARED) {
1528 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1529 HAMMER2_RESOLVE_SHARED);
1531 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1537 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1540 hammer2_chain_unlock(parent);
1541 hammer2_chain_drop(parent);
1546 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1548 hammer2_chain_t *oparent;
1549 hammer2_chain_t *nparent;
1552 * Be careful of order, oparent must be unlocked before nparent
1553 * is locked below to avoid a deadlock.
1556 hammer2_spin_ex(&oparent->core.spin);
1557 nparent = oparent->parent;
1558 hammer2_chain_ref(nparent);
1559 hammer2_spin_unex(&oparent->core.spin);
1561 hammer2_chain_unlock(oparent);
1562 hammer2_chain_drop(oparent);
1566 hammer2_chain_lock(nparent, how);
1573 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1574 * (*parentp) typically points to an inode but can also point to a related
1575 * indirect block and this function will recurse upwards and find the inode
1578 * (*parentp) must be exclusively locked and referenced and can be an inode
1579 * or an existing indirect block within the inode.
1581 * On return (*parentp) will be modified to point at the deepest parent chain
1582 * element encountered during the search, as a helper for an insertion or
1583 * deletion. The new (*parentp) will be locked and referenced and the old
1584 * will be unlocked and dereferenced (no change if they are both the same).
1586 * The matching chain will be returned exclusively locked. If NOLOCK is
1587 * requested the chain will be returned only referenced. Note that the
1588 * parent chain must always be locked shared or exclusive, matching the
1589 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1590 * when NOLOCK is specified but that complicates matters if *parentp must
1591 * inherit the chain.
1593 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1594 * data pointer or can otherwise be in flux.
1596 * NULL is returned if no match was found, but (*parentp) will still
1597 * potentially be adjusted.
1599 * If a fatal error occurs (typically an I/O error), a dummy chain is
1600 * returned with chain->error and error-identifying information set. This
1601 * chain will assert if you try to do anything fancy with it.
1603 * XXX Depending on where the error occurs we should allow continued iteration.
1605 * On return (*key_nextp) will point to an iterative value for key_beg.
1606 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1608 * This function will also recurse up the chain if the key is not within the
1609 * current parent's range. (*parentp) can never be set to NULL. An iteration
1610 * can simply allow (*parentp) to float inside the loop.
1612 * NOTE! chain->data is not always resolved. By default it will not be
1613 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1614 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1615 * BREF_TYPE_DATA as the device buffer can alias the logical file
1619 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1620 hammer2_key_t key_beg, hammer2_key_t key_end,
1621 int *cache_indexp, int flags)
1624 hammer2_chain_t *parent;
1625 hammer2_chain_t *chain;
1626 hammer2_blockref_t *base;
1627 hammer2_blockref_t *bref;
1628 hammer2_blockref_t bcopy;
1629 hammer2_key_t scan_beg;
1630 hammer2_key_t scan_end;
1632 int how_always = HAMMER2_RESOLVE_ALWAYS;
1633 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1636 int maxloops = 300000;
1638 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1639 how_maybe = how_always;
1640 how = HAMMER2_RESOLVE_ALWAYS;
1641 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1642 how = HAMMER2_RESOLVE_NEVER;
1644 how = HAMMER2_RESOLVE_MAYBE;
1646 if (flags & HAMMER2_LOOKUP_SHARED) {
1647 how_maybe |= HAMMER2_RESOLVE_SHARED;
1648 how_always |= HAMMER2_RESOLVE_SHARED;
1649 how |= HAMMER2_RESOLVE_SHARED;
1653 * Recurse (*parentp) upward if necessary until the parent completely
1654 * encloses the key range or we hit the inode.
1656 * This function handles races against the flusher doing a delete-
1657 * duplicate above us and re-homes the parent to the duplicate in
1658 * that case, otherwise we'd wind up recursing down a stale chain.
1663 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1664 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1665 scan_beg = parent->bref.key;
1666 scan_end = scan_beg +
1667 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1668 if (key_beg >= scan_beg && key_end <= scan_end)
1670 parent = hammer2_chain_getparent(parentp, how_maybe);
1674 if (--maxloops == 0)
1675 panic("hammer2_chain_lookup: maxloops");
1677 * Locate the blockref array. Currently we do a fully associative
1678 * search through the array.
1680 switch(parent->bref.type) {
1681 case HAMMER2_BREF_TYPE_INODE:
1683 * Special shortcut for embedded data returns the inode
1684 * itself. Callers must detect this condition and access
1685 * the embedded data (the strategy code does this for us).
1687 * This is only applicable to regular files and softlinks.
1689 if (parent->data->ipdata.meta.op_flags &
1690 HAMMER2_OPFLAG_DIRECTDATA) {
1691 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1693 *key_nextp = key_end + 1;
1696 hammer2_chain_ref(parent);
1697 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1698 hammer2_chain_lock(parent, how_always);
1699 *key_nextp = key_end + 1;
1702 base = &parent->data->ipdata.u.blockset.blockref[0];
1703 count = HAMMER2_SET_COUNT;
1705 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1706 case HAMMER2_BREF_TYPE_INDIRECT:
1708 * Handle MATCHIND on the parent
1710 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1711 scan_beg = parent->bref.key;
1712 scan_end = scan_beg +
1713 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1714 if (key_beg == scan_beg && key_end == scan_end) {
1716 hammer2_chain_ref(chain);
1717 hammer2_chain_lock(chain, how_maybe);
1718 *key_nextp = scan_end + 1;
1723 * Optimize indirect blocks in the INITIAL state to avoid
1726 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1729 if (parent->data == NULL)
1730 panic("parent->data is NULL");
1731 base = &parent->data->npdata[0];
1733 count = parent->bytes / sizeof(hammer2_blockref_t);
1735 case HAMMER2_BREF_TYPE_VOLUME:
1736 base = &parent->data->voldata.sroot_blockset.blockref[0];
1737 count = HAMMER2_SET_COUNT;
1739 case HAMMER2_BREF_TYPE_FREEMAP:
1740 base = &parent->data->blkset.blockref[0];
1741 count = HAMMER2_SET_COUNT;
1744 kprintf("hammer2_chain_lookup: unrecognized "
1745 "blockref(B) type: %d",
1748 tsleep(&base, 0, "dead", 0);
1749 panic("hammer2_chain_lookup: unrecognized "
1750 "blockref(B) type: %d",
1752 base = NULL; /* safety */
1753 count = 0; /* safety */
1757 * Merged scan to find next candidate.
1759 * hammer2_base_*() functions require the parent->core.live_* fields
1760 * to be synchronized.
1762 * We need to hold the spinlock to access the block array and RB tree
1763 * and to interlock chain creation.
1765 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1766 hammer2_chain_countbrefs(parent, base, count);
1771 hammer2_spin_ex(&parent->core.spin);
1772 chain = hammer2_combined_find(parent, base, count,
1773 cache_indexp, key_nextp,
1776 generation = parent->core.generation;
1779 * Exhausted parent chain, iterate.
1782 hammer2_spin_unex(&parent->core.spin);
1783 if (key_beg == key_end) /* short cut single-key case */
1787 * Stop if we reached the end of the iteration.
1789 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1790 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1795 * Calculate next key, stop if we reached the end of the
1796 * iteration, otherwise go up one level and loop.
1798 key_beg = parent->bref.key +
1799 ((hammer2_key_t)1 << parent->bref.keybits);
1800 if (key_beg == 0 || key_beg > key_end)
1802 parent = hammer2_chain_getparent(parentp, how_maybe);
1807 * Selected from blockref or in-memory chain.
1809 if (chain == NULL) {
1811 hammer2_spin_unex(&parent->core.spin);
1812 chain = hammer2_chain_get(parent, generation,
1814 if (chain == NULL) {
1815 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1816 parent, key_beg, key_end);
1819 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1820 hammer2_chain_drop(chain);
1824 hammer2_chain_ref(chain);
1825 hammer2_spin_unex(&parent->core.spin);
1829 * chain is referenced but not locked. We must lock the chain
1830 * to obtain definitive DUPLICATED/DELETED state
1832 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1833 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1834 hammer2_chain_lock(chain, how_maybe);
1836 hammer2_chain_lock(chain, how);
1840 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1842 * NOTE: Chain's key range is not relevant as there might be
1843 * one-offs within the range that are not deleted.
1845 * NOTE: Lookups can race delete-duplicate because
1846 * delete-duplicate does not lock the parent's core
1847 * (they just use the spinlock on the core). We must
1848 * check for races by comparing the DUPLICATED flag before
1849 * releasing the spinlock with the flag after locking the
1852 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1853 hammer2_chain_unlock(chain);
1854 hammer2_chain_drop(chain);
1855 key_beg = *key_nextp;
1856 if (key_beg == 0 || key_beg > key_end)
1862 * If the chain element is an indirect block it becomes the new
1863 * parent and we loop on it. We must maintain our top-down locks
1864 * to prevent the flusher from interfering (i.e. doing a
1865 * delete-duplicate and leaving us recursing down a deleted chain).
1867 * The parent always has to be locked with at least RESOLVE_MAYBE
1868 * so we can access its data. It might need a fixup if the caller
1869 * passed incompatible flags. Be careful not to cause a deadlock
1870 * as a data-load requires an exclusive lock.
1872 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1873 * range is within the requested key range we return the indirect
1874 * block and do NOT loop. This is usually only used to acquire
1877 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1878 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1879 hammer2_chain_unlock(parent);
1880 hammer2_chain_drop(parent);
1881 *parentp = parent = chain;
1886 * All done, return the chain.
1888 * If the caller does not want a locked chain, replace the lock with
1889 * a ref. Perhaps this can eventually be optimized to not obtain the
1890 * lock in the first place for situations where the data does not
1891 * need to be resolved.
1894 if (flags & HAMMER2_LOOKUP_NOLOCK)
1895 hammer2_chain_unlock(chain);
1902 * After having issued a lookup we can iterate all matching keys.
1904 * If chain is non-NULL we continue the iteration from just after it's index.
1906 * If chain is NULL we assume the parent was exhausted and continue the
1907 * iteration at the next parent.
1909 * If a fatal error occurs (typically an I/O error), a dummy chain is
1910 * returned with chain->error and error-identifying information set. This
1911 * chain will assert if you try to do anything fancy with it.
1913 * XXX Depending on where the error occurs we should allow continued iteration.
1915 * parent must be locked on entry and remains locked throughout. chain's
1916 * lock status must match flags. Chain is always at least referenced.
1918 * WARNING! The MATCHIND flag does not apply to this function.
1921 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1922 hammer2_key_t *key_nextp,
1923 hammer2_key_t key_beg, hammer2_key_t key_end,
1924 int *cache_indexp, int flags)
1926 hammer2_chain_t *parent;
1930 * Calculate locking flags for upward recursion.
1932 how_maybe = HAMMER2_RESOLVE_MAYBE;
1933 if (flags & HAMMER2_LOOKUP_SHARED)
1934 how_maybe |= HAMMER2_RESOLVE_SHARED;
1939 * Calculate the next index and recalculate the parent if necessary.
1942 key_beg = chain->bref.key +
1943 ((hammer2_key_t)1 << chain->bref.keybits);
1944 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1945 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1946 hammer2_chain_unlock(chain);
1948 hammer2_chain_drop(chain);
1951 * chain invalid past this point, but we can still do a
1952 * pointer comparison w/parent.
1954 * Any scan where the lookup returned degenerate data embedded
1955 * in the inode has an invalid index and must terminate.
1957 if (chain == parent)
1959 if (key_beg == 0 || key_beg > key_end)
1962 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1963 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1965 * We reached the end of the iteration.
1970 * Continue iteration with next parent unless the current
1971 * parent covers the range.
1973 key_beg = parent->bref.key +
1974 ((hammer2_key_t)1 << parent->bref.keybits);
1975 if (key_beg == 0 || key_beg > key_end)
1977 parent = hammer2_chain_getparent(parentp, how_maybe);
1983 return (hammer2_chain_lookup(parentp, key_nextp,
1985 cache_indexp, flags));
1989 * The raw scan function is similar to lookup/next but does not seek to a key.
1990 * Blockrefs are iterated via first_chain = (parent, NULL) and
1991 * next_chain = (parent, chain).
1993 * The passed-in parent must be locked and its data resolved. The returned
1994 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1995 * under parent and then iterate with the passed-in chain (which this
1996 * function will unlock).
1999 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2000 int *cache_indexp, int flags)
2003 hammer2_blockref_t *base;
2004 hammer2_blockref_t *bref;
2005 hammer2_blockref_t bcopy;
2007 hammer2_key_t next_key;
2009 int how_always = HAMMER2_RESOLVE_ALWAYS;
2010 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2013 int maxloops = 300000;
2018 * Scan flags borrowed from lookup.
2020 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2021 how_maybe = how_always;
2022 how = HAMMER2_RESOLVE_ALWAYS;
2023 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2024 how = HAMMER2_RESOLVE_NEVER;
2026 how = HAMMER2_RESOLVE_MAYBE;
2028 if (flags & HAMMER2_LOOKUP_SHARED) {
2029 how_maybe |= HAMMER2_RESOLVE_SHARED;
2030 how_always |= HAMMER2_RESOLVE_SHARED;
2031 how |= HAMMER2_RESOLVE_SHARED;
2035 * Calculate key to locate first/next element, unlocking the previous
2036 * element as we go. Be careful, the key calculation can overflow.
2039 key = chain->bref.key +
2040 ((hammer2_key_t)1 << chain->bref.keybits);
2041 hammer2_chain_unlock(chain);
2042 hammer2_chain_drop(chain);
2051 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2052 if (--maxloops == 0)
2053 panic("hammer2_chain_scan: maxloops");
2055 * Locate the blockref array. Currently we do a fully associative
2056 * search through the array.
2058 switch(parent->bref.type) {
2059 case HAMMER2_BREF_TYPE_INODE:
2061 * An inode with embedded data has no sub-chains.
2063 * WARNING! Bulk scan code may pass a static chain marked
2064 * as BREF_TYPE_INODE with a copy of the volume
2065 * root blockset to snapshot the volume.
2067 if (parent->data->ipdata.meta.op_flags &
2068 HAMMER2_OPFLAG_DIRECTDATA) {
2071 base = &parent->data->ipdata.u.blockset.blockref[0];
2072 count = HAMMER2_SET_COUNT;
2074 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2075 case HAMMER2_BREF_TYPE_INDIRECT:
2077 * Optimize indirect blocks in the INITIAL state to avoid
2080 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2083 if (parent->data == NULL)
2084 panic("parent->data is NULL");
2085 base = &parent->data->npdata[0];
2087 count = parent->bytes / sizeof(hammer2_blockref_t);
2089 case HAMMER2_BREF_TYPE_VOLUME:
2090 base = &parent->data->voldata.sroot_blockset.blockref[0];
2091 count = HAMMER2_SET_COUNT;
2093 case HAMMER2_BREF_TYPE_FREEMAP:
2094 base = &parent->data->blkset.blockref[0];
2095 count = HAMMER2_SET_COUNT;
2098 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2100 base = NULL; /* safety */
2101 count = 0; /* safety */
2105 * Merged scan to find next candidate.
2107 * hammer2_base_*() functions require the parent->core.live_* fields
2108 * to be synchronized.
2110 * We need to hold the spinlock to access the block array and RB tree
2111 * and to interlock chain creation.
2113 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2114 hammer2_chain_countbrefs(parent, base, count);
2117 hammer2_spin_ex(&parent->core.spin);
2118 chain = hammer2_combined_find(parent, base, count,
2119 cache_indexp, &next_key,
2120 key, HAMMER2_KEY_MAX,
2122 generation = parent->core.generation;
2125 * Exhausted parent chain, we're done.
2128 hammer2_spin_unex(&parent->core.spin);
2129 KKASSERT(chain == NULL);
2134 * Selected from blockref or in-memory chain.
2136 if (chain == NULL) {
2138 hammer2_spin_unex(&parent->core.spin);
2139 chain = hammer2_chain_get(parent, generation, &bcopy);
2140 if (chain == NULL) {
2141 kprintf("retry scan parent %p keys %016jx\n",
2145 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2146 hammer2_chain_drop(chain);
2151 hammer2_chain_ref(chain);
2152 hammer2_spin_unex(&parent->core.spin);
2156 * chain is referenced but not locked. We must lock the chain
2157 * to obtain definitive DUPLICATED/DELETED state
2159 hammer2_chain_lock(chain, how);
2162 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2164 * NOTE: chain's key range is not relevant as there might be
2165 * one-offs within the range that are not deleted.
2167 * NOTE: XXX this could create problems with scans used in
2168 * situations other than mount-time recovery.
2170 * NOTE: Lookups can race delete-duplicate because
2171 * delete-duplicate does not lock the parent's core
2172 * (they just use the spinlock on the core). We must
2173 * check for races by comparing the DUPLICATED flag before
2174 * releasing the spinlock with the flag after locking the
2177 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2178 hammer2_chain_unlock(chain);
2179 hammer2_chain_drop(chain);
2190 * All done, return the chain or NULL
2196 * Create and return a new hammer2 system memory structure of the specified
2197 * key, type and size and insert it under (*parentp). This is a full
2198 * insertion, based on the supplied key/keybits, and may involve creating
2199 * indirect blocks and moving other chains around via delete/duplicate.
2201 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2202 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2203 * FULL. This typically means that the caller is creating the chain after
2204 * doing a hammer2_chain_lookup().
2206 * (*parentp) must be exclusive locked and may be replaced on return
2207 * depending on how much work the function had to do.
2209 * (*parentp) must not be errored or this function will assert.
2211 * (*chainp) usually starts out NULL and returns the newly created chain,
2212 * but if the caller desires the caller may allocate a disconnected chain
2213 * and pass it in instead.
2215 * This function should NOT be used to insert INDIRECT blocks. It is
2216 * typically used to create/insert inodes and data blocks.
2218 * Caller must pass-in an exclusively locked parent the new chain is to
2219 * be inserted under, and optionally pass-in a disconnected, exclusively
2220 * locked chain to insert (else we create a new chain). The function will
2221 * adjust (*parentp) as necessary, create or connect the chain, and
2222 * return an exclusively locked chain in *chainp.
2224 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2225 * and will be reassigned.
2228 hammer2_chain_create(hammer2_chain_t **parentp,
2229 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2230 hammer2_key_t key, int keybits, int type, size_t bytes,
2231 hammer2_tid_t mtid, int flags)
2234 hammer2_chain_t *chain;
2235 hammer2_chain_t *parent;
2236 hammer2_blockref_t *base;
2237 hammer2_blockref_t dummy;
2241 int maxloops = 300000;
2244 * Topology may be crossing a PFS boundary.
2247 KKASSERT(hammer2_mtx_owned(&parent->lock));
2248 KKASSERT(parent->error == 0);
2252 if (chain == NULL) {
2254 * First allocate media space and construct the dummy bref,
2255 * then allocate the in-memory chain structure. Set the
2256 * INITIAL flag for fresh chains which do not have embedded
2259 * XXX for now set the check mode of the child based on
2260 * the parent or, if the parent is an inode, the
2261 * specification in the inode.
2263 bzero(&dummy, sizeof(dummy));
2266 dummy.keybits = keybits;
2267 dummy.data_off = hammer2_getradix(bytes);
2268 dummy.methods = parent->bref.methods;
2269 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2271 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2272 dummy.methods |= HAMMER2_ENC_CHECK(
2273 parent->data->ipdata.meta.check_algo);
2276 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2279 * Lock the chain manually, chain_lock will load the chain
2280 * which we do NOT want to do. (note: chain->refs is set
2281 * to 1 by chain_alloc() for us, but lockcnt is not).
2284 hammer2_mtx_ex(&chain->lock);
2288 * Set INITIAL to optimize I/O. The flag will generally be
2289 * processed when we call hammer2_chain_modify().
2291 * Recalculate bytes to reflect the actual media block
2294 bytes = (hammer2_off_t)1 <<
2295 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2296 chain->bytes = bytes;
2299 case HAMMER2_BREF_TYPE_VOLUME:
2300 case HAMMER2_BREF_TYPE_FREEMAP:
2301 panic("hammer2_chain_create: called with volume type");
2303 case HAMMER2_BREF_TYPE_INDIRECT:
2304 panic("hammer2_chain_create: cannot be used to"
2305 "create indirect block");
2307 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2308 panic("hammer2_chain_create: cannot be used to"
2309 "create freemap root or node");
2311 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2312 KKASSERT(bytes == sizeof(chain->data->bmdata));
2314 case HAMMER2_BREF_TYPE_INODE:
2315 case HAMMER2_BREF_TYPE_DATA:
2318 * leave chain->data NULL, set INITIAL
2320 KKASSERT(chain->data == NULL);
2321 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2326 * We are reattaching a previously deleted chain, possibly
2327 * under a new parent and possibly with a new key/keybits.
2328 * The chain does not have to be in a modified state. The
2329 * UPDATE flag will be set later on in this routine.
2331 * Do NOT mess with the current state of the INITIAL flag.
2333 chain->bref.key = key;
2334 chain->bref.keybits = keybits;
2335 if (chain->flags & HAMMER2_CHAIN_DELETED)
2336 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2337 KKASSERT(chain->parent == NULL);
2339 if (flags & HAMMER2_INSERT_PFSROOT)
2340 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2342 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2345 * Calculate how many entries we have in the blockref array and
2346 * determine if an indirect block is required.
2349 if (--maxloops == 0)
2350 panic("hammer2_chain_create: maxloops");
2352 switch(parent->bref.type) {
2353 case HAMMER2_BREF_TYPE_INODE:
2354 KKASSERT((parent->data->ipdata.meta.op_flags &
2355 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2356 KKASSERT(parent->data != NULL);
2357 base = &parent->data->ipdata.u.blockset.blockref[0];
2358 count = HAMMER2_SET_COUNT;
2360 case HAMMER2_BREF_TYPE_INDIRECT:
2361 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2362 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2365 base = &parent->data->npdata[0];
2366 count = parent->bytes / sizeof(hammer2_blockref_t);
2368 case HAMMER2_BREF_TYPE_VOLUME:
2369 KKASSERT(parent->data != NULL);
2370 base = &parent->data->voldata.sroot_blockset.blockref[0];
2371 count = HAMMER2_SET_COUNT;
2373 case HAMMER2_BREF_TYPE_FREEMAP:
2374 KKASSERT(parent->data != NULL);
2375 base = &parent->data->blkset.blockref[0];
2376 count = HAMMER2_SET_COUNT;
2379 panic("hammer2_chain_create: unrecognized blockref type: %d",
2387 * Make sure we've counted the brefs
2389 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2390 hammer2_chain_countbrefs(parent, base, count);
2392 KKASSERT(parent->core.live_count >= 0 &&
2393 parent->core.live_count <= count);
2396 * If no free blockref could be found we must create an indirect
2397 * block and move a number of blockrefs into it. With the parent
2398 * locked we can safely lock each child in order to delete+duplicate
2399 * it without causing a deadlock.
2401 * This may return the new indirect block or the old parent depending
2402 * on where the key falls. NULL is returned on error.
2404 if (parent->core.live_count == count) {
2405 hammer2_chain_t *nparent;
2407 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2408 mtid, type, &error);
2409 if (nparent == NULL) {
2411 hammer2_chain_drop(chain);
2415 if (parent != nparent) {
2416 hammer2_chain_unlock(parent);
2417 hammer2_chain_drop(parent);
2418 parent = *parentp = nparent;
2424 * Link the chain into its parent.
2426 if (chain->parent != NULL)
2427 panic("hammer2: hammer2_chain_create: chain already connected");
2428 KKASSERT(chain->parent == NULL);
2429 hammer2_chain_insert(parent, chain,
2430 HAMMER2_CHAIN_INSERT_SPIN |
2431 HAMMER2_CHAIN_INSERT_LIVE,
2436 * Mark the newly created chain modified. This will cause
2437 * UPDATE to be set and process the INITIAL flag.
2439 * Device buffers are not instantiated for DATA elements
2440 * as these are handled by logical buffers.
2442 * Indirect and freemap node indirect blocks are handled
2443 * by hammer2_chain_create_indirect() and not by this
2446 * Data for all other bref types is expected to be
2447 * instantiated (INODE, LEAF).
2449 switch(chain->bref.type) {
2450 case HAMMER2_BREF_TYPE_DATA:
2451 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2452 case HAMMER2_BREF_TYPE_INODE:
2453 hammer2_chain_modify(chain, mtid,
2454 HAMMER2_MODIFY_OPTDATA);
2458 * Remaining types are not supported by this function.
2459 * In particular, INDIRECT and LEAF_NODE types are
2460 * handled by create_indirect().
2462 panic("hammer2_chain_create: bad type: %d",
2469 * When reconnecting a chain we must set UPDATE and
2470 * setflush so the flush recognizes that it must update
2471 * the bref in the parent.
2473 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2474 hammer2_chain_ref(chain);
2475 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2480 * We must setflush(parent) to ensure that it recurses through to
2481 * chain. setflush(chain) might not work because ONFLUSH is possibly
2482 * already set in the chain (so it won't recurse up to set it in the
2485 hammer2_chain_setflush(parent);
2494 * Move the chain from its old parent to a new parent. The chain must have
2495 * already been deleted or already disconnected (or never associated) with
2496 * a parent. The chain is reassociated with the new parent and the deleted
2497 * flag will be cleared (no longer deleted). The chain's modification state
2500 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2501 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2502 * FULL. This typically means that the caller is creating the chain after
2503 * doing a hammer2_chain_lookup().
2505 * A non-NULL bref is typically passed when key and keybits must be overridden.
2506 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2507 * from a passed-in bref and uses the old chain's bref for everything else.
2509 * Neither (parent) or (chain) can be errored.
2511 * If (parent) is non-NULL then the new duplicated chain is inserted under
2514 * If (parent) is NULL then the newly duplicated chain is not inserted
2515 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2516 * passing into hammer2_chain_create() after this function returns).
2518 * WARNING! This function calls create which means it can insert indirect
2519 * blocks. This can cause other unrelated chains in the parent to
2520 * be moved to a newly inserted indirect block in addition to the
2524 hammer2_chain_rename(hammer2_blockref_t *bref,
2525 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2526 hammer2_tid_t mtid, int flags)
2529 hammer2_chain_t *parent;
2533 * WARNING! We should never resolve DATA to device buffers
2534 * (XXX allow it if the caller did?), and since
2535 * we currently do not have the logical buffer cache
2536 * buffer in-hand to fix its cached physical offset
2537 * we also force the modify code to not COW it. XXX
2540 KKASSERT(chain->parent == NULL);
2541 KKASSERT(chain->error == 0);
2544 * Now create a duplicate of the chain structure, associating
2545 * it with the same core, making it the same size, pointing it
2546 * to the same bref (the same media block).
2549 bref = &chain->bref;
2550 bytes = (hammer2_off_t)1 <<
2551 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2554 * If parent is not NULL the duplicated chain will be entered under
2555 * the parent and the UPDATE bit set to tell flush to update
2558 * We must setflush(parent) to ensure that it recurses through to
2559 * chain. setflush(chain) might not work because ONFLUSH is possibly
2560 * already set in the chain (so it won't recurse up to set it in the
2563 * Having both chains locked is extremely important for atomicy.
2565 if (parentp && (parent = *parentp) != NULL) {
2566 KKASSERT(hammer2_mtx_owned(&parent->lock));
2567 KKASSERT(parent->refs > 0);
2568 KKASSERT(parent->error == 0);
2570 hammer2_chain_create(parentp, &chain, chain->pmp,
2571 bref->key, bref->keybits, bref->type,
2572 chain->bytes, mtid, flags);
2573 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2574 hammer2_chain_setflush(*parentp);
2579 * Helper function for deleting chains.
2581 * The chain is removed from the live view (the RBTREE) as well as the parent's
2582 * blockmap. Both chain and its parent must be locked.
2584 * parent may not be errored. chain can be errored.
2587 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2588 hammer2_tid_t mtid, int flags)
2592 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2593 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2594 KKASSERT(chain->parent == parent);
2597 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2599 * Chain is blockmapped, so there must be a parent.
2600 * Atomically remove the chain from the parent and remove
2601 * the blockmap entry.
2603 hammer2_blockref_t *base;
2606 KKASSERT(parent != NULL);
2607 KKASSERT(parent->error == 0);
2608 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2609 hammer2_chain_modify(parent, mtid, HAMMER2_MODIFY_OPTDATA);
2612 * Calculate blockmap pointer
2614 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2615 hammer2_spin_ex(&parent->core.spin);
2617 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2618 atomic_add_int(&parent->core.live_count, -1);
2619 ++parent->core.generation;
2620 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2621 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2622 --parent->core.chain_count;
2623 chain->parent = NULL;
2625 switch(parent->bref.type) {
2626 case HAMMER2_BREF_TYPE_INODE:
2628 * Access the inode's block array. However, there
2629 * is no block array if the inode is flagged
2630 * DIRECTDATA. The DIRECTDATA case typicaly only
2631 * occurs when a hardlink has been shifted up the
2632 * tree and the original inode gets replaced with
2633 * an OBJTYPE_HARDLINK placeholding inode.
2636 (parent->data->ipdata.meta.op_flags &
2637 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2639 &parent->data->ipdata.u.blockset.blockref[0];
2643 count = HAMMER2_SET_COUNT;
2645 case HAMMER2_BREF_TYPE_INDIRECT:
2646 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2648 base = &parent->data->npdata[0];
2651 count = parent->bytes / sizeof(hammer2_blockref_t);
2653 case HAMMER2_BREF_TYPE_VOLUME:
2654 base = &parent->data->voldata.
2655 sroot_blockset.blockref[0];
2656 count = HAMMER2_SET_COUNT;
2658 case HAMMER2_BREF_TYPE_FREEMAP:
2659 base = &parent->data->blkset.blockref[0];
2660 count = HAMMER2_SET_COUNT;
2665 panic("hammer2_flush_pass2: "
2666 "unrecognized blockref type: %d",
2671 * delete blockmapped chain from its parent.
2673 * The parent is not affected by any statistics in chain
2674 * which are pending synchronization. That is, there is
2675 * nothing to undo in the parent since they have not yet
2676 * been incorporated into the parent.
2678 * The parent is affected by statistics stored in inodes.
2679 * Those have already been synchronized, so they must be
2680 * undone. XXX split update possible w/delete in middle?
2683 int cache_index = -1;
2684 hammer2_base_delete(parent, base, count,
2685 &cache_index, chain);
2687 hammer2_spin_unex(&parent->core.spin);
2688 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2690 * Chain is not blockmapped but a parent is present.
2691 * Atomically remove the chain from the parent. There is
2692 * no blockmap entry to remove.
2694 * Because chain was associated with a parent but not
2695 * synchronized, the chain's *_count_up fields contain
2696 * inode adjustment statistics which must be undone.
2698 hammer2_spin_ex(&parent->core.spin);
2699 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2700 atomic_add_int(&parent->core.live_count, -1);
2701 ++parent->core.generation;
2702 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2703 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2704 --parent->core.chain_count;
2705 chain->parent = NULL;
2706 hammer2_spin_unex(&parent->core.spin);
2709 * Chain is not blockmapped and has no parent. This
2710 * is a degenerate case.
2712 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2717 * Create an indirect block that covers one or more of the elements in the
2718 * current parent. Either returns the existing parent with no locking or
2719 * ref changes or returns the new indirect block locked and referenced
2720 * and leaving the original parent lock/ref intact as well.
2722 * If an error occurs, NULL is returned and *errorp is set to the error.
2724 * The returned chain depends on where the specified key falls.
2726 * The key/keybits for the indirect mode only needs to follow three rules:
2728 * (1) That all elements underneath it fit within its key space and
2730 * (2) That all elements outside it are outside its key space.
2732 * (3) When creating the new indirect block any elements in the current
2733 * parent that fit within the new indirect block's keyspace must be
2734 * moved into the new indirect block.
2736 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2737 * keyspace the the current parent, but lookup/iteration rules will
2738 * ensure (and must ensure) that rule (2) for all parents leading up
2739 * to the nearest inode or the root volume header is adhered to. This
2740 * is accomplished by always recursing through matching keyspaces in
2741 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2743 * The current implementation calculates the current worst-case keyspace by
2744 * iterating the current parent and then divides it into two halves, choosing
2745 * whichever half has the most elements (not necessarily the half containing
2746 * the requested key).
2748 * We can also opt to use the half with the least number of elements. This
2749 * causes lower-numbered keys (aka logical file offsets) to recurse through
2750 * fewer indirect blocks and higher-numbered keys to recurse through more.
2751 * This also has the risk of not moving enough elements to the new indirect
2752 * block and being forced to create several indirect blocks before the element
2755 * Must be called with an exclusively locked parent.
2757 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2758 hammer2_key_t *keyp, int keybits,
2759 hammer2_blockref_t *base, int count);
2760 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2761 hammer2_key_t *keyp, int keybits,
2762 hammer2_blockref_t *base, int count);
2765 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2766 hammer2_key_t create_key, int create_bits,
2767 hammer2_tid_t mtid, int for_type, int *errorp)
2770 hammer2_blockref_t *base;
2771 hammer2_blockref_t *bref;
2772 hammer2_blockref_t bcopy;
2773 hammer2_chain_t *chain;
2774 hammer2_chain_t *ichain;
2775 hammer2_chain_t dummy;
2776 hammer2_key_t key = create_key;
2777 hammer2_key_t key_beg;
2778 hammer2_key_t key_end;
2779 hammer2_key_t key_next;
2780 int keybits = create_bits;
2787 int maxloops = 300000;
2790 * Calculate the base blockref pointer or NULL if the chain
2791 * is known to be empty. We need to calculate the array count
2792 * for RB lookups either way.
2796 KKASSERT(hammer2_mtx_owned(&parent->lock));
2798 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2799 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2802 switch(parent->bref.type) {
2803 case HAMMER2_BREF_TYPE_INODE:
2804 count = HAMMER2_SET_COUNT;
2806 case HAMMER2_BREF_TYPE_INDIRECT:
2807 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2808 count = parent->bytes / sizeof(hammer2_blockref_t);
2810 case HAMMER2_BREF_TYPE_VOLUME:
2811 count = HAMMER2_SET_COUNT;
2813 case HAMMER2_BREF_TYPE_FREEMAP:
2814 count = HAMMER2_SET_COUNT;
2817 panic("hammer2_chain_create_indirect: "
2818 "unrecognized blockref type: %d",
2824 switch(parent->bref.type) {
2825 case HAMMER2_BREF_TYPE_INODE:
2826 base = &parent->data->ipdata.u.blockset.blockref[0];
2827 count = HAMMER2_SET_COUNT;
2829 case HAMMER2_BREF_TYPE_INDIRECT:
2830 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2831 base = &parent->data->npdata[0];
2832 count = parent->bytes / sizeof(hammer2_blockref_t);
2834 case HAMMER2_BREF_TYPE_VOLUME:
2835 base = &parent->data->voldata.
2836 sroot_blockset.blockref[0];
2837 count = HAMMER2_SET_COUNT;
2839 case HAMMER2_BREF_TYPE_FREEMAP:
2840 base = &parent->data->blkset.blockref[0];
2841 count = HAMMER2_SET_COUNT;
2844 panic("hammer2_chain_create_indirect: "
2845 "unrecognized blockref type: %d",
2853 * dummy used in later chain allocation (no longer used for lookups).
2855 bzero(&dummy, sizeof(dummy));
2858 * When creating an indirect block for a freemap node or leaf
2859 * the key/keybits must be fitted to static radix levels because
2860 * particular radix levels use particular reserved blocks in the
2863 * This routine calculates the key/radix of the indirect block
2864 * we need to create, and whether it is on the high-side or the
2867 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2868 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2869 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2872 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2877 * Normalize the key for the radix being represented, keeping the
2878 * high bits and throwing away the low bits.
2880 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2883 * How big should our new indirect block be? It has to be at least
2884 * as large as its parent.
2886 * The freemap uses a specific indirect block size.
2888 * The first indirect block level down from an inode typically
2889 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2891 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2892 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2893 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2894 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2895 nbytes = HAMMER2_IND_BYTES_MIN;
2897 nbytes = HAMMER2_IND_BYTES_MAX;
2899 if (nbytes < count * sizeof(hammer2_blockref_t)) {
2900 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2901 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2902 nbytes = count * sizeof(hammer2_blockref_t);
2906 * Ok, create our new indirect block
2908 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2909 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2910 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2912 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2914 dummy.bref.key = key;
2915 dummy.bref.keybits = keybits;
2916 dummy.bref.data_off = hammer2_getradix(nbytes);
2917 dummy.bref.methods = parent->bref.methods;
2919 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2920 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2921 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2922 /* ichain has one ref at this point */
2925 * We have to mark it modified to allocate its block, but use
2926 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2927 * it won't be acted upon by the flush code.
2929 hammer2_chain_modify(ichain, mtid, HAMMER2_MODIFY_OPTDATA);
2932 * Iterate the original parent and move the matching brefs into
2933 * the new indirect block.
2935 * XXX handle flushes.
2938 key_end = HAMMER2_KEY_MAX;
2940 hammer2_spin_ex(&parent->core.spin);
2945 if (++loops > 100000) {
2946 hammer2_spin_unex(&parent->core.spin);
2947 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2948 reason, parent, base, count, key_next);
2952 * NOTE: spinlock stays intact, returned chain (if not NULL)
2953 * is not referenced or locked which means that we
2954 * cannot safely check its flagged / deletion status
2957 chain = hammer2_combined_find(parent, base, count,
2958 &cache_index, &key_next,
2961 generation = parent->core.generation;
2964 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2967 * Skip keys that are not within the key/radix of the new
2968 * indirect block. They stay in the parent.
2970 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2971 (key ^ bref->key)) != 0) {
2972 goto next_key_spinlocked;
2976 * Load the new indirect block by acquiring the related
2977 * chains (potentially from media as it might not be
2978 * in-memory). Then move it to the new parent (ichain)
2979 * via DELETE-DUPLICATE.
2981 * chain is referenced but not locked. We must lock the
2982 * chain to obtain definitive DUPLICATED/DELETED state
2986 * Use chain already present in the RBTREE
2988 hammer2_chain_ref(chain);
2989 hammer2_spin_unex(&parent->core.spin);
2990 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2993 * Get chain for blockref element. _get returns NULL
2994 * on insertion race.
2997 hammer2_spin_unex(&parent->core.spin);
2998 chain = hammer2_chain_get(parent, generation, &bcopy);
2999 if (chain == NULL) {
3001 hammer2_spin_ex(&parent->core.spin);
3004 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3005 kprintf("REASON 2\n");
3007 hammer2_chain_drop(chain);
3008 hammer2_spin_ex(&parent->core.spin);
3011 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3015 * This is always live so if the chain has been deleted
3016 * we raced someone and we have to retry.
3018 * NOTE: Lookups can race delete-duplicate because
3019 * delete-duplicate does not lock the parent's core
3020 * (they just use the spinlock on the core). We must
3021 * check for races by comparing the DUPLICATED flag before
3022 * releasing the spinlock with the flag after locking the
3025 * (note reversed logic for this one)
3027 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3028 hammer2_chain_unlock(chain);
3029 hammer2_chain_drop(chain);
3034 * Shift the chain to the indirect block.
3036 * WARNING! No reason for us to load chain data, pass NOSTATS
3037 * to prevent delete/insert from trying to access
3038 * inode stats (and thus asserting if there is no
3039 * chain->data loaded).
3041 hammer2_chain_delete(parent, chain, mtid, 0);
3042 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3043 hammer2_chain_unlock(chain);
3044 hammer2_chain_drop(chain);
3045 KKASSERT(parent->refs > 0);
3048 hammer2_spin_ex(&parent->core.spin);
3049 next_key_spinlocked:
3050 if (--maxloops == 0)
3051 panic("hammer2_chain_create_indirect: maxloops");
3053 if (key_next == 0 || key_next > key_end)
3058 hammer2_spin_unex(&parent->core.spin);
3061 * Insert the new indirect block into the parent now that we've
3062 * cleared out some entries in the parent. We calculated a good
3063 * insertion index in the loop above (ichain->index).
3065 * We don't have to set UPDATE here because we mark ichain
3066 * modified down below (so the normal modified -> flush -> set-moved
3067 * sequence applies).
3069 * The insertion shouldn't race as this is a completely new block
3070 * and the parent is locked.
3072 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3073 hammer2_chain_insert(parent, ichain,
3074 HAMMER2_CHAIN_INSERT_SPIN |
3075 HAMMER2_CHAIN_INSERT_LIVE,
3079 * Make sure flushes propogate after our manual insertion.
3081 hammer2_chain_setflush(ichain);
3082 hammer2_chain_setflush(parent);
3085 * Figure out what to return.
3087 if (~(((hammer2_key_t)1 << keybits) - 1) &
3088 (create_key ^ key)) {
3090 * Key being created is outside the key range,
3091 * return the original parent.
3093 hammer2_chain_unlock(ichain);
3094 hammer2_chain_drop(ichain);
3097 * Otherwise its in the range, return the new parent.
3098 * (leave both the new and old parent locked).
3107 * Calculate the keybits and highside/lowside of the freemap node the
3108 * caller is creating.
3110 * This routine will specify the next higher-level freemap key/radix
3111 * representing the lowest-ordered set. By doing so, eventually all
3112 * low-ordered sets will be moved one level down.
3114 * We have to be careful here because the freemap reserves a limited
3115 * number of blocks for a limited number of levels. So we can't just
3116 * push indiscriminately.
3119 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3120 int keybits, hammer2_blockref_t *base, int count)
3122 hammer2_chain_t *chain;
3123 hammer2_blockref_t *bref;
3125 hammer2_key_t key_beg;
3126 hammer2_key_t key_end;
3127 hammer2_key_t key_next;
3131 int maxloops = 300000;
3139 * Calculate the range of keys in the array being careful to skip
3140 * slots which are overridden with a deletion.
3143 key_end = HAMMER2_KEY_MAX;
3145 hammer2_spin_ex(&parent->core.spin);
3148 if (--maxloops == 0) {
3149 panic("indkey_freemap shit %p %p:%d\n",
3150 parent, base, count);
3152 chain = hammer2_combined_find(parent, base, count,
3153 &cache_index, &key_next,
3164 * Skip deleted chains.
3166 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3167 if (key_next == 0 || key_next > key_end)
3174 * Use the full live (not deleted) element for the scan
3175 * iteration. HAMMER2 does not allow partial replacements.
3177 * XXX should be built into hammer2_combined_find().
3179 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3181 if (keybits > bref->keybits) {
3183 keybits = bref->keybits;
3184 } else if (keybits == bref->keybits && bref->key < key) {
3191 hammer2_spin_unex(&parent->core.spin);
3194 * Return the keybits for a higher-level FREEMAP_NODE covering
3198 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3199 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3201 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3202 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3204 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3205 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3207 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3208 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3210 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3211 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3213 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3214 panic("hammer2_chain_indkey_freemap: level too high");
3217 panic("hammer2_chain_indkey_freemap: bad radix");
3226 * Calculate the keybits and highside/lowside of the indirect block the
3227 * caller is creating.
3230 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3231 int keybits, hammer2_blockref_t *base, int count)
3233 hammer2_blockref_t *bref;
3234 hammer2_chain_t *chain;
3235 hammer2_key_t key_beg;
3236 hammer2_key_t key_end;
3237 hammer2_key_t key_next;
3243 int maxloops = 300000;
3250 * Calculate the range of keys in the array being careful to skip
3251 * slots which are overridden with a deletion. Once the scan
3252 * completes we will cut the key range in half and shift half the
3253 * range into the new indirect block.
3256 key_end = HAMMER2_KEY_MAX;
3258 hammer2_spin_ex(&parent->core.spin);
3261 if (--maxloops == 0) {
3262 panic("indkey_freemap shit %p %p:%d\n",
3263 parent, base, count);
3265 chain = hammer2_combined_find(parent, base, count,
3266 &cache_index, &key_next,
3277 * NOTE: No need to check DUPLICATED here because we do
3278 * not release the spinlock.
3280 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3281 if (key_next == 0 || key_next > key_end)
3288 * Use the full live (not deleted) element for the scan
3289 * iteration. HAMMER2 does not allow partial replacements.
3291 * XXX should be built into hammer2_combined_find().
3293 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3296 * Expand our calculated key range (key, keybits) to fit
3297 * the scanned key. nkeybits represents the full range
3298 * that we will later cut in half (two halves @ nkeybits - 1).
3301 if (nkeybits < bref->keybits) {
3302 if (bref->keybits > 64) {
3303 kprintf("bad bref chain %p bref %p\n",
3307 nkeybits = bref->keybits;
3309 while (nkeybits < 64 &&
3310 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3311 (key ^ bref->key)) != 0) {
3316 * If the new key range is larger we have to determine
3317 * which side of the new key range the existing keys fall
3318 * under by checking the high bit, then collapsing the
3319 * locount into the hicount or vise-versa.
3321 if (keybits != nkeybits) {
3322 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3333 * The newly scanned key will be in the lower half or the
3334 * upper half of the (new) key range.
3336 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3345 hammer2_spin_unex(&parent->core.spin);
3346 bref = NULL; /* now invalid (safety) */
3349 * Adjust keybits to represent half of the full range calculated
3350 * above (radix 63 max)
3355 * Select whichever half contains the most elements. Theoretically
3356 * we can select either side as long as it contains at least one
3357 * element (in order to ensure that a free slot is present to hold
3358 * the indirect block).
3360 if (hammer2_indirect_optimize) {
3362 * Insert node for least number of keys, this will arrange
3363 * the first few blocks of a large file or the first few
3364 * inodes in a directory with fewer indirect blocks when
3367 if (hicount < locount && hicount != 0)
3368 key |= (hammer2_key_t)1 << keybits;
3370 key &= ~(hammer2_key_t)1 << keybits;
3373 * Insert node for most number of keys, best for heavily
3376 if (hicount > locount)
3377 key |= (hammer2_key_t)1 << keybits;
3379 key &= ~(hammer2_key_t)1 << keybits;
3387 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3390 * Both parent and chain must be locked exclusively.
3392 * This function will modify the parent if the blockref requires removal
3393 * from the parent's block table.
3395 * This function is NOT recursive. Any entity already pushed into the
3396 * chain (such as an inode) may still need visibility into its contents,
3397 * as well as the ability to read and modify the contents. For example,
3398 * for an unlinked file which is still open.
3401 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3402 hammer2_tid_t mtid, int flags)
3404 KKASSERT(hammer2_mtx_owned(&chain->lock));
3407 * Nothing to do if already marked.
3409 * We need the spinlock on the core whos RBTREE contains chain
3410 * to protect against races.
3412 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3413 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3414 chain->parent == parent);
3415 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3419 * To avoid losing track of a permanent deletion we add the chain
3420 * to the delayed flush queue. If were to flush it right now the
3421 * parent would end up in a modified state and generate I/O.
3422 * The delayed queue gives the parent a chance to be deleted to
3425 if (flags & HAMMER2_DELETE_PERMANENT) {
3426 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3427 hammer2_delayed_flush(chain);
3429 /* XXX might not be needed */
3430 hammer2_chain_setflush(chain);
3435 * Returns the index of the nearest element in the blockref array >= elm.
3436 * Returns (count) if no element could be found.
3438 * Sets *key_nextp to the next key for loop purposes but does not modify
3439 * it if the next key would be higher than the current value of *key_nextp.
3440 * Note that *key_nexp can overflow to 0, which should be tested by the
3443 * (*cache_indexp) is a heuristic and can be any value without effecting
3446 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3447 * held through the operation.
3450 hammer2_base_find(hammer2_chain_t *parent,
3451 hammer2_blockref_t *base, int count,
3452 int *cache_indexp, hammer2_key_t *key_nextp,
3453 hammer2_key_t key_beg, hammer2_key_t key_end)
3455 hammer2_blockref_t *scan;
3456 hammer2_key_t scan_end;
3461 * Require the live chain's already have their core's counted
3462 * so we can optimize operations.
3464 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3469 if (count == 0 || base == NULL)
3473 * Sequential optimization using *cache_indexp. This is the most
3476 * We can avoid trailing empty entries on live chains, otherwise
3477 * we might have to check the whole block array.
3481 limit = parent->core.live_zero;
3486 KKASSERT(i < count);
3492 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3499 * Search forwards, stop when we find a scan element which
3500 * encloses the key or until we know that there are no further
3504 if (scan->type != 0) {
3505 scan_end = scan->key +
3506 ((hammer2_key_t)1 << scan->keybits) - 1;
3507 if (scan->key > key_beg || scan_end >= key_beg)
3520 scan_end = scan->key +
3521 ((hammer2_key_t)1 << scan->keybits);
3522 if (scan_end && (*key_nextp > scan_end ||
3524 *key_nextp = scan_end;
3532 * Do a combined search and return the next match either from the blockref
3533 * array or from the in-memory chain. Sets *bresp to the returned bref in
3534 * both cases, or sets it to NULL if the search exhausted. Only returns
3535 * a non-NULL chain if the search matched from the in-memory chain.
3537 * When no in-memory chain has been found and a non-NULL bref is returned
3541 * The returned chain is not locked or referenced. Use the returned bref
3542 * to determine if the search exhausted or not. Iterate if the base find
3543 * is chosen but matches a deleted chain.
3545 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3546 * held through the operation.
3548 static hammer2_chain_t *
3549 hammer2_combined_find(hammer2_chain_t *parent,
3550 hammer2_blockref_t *base, int count,
3551 int *cache_indexp, hammer2_key_t *key_nextp,
3552 hammer2_key_t key_beg, hammer2_key_t key_end,
3553 hammer2_blockref_t **bresp)
3555 hammer2_blockref_t *bref;
3556 hammer2_chain_t *chain;
3560 * Lookup in block array and in rbtree.
3562 *key_nextp = key_end + 1;
3563 i = hammer2_base_find(parent, base, count, cache_indexp,
3564 key_nextp, key_beg, key_end);
3565 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3570 if (i == count && chain == NULL) {
3576 * Only chain matched.
3579 bref = &chain->bref;
3584 * Only blockref matched.
3586 if (chain == NULL) {
3592 * Both in-memory and blockref matched, select the nearer element.
3594 * If both are flush with the left-hand side or both are the
3595 * same distance away, select the chain. In this situation the
3596 * chain must have been loaded from the matching blockmap.
3598 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3599 chain->bref.key == base[i].key) {
3600 KKASSERT(chain->bref.key == base[i].key);
3601 bref = &chain->bref;
3606 * Select the nearer key
3608 if (chain->bref.key < base[i].key) {
3609 bref = &chain->bref;
3616 * If the bref is out of bounds we've exhausted our search.
3619 if (bref->key > key_end) {
3629 * Locate the specified block array element and delete it. The element
3632 * The spin lock on the related chain must be held.
3634 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3635 * need to be adjusted when we commit the media change.
3638 hammer2_base_delete(hammer2_chain_t *parent,
3639 hammer2_blockref_t *base, int count,
3640 int *cache_indexp, hammer2_chain_t *chain)
3642 hammer2_blockref_t *elm = &chain->bref;
3643 hammer2_key_t key_next;
3647 * Delete element. Expect the element to exist.
3649 * XXX see caller, flush code not yet sophisticated enough to prevent
3650 * re-flushed in some cases.
3652 key_next = 0; /* max range */
3653 i = hammer2_base_find(parent, base, count, cache_indexp,
3654 &key_next, elm->key, elm->key);
3655 if (i == count || base[i].type == 0 ||
3656 base[i].key != elm->key ||
3657 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3658 base[i].keybits != elm->keybits)) {
3659 hammer2_spin_unex(&parent->core.spin);
3660 panic("delete base %p element not found at %d/%d elm %p\n",
3661 base, i, count, elm);
3666 * Update stats and zero the entry
3668 parent->bref.data_count -= base[i].data_count;
3669 parent->bref.data_count -= (hammer2_off_t)1 <<
3670 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3671 parent->bref.inode_count -= base[i].inode_count;
3672 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3673 parent->bref.inode_count -= 1;
3675 bzero(&base[i], sizeof(*base));
3678 * We can only optimize parent->core.live_zero for live chains.
3680 if (parent->core.live_zero == i + 1) {
3681 while (--i >= 0 && base[i].type == 0)
3683 parent->core.live_zero = i + 1;
3687 * Clear appropriate blockmap flags in chain.
3689 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3690 HAMMER2_CHAIN_BMAPUPD);
3694 * Insert the specified element. The block array must not already have the
3695 * element and must have space available for the insertion.
3697 * The spin lock on the related chain must be held.
3699 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3700 * need to be adjusted when we commit the media change.
3703 hammer2_base_insert(hammer2_chain_t *parent,
3704 hammer2_blockref_t *base, int count,
3705 int *cache_indexp, hammer2_chain_t *chain)
3707 hammer2_blockref_t *elm = &chain->bref;
3708 hammer2_key_t key_next;
3717 * Insert new element. Expect the element to not already exist
3718 * unless we are replacing it.
3720 * XXX see caller, flush code not yet sophisticated enough to prevent
3721 * re-flushed in some cases.
3723 key_next = 0; /* max range */
3724 i = hammer2_base_find(parent, base, count, cache_indexp,
3725 &key_next, elm->key, elm->key);
3728 * Shortcut fill optimization, typical ordered insertion(s) may not
3731 KKASSERT(i >= 0 && i <= count);
3734 * Set appropriate blockmap flags in chain.
3736 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3739 * Update stats and zero the entry
3741 parent->bref.data_count += elm->data_count;
3742 parent->bref.data_count += (hammer2_off_t)1 <<
3743 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3744 parent->bref.inode_count += elm->inode_count;
3745 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3746 parent->bref.inode_count += 1;
3750 * We can only optimize parent->core.live_zero for live chains.
3752 if (i == count && parent->core.live_zero < count) {
3753 i = parent->core.live_zero++;
3758 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3759 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3760 hammer2_spin_unex(&parent->core.spin);
3761 panic("insert base %p overlapping elements at %d elm %p\n",
3766 * Try to find an empty slot before or after.
3770 while (j > 0 || k < count) {
3772 if (j >= 0 && base[j].type == 0) {
3776 bcopy(&base[j+1], &base[j],
3777 (i - j - 1) * sizeof(*base));
3783 if (k < count && base[k].type == 0) {
3784 bcopy(&base[i], &base[i+1],
3785 (k - i) * sizeof(hammer2_blockref_t));
3789 * We can only update parent->core.live_zero for live
3792 if (parent->core.live_zero <= k)
3793 parent->core.live_zero = k + 1;
3798 panic("hammer2_base_insert: no room!");
3805 for (l = 0; l < count; ++l) {
3807 key_next = base[l].key +
3808 ((hammer2_key_t)1 << base[l].keybits) - 1;
3812 while (++l < count) {
3814 if (base[l].key <= key_next)
3815 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3816 key_next = base[l].key +
3817 ((hammer2_key_t)1 << base[l].keybits) - 1;
3827 * Sort the blockref array for the chain. Used by the flush code to
3828 * sort the blockref[] array.
3830 * The chain must be exclusively locked AND spin-locked.
3832 typedef hammer2_blockref_t *hammer2_blockref_p;
3836 hammer2_base_sort_callback(const void *v1, const void *v2)
3838 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3839 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3842 * Make sure empty elements are placed at the end of the array
3844 if (bref1->type == 0) {
3845 if (bref2->type == 0)
3848 } else if (bref2->type == 0) {
3855 if (bref1->key < bref2->key)
3857 if (bref1->key > bref2->key)
3863 hammer2_base_sort(hammer2_chain_t *chain)
3865 hammer2_blockref_t *base;
3868 switch(chain->bref.type) {
3869 case HAMMER2_BREF_TYPE_INODE:
3871 * Special shortcut for embedded data returns the inode
3872 * itself. Callers must detect this condition and access
3873 * the embedded data (the strategy code does this for us).
3875 * This is only applicable to regular files and softlinks.
3877 if (chain->data->ipdata.meta.op_flags &
3878 HAMMER2_OPFLAG_DIRECTDATA) {
3881 base = &chain->data->ipdata.u.blockset.blockref[0];
3882 count = HAMMER2_SET_COUNT;
3884 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3885 case HAMMER2_BREF_TYPE_INDIRECT:
3887 * Optimize indirect blocks in the INITIAL state to avoid
3890 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3891 base = &chain->data->npdata[0];
3892 count = chain->bytes / sizeof(hammer2_blockref_t);
3894 case HAMMER2_BREF_TYPE_VOLUME:
3895 base = &chain->data->voldata.sroot_blockset.blockref[0];
3896 count = HAMMER2_SET_COUNT;
3898 case HAMMER2_BREF_TYPE_FREEMAP:
3899 base = &chain->data->blkset.blockref[0];
3900 count = HAMMER2_SET_COUNT;
3903 kprintf("hammer2_chain_lookup: unrecognized "
3904 "blockref(A) type: %d",
3907 tsleep(&base, 0, "dead", 0);
3908 panic("hammer2_chain_lookup: unrecognized "
3909 "blockref(A) type: %d",
3911 base = NULL; /* safety */
3912 count = 0; /* safety */
3914 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3920 * Chain memory management
3923 hammer2_chain_wait(hammer2_chain_t *chain)
3925 tsleep(chain, 0, "chnflw", 1);
3928 const hammer2_media_data_t *
3929 hammer2_chain_rdata(hammer2_chain_t *chain)
3931 KKASSERT(chain->data != NULL);
3932 return (chain->data);
3935 hammer2_media_data_t *
3936 hammer2_chain_wdata(hammer2_chain_t *chain)
3938 KKASSERT(chain->data != NULL);
3939 return (chain->data);
3943 * Set the check data for a chain. This can be a heavy-weight operation
3944 * and typically only runs on-flush. For file data check data is calculated
3945 * when the logical buffers are flushed.
3948 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3950 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3952 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3953 case HAMMER2_CHECK_NONE:
3955 case HAMMER2_CHECK_DISABLED:
3957 case HAMMER2_CHECK_ISCSI32:
3958 chain->bref.check.iscsi32.value =
3959 hammer2_icrc32(bdata, chain->bytes);
3961 case HAMMER2_CHECK_CRC64:
3962 chain->bref.check.crc64.value = 0;
3965 case HAMMER2_CHECK_SHA192:
3967 SHA256_CTX hash_ctx;
3969 uint8_t digest[SHA256_DIGEST_LENGTH];
3970 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3973 SHA256_Init(&hash_ctx);
3974 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3975 SHA256_Final(u.digest, &hash_ctx);
3976 u.digest64[2] ^= u.digest64[3];
3978 chain->bref.check.sha192.data,
3979 sizeof(chain->bref.check.sha192.data));
3982 case HAMMER2_CHECK_FREEMAP:
3983 chain->bref.check.freemap.icrc32 =
3984 hammer2_icrc32(bdata, chain->bytes);
3987 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3988 chain->bref.methods);
3994 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3998 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4001 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4002 case HAMMER2_CHECK_NONE:
4005 case HAMMER2_CHECK_DISABLED:
4008 case HAMMER2_CHECK_ISCSI32:
4009 r = (chain->bref.check.iscsi32.value ==
4010 hammer2_icrc32(bdata, chain->bytes));
4012 case HAMMER2_CHECK_CRC64:
4013 r = (chain->bref.check.crc64.value == 0);
4016 case HAMMER2_CHECK_SHA192:
4018 SHA256_CTX hash_ctx;
4020 uint8_t digest[SHA256_DIGEST_LENGTH];
4021 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4024 SHA256_Init(&hash_ctx);
4025 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4026 SHA256_Final(u.digest, &hash_ctx);
4027 u.digest64[2] ^= u.digest64[3];
4029 chain->bref.check.sha192.data,
4030 sizeof(chain->bref.check.sha192.data)) == 0) {
4037 case HAMMER2_CHECK_FREEMAP:
4038 r = (chain->bref.check.freemap.icrc32 ==
4039 hammer2_icrc32(bdata, chain->bytes));
4041 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4042 chain->bref.check.freemap.icrc32,
4043 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4045 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4046 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4051 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4052 chain->bref.methods);
4060 * The caller presents a shared-locked (parent, chain) where the chain
4061 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4062 * structure representing the inode locked to prevent
4063 * consolidation/deconsolidation races.
4065 * We locate the hardlink in the current or a common parent directory.
4067 * If we are unable to locate the hardlink, EIO is returned and
4068 * (*chainp) is unlocked and dropped.
4071 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4072 hammer2_chain_t **parentp,
4073 hammer2_chain_t **chainp,
4076 hammer2_chain_t *parent;
4077 hammer2_chain_t *rchain;
4078 hammer2_key_t key_dummy;
4080 int cache_index = -1;
4083 * Obtain the key for the hardlink from *chainp.
4086 lhc = rchain->data->ipdata.meta.inum;
4087 hammer2_chain_unlock(rchain);
4088 hammer2_chain_drop(rchain);
4093 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4095 &cache_index, flags);
4100 * Iterate parents, handle parent rename races by retrying
4108 parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4111 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4113 if (parent->parent == NULL)
4115 parent = parent->parent;
4116 hammer2_chain_ref(parent);
4117 hammer2_chain_unlock(*parentp);
4118 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4120 if ((*parentp)->parent == parent) {
4121 hammer2_chain_drop(*parentp);
4124 hammer2_chain_unlock(parent);
4125 hammer2_chain_drop(parent);
4126 hammer2_chain_lock(*parentp,
4127 HAMMER2_RESOLVE_ALWAYS |
4129 parent = NULL; /* safety */
4137 return (rchain ? EINVAL : 0);
4141 * Used by the bulkscan code to snapshot the synchronized storage for
4142 * a volume, allowing it to be scanned concurrently against normal
4146 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4148 hammer2_chain_t *copy;
4150 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4151 switch(chain->bref.type) {
4152 case HAMMER2_BREF_TYPE_VOLUME:
4153 copy->data = kmalloc(sizeof(copy->data->voldata),
4156 hammer2_spin_ex(&chain->core.spin);
4157 copy->data->voldata = chain->data->voldata;
4158 hammer2_spin_unex(&chain->core.spin);
4160 case HAMMER2_BREF_TYPE_FREEMAP:
4161 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4164 hammer2_spin_ex(&chain->core.spin);
4165 copy->data->blkset = chain->data->blkset;
4166 hammer2_spin_unex(&chain->core.spin);
4175 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4177 switch(copy->bref.type) {
4178 case HAMMER2_BREF_TYPE_VOLUME:
4179 case HAMMER2_BREF_TYPE_FREEMAP:
4180 KKASSERT(copy->data);
4181 kfree(copy->data, copy->hmp->mchain);
4186 hammer2_chain_drop(copy);
4190 * Create a snapshot of the specified {parent, ochain} with the specified
4191 * label. The originating hammer2_inode must be exclusively locked for
4194 * The ioctl code has already synced the filesystem.
4197 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4201 const hammer2_inode_data_t *ripdata;
4202 hammer2_inode_data_t *wipdata;
4203 hammer2_chain_t *nchain;
4204 hammer2_inode_t *nip;
4213 kprintf("snapshot %s\n", pmp->name);
4215 name_len = strlen(pmp->name);
4216 lhc = hammer2_dirhash(pmp->name, name_len);
4221 ripdata = &chain->data->ipdata;
4223 opfs_clid = ripdata->meta.pfs_clid;
4228 * Create the snapshot directory under the super-root
4230 * Set PFS type, generate a unique filesystem id, and generate
4231 * a cluster id. Use the same clid when snapshotting a PFS root,
4232 * which theoretically allows the snapshot to be used as part of
4233 * the same cluster (perhaps as a cache).
4235 * Copy the (flushed) blockref array. Theoretically we could use
4236 * chain_duplicate() but it becomes difficult to disentangle
4237 * the shared core so for now just brute-force it.
4242 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4243 pmp->name, name_len, 0,
4245 HAMMER2_INSERT_PFSROOT, &error);
4248 hammer2_inode_modify(nip);
4249 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4250 hammer2_chain_modify(nchain, mtid, 0);
4251 wipdata = &nchain->data->ipdata;
4253 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4254 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4255 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4256 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4259 * Give the snapshot its own private cluster id. As a
4260 * snapshot no further synchronization with the original
4261 * cluster will be done.
4264 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4265 nip->meta.pfs_clid = opfs_clid;
4267 kern_uuidgen(&nip->meta.pfs_clid, 1);
4269 kern_uuidgen(&nip->meta.pfs_clid, 1);
4270 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4272 /* XXX hack blockset copy */
4273 /* XXX doesn't work with real cluster */
4274 wipdata->meta = nip->meta;
4275 wipdata->u.blockset = ripdata->u.blockset;
4276 hammer2_flush(nchain, mtid, 1);
4277 hammer2_chain_unlock(nchain);
4278 hammer2_chain_drop(nchain);
4279 hammer2_inode_unlock(nip);