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);
584 ++curthread->td_tracker;
587 * If we already have a valid data pointer no further action is
594 * Do we have to resolve the data?
596 switch(how & HAMMER2_RESOLVE_MASK) {
597 case HAMMER2_RESOLVE_NEVER:
599 case HAMMER2_RESOLVE_MAYBE:
600 if (chain->flags & HAMMER2_CHAIN_INITIAL)
602 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
605 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
607 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
611 case HAMMER2_RESOLVE_ALWAYS:
617 * Caller requires data
619 hammer2_chain_load_data(chain);
623 * Obtains a second shared lock on the chain, does not account the second
624 * shared lock as being owned by the current thread.
626 * Caller must already own a shared lock on this chain.
629 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
631 hammer2_mtx_sh(&chain->lock);
632 atomic_add_int(&chain->lockcnt, 1);
633 /* do not count in td_tracker for this thread */
637 * Accounts for a shared lock that was pushed to us as being owned by our
641 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
643 ++curthread->td_tracker;
647 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
648 * may be of any type.
650 * Once chain->data is set it cannot be disposed of until all locks are
654 hammer2_chain_load_data(hammer2_chain_t *chain)
656 hammer2_blockref_t *bref;
662 * Degenerate case, data already present.
668 KKASSERT(hmp != NULL);
671 * Gain the IOINPROG bit, interlocked block.
677 oflags = chain->flags;
679 if (oflags & HAMMER2_CHAIN_IOINPROG) {
680 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
681 tsleep_interlock(&chain->flags, 0);
682 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
683 tsleep(&chain->flags, PINTERLOCKED,
688 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
689 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
697 * We own CHAIN_IOINPROG
699 * Degenerate case if we raced another load.
705 * We must resolve to a device buffer, either by issuing I/O or
706 * by creating a zero-fill element. We do not mark the buffer
707 * dirty when creating a zero-fill element (the hammer2_chain_modify()
708 * API must still be used to do that).
710 * The device buffer is variable-sized in powers of 2 down
711 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
712 * chunk always contains buffers of the same size. (XXX)
714 * The minimum physical IO size may be larger than the variable
720 * The getblk() optimization can only be used on newly created
721 * elements if the physical block size matches the request.
723 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
724 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
727 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
729 hammer2_adjreadcounter(&chain->bref, chain->bytes);
732 chain->error = HAMMER2_ERROR_IO;
733 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
734 (intmax_t)bref->data_off, error);
735 hammer2_io_bqrelse(&chain->dio);
741 * NOTE: A locked chain's data cannot be modified without first
742 * calling hammer2_chain_modify().
746 * Clear INITIAL. In this case we used io_new() and the buffer has
747 * been zero'd and marked dirty.
749 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
750 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
751 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
752 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
753 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
755 * check data not currently synchronized due to
756 * modification. XXX assumes data stays in the buffer
757 * cache, which might not be true (need biodep on flush
758 * to calculate crc? or simple crc?).
761 if (hammer2_chain_testcheck(chain, bdata) == 0) {
762 kprintf("chain %016jx.%02x meth=%02x "
763 "CHECK FAIL %08x (flags=%08x)\n",
764 chain->bref.data_off,
767 hammer2_icrc32(bdata, chain->bytes),
769 chain->error = HAMMER2_ERROR_CHECK;
774 * Setup the data pointer, either pointing it to an embedded data
775 * structure and copying the data from the buffer, or pointing it
778 * The buffer is not retained when copying to an embedded data
779 * structure in order to avoid potential deadlocks or recursions
780 * on the same physical buffer.
782 * WARNING! Other threads can start using the data the instant we
783 * set chain->data non-NULL.
785 switch (bref->type) {
786 case HAMMER2_BREF_TYPE_VOLUME:
787 case HAMMER2_BREF_TYPE_FREEMAP:
789 * Copy data from bp to embedded buffer
791 panic("hammer2_chain_lock: called on unresolved volume header");
793 case HAMMER2_BREF_TYPE_INODE:
794 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
795 case HAMMER2_BREF_TYPE_INDIRECT:
796 case HAMMER2_BREF_TYPE_DATA:
797 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
800 * Point data at the device buffer and leave dio intact.
802 chain->data = (void *)bdata;
807 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
814 oflags = chain->flags;
815 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
816 HAMMER2_CHAIN_IOSIGNAL);
817 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
818 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
819 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
820 wakeup(&chain->flags);
827 * Unlock and deref a chain element.
829 * On the last lock release any non-embedded data (chain->dio) will be
833 hammer2_chain_unlock(hammer2_chain_t *chain)
835 hammer2_mtx_state_t ostate;
839 --curthread->td_tracker;
841 * If multiple locks are present (or being attempted) on this
842 * particular chain we can just unlock, drop refs, and return.
844 * Otherwise fall-through on the 1->0 transition.
847 lockcnt = chain->lockcnt;
848 KKASSERT(lockcnt > 0);
851 if (atomic_cmpset_int(&chain->lockcnt,
852 lockcnt, lockcnt - 1)) {
853 hammer2_mtx_unlock(&chain->lock);
857 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
864 * On the 1->0 transition we upgrade the core lock (if necessary)
865 * to exclusive for terminal processing. If after upgrading we find
866 * that lockcnt is non-zero, another thread is racing us and will
867 * handle the unload for us later on, so just cleanup and return
868 * leaving the data/io intact
870 * Otherwise if lockcnt is still 0 it is possible for it to become
871 * non-zero and race, but since we hold the core->lock exclusively
872 * all that will happen is that the chain will be reloaded after we
875 ostate = hammer2_mtx_upgrade(&chain->lock);
876 if (chain->lockcnt) {
877 hammer2_mtx_unlock(&chain->lock);
882 * Shortcut the case if the data is embedded or not resolved.
884 * Do NOT NULL out chain->data (e.g. inode data), it might be
887 if (chain->dio == NULL) {
888 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
889 hammer2_chain_drop_data(chain, 0);
890 hammer2_mtx_unlock(&chain->lock);
897 if (hammer2_io_isdirty(chain->dio)) {
898 switch(chain->bref.type) {
899 case HAMMER2_BREF_TYPE_DATA:
900 counterp = &hammer2_iod_file_write;
902 case HAMMER2_BREF_TYPE_INODE:
903 counterp = &hammer2_iod_meta_write;
905 case HAMMER2_BREF_TYPE_INDIRECT:
906 counterp = &hammer2_iod_indr_write;
908 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
909 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
910 counterp = &hammer2_iod_fmap_write;
913 counterp = &hammer2_iod_volu_write;
916 *counterp += chain->bytes;
922 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
926 hammer2_io_bqrelse(&chain->dio);
927 hammer2_mtx_unlock(&chain->lock);
931 * Helper to obtain the blockref[] array base and count for a chain.
933 * XXX Not widely used yet, various use cases need to be validated and
934 * converted to use this function.
938 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
940 hammer2_blockref_t *base;
943 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
946 switch(parent->bref.type) {
947 case HAMMER2_BREF_TYPE_INODE:
948 count = HAMMER2_SET_COUNT;
950 case HAMMER2_BREF_TYPE_INDIRECT:
951 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
952 count = parent->bytes / sizeof(hammer2_blockref_t);
954 case HAMMER2_BREF_TYPE_VOLUME:
955 count = HAMMER2_SET_COUNT;
957 case HAMMER2_BREF_TYPE_FREEMAP:
958 count = HAMMER2_SET_COUNT;
961 panic("hammer2_chain_create_indirect: "
962 "unrecognized blockref type: %d",
968 switch(parent->bref.type) {
969 case HAMMER2_BREF_TYPE_INODE:
970 base = &parent->data->ipdata.u.blockset.blockref[0];
971 count = HAMMER2_SET_COUNT;
973 case HAMMER2_BREF_TYPE_INDIRECT:
974 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
975 base = &parent->data->npdata[0];
976 count = parent->bytes / sizeof(hammer2_blockref_t);
978 case HAMMER2_BREF_TYPE_VOLUME:
979 base = &parent->data->voldata.
980 sroot_blockset.blockref[0];
981 count = HAMMER2_SET_COUNT;
983 case HAMMER2_BREF_TYPE_FREEMAP:
984 base = &parent->data->blkset.blockref[0];
985 count = HAMMER2_SET_COUNT;
988 panic("hammer2_chain_create_indirect: "
989 "unrecognized blockref type: %d",
1001 * This counts the number of live blockrefs in a block array and
1002 * also calculates the point at which all remaining blockrefs are empty.
1003 * This routine can only be called on a live chain (DUPLICATED flag not set).
1005 * NOTE: Flag is not set until after the count is complete, allowing
1006 * callers to test the flag without holding the spinlock.
1008 * NOTE: If base is NULL the related chain is still in the INITIAL
1009 * state and there are no blockrefs to count.
1011 * NOTE: live_count may already have some counts accumulated due to
1012 * creation and deletion and could even be initially negative.
1015 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1016 hammer2_blockref_t *base, int count)
1018 hammer2_spin_ex(&chain->core.spin);
1019 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1021 while (--count >= 0) {
1022 if (base[count].type)
1025 chain->core.live_zero = count + 1;
1026 while (count >= 0) {
1027 if (base[count].type)
1028 atomic_add_int(&chain->core.live_count,
1033 chain->core.live_zero = 0;
1035 /* else do not modify live_count */
1036 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1038 hammer2_spin_unex(&chain->core.spin);
1042 * Resize the chain's physical storage allocation in-place. This function does
1043 * not adjust the data pointer and must be followed by (typically) a
1044 * hammer2_chain_modify() call to copy any old data over and adjust the
1047 * Chains can be resized smaller without reallocating the storage. Resizing
1048 * larger will reallocate the storage. Excess or prior storage is reclaimed
1049 * asynchronously at a later time.
1051 * Must be passed an exclusively locked parent and chain.
1053 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1054 * to avoid instantiating a device buffer that conflicts with the vnode data
1055 * buffer. However, because H2 can compress or encrypt data, the chain may
1056 * have a dio assigned to it in those situations, and they do not conflict.
1058 * XXX return error if cannot resize.
1061 hammer2_chain_resize(hammer2_inode_t *ip,
1062 hammer2_chain_t *parent, hammer2_chain_t *chain,
1063 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1064 int nradix, int flags)
1073 * Only data and indirect blocks can be resized for now.
1074 * (The volu root, inodes, and freemap elements use a fixed size).
1076 KKASSERT(chain != &hmp->vchain);
1077 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1078 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1079 KKASSERT(chain->parent == parent);
1082 * Nothing to do if the element is already the proper size
1084 obytes = chain->bytes;
1085 nbytes = 1U << nradix;
1086 if (obytes == nbytes)
1090 * Make sure the old data is instantiated so we can copy it. If this
1091 * is a data block, the device data may be superfluous since the data
1092 * might be in a logical block, but compressed or encrypted data is
1095 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1097 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1100 * Relocate the block, even if making it smaller (because different
1101 * block sizes may be in different regions).
1103 * (data blocks only, we aren't copying the storage here).
1105 hammer2_freemap_alloc(chain, nbytes);
1106 chain->bytes = nbytes;
1107 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1110 * We don't want the followup chain_modify() to try to copy data
1111 * from the old (wrong-sized) buffer. It won't know how much to
1112 * copy. This case should only occur during writes when the
1113 * originator already has the data to write in-hand.
1116 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1117 hammer2_io_brelse(&chain->dio);
1123 * Set the chain modified so its data can be changed by the caller.
1125 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1126 * is a CLC (cluster level change) field and is not updated by parent
1127 * propagation during a flush.
1129 * If the caller passes a non-zero dedup_off we assign data_off to that
1130 * instead of allocating a ne block. Caller must not modify the data already
1131 * present at the target offset.
1134 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1135 hammer2_off_t dedup_off, int flags)
1137 hammer2_blockref_t obref;
1146 obref = chain->bref;
1147 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1150 * Data is not optional for freemap chains (we must always be sure
1151 * to copy the data on COW storage allocations).
1153 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1154 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1155 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1156 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1160 * Data must be resolved if already assigned, unless explicitly
1161 * flagged otherwise.
1163 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1164 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1165 hammer2_chain_load_data(chain);
1169 * Set MODIFIED to indicate that the chain has been modified.
1170 * Set UPDATE to ensure that the blockref is updated in the parent.
1172 if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1173 (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1175 * Modified already set but a new allocation is needed
1176 * anyway because we recorded this data_off for possible
1180 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1182 * Must set modified bit. If the chain has been deleted
1183 * it must be placed on the delayed-flush queue to prevent
1184 * it from possibly being lost (a normal flush of the topology
1185 * will no longer see it).
1187 atomic_add_long(&hammer2_count_modified_chains, 1);
1188 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1189 hammer2_chain_ref(chain);
1190 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1191 if ((chain->flags & HAMMER2_CHAIN_DELETED) &&
1192 (chain->flags & HAMMER2_CHAIN_DELAYED) == 0) {
1193 hammer2_delayed_flush(chain);
1198 * Already flagged modified, no new allocation is needed.
1202 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1203 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1204 hammer2_chain_ref(chain);
1206 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1209 * The modification or re-modification requires an allocation and
1212 * If dedup_off is non-zero, caller already has a data offset
1213 * containing the caller's desired data. The dedup offset is
1214 * allowed to be in a partially free state and we must be sure
1215 * to reset it to a fully allocated state to force two bulkfree
1216 * passes to free it again.
1218 * XXX can a chain already be marked MODIFIED without a data
1219 * assignment? If not, assert here instead of testing the case.
1221 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1222 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1226 chain->bref.data_off = dedup_off;
1227 chain->bytes = 1 << (dedup_off &
1228 HAMMER2_OFF_MASK_RADIX);
1229 atomic_set_int(&chain->flags,
1230 HAMMER2_CHAIN_DEDUP);
1231 hammer2_freemap_adjust(hmp, &chain->bref,
1232 HAMMER2_FREEMAP_DORECOVER);
1234 hammer2_freemap_alloc(chain, chain->bytes);
1236 /* XXX failed allocation */
1241 * Update mirror_tid and modify_tid. modify_tid is only updated
1242 * if not passed as zero (during flushes, parent propagation passes
1245 * NOTE: chain->pmp could be the device spmp.
1247 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1249 chain->bref.modify_tid = mtid;
1252 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1253 * requires updating as well as to tell the delete code that the
1254 * chain's blockref might not exactly match (in terms of physical size
1255 * or block offset) the one in the parent's blocktable. The base key
1256 * of course will still match.
1258 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1259 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1262 * Short-cut data blocks which the caller does not need an actual
1263 * data reference to (aka OPTDATA), as long as the chain does not
1264 * already have a data pointer to the data. This generally means
1265 * that the modifications are being done via the logical buffer cache.
1266 * The INITIAL flag relates only to the device data buffer and thus
1267 * remains unchange in this situation.
1269 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1270 (flags & HAMMER2_MODIFY_OPTDATA) &&
1271 chain->data == NULL) {
1276 * Clearing the INITIAL flag (for indirect blocks) indicates that
1277 * we've processed the uninitialized storage allocation.
1279 * If this flag is already clear we are likely in a copy-on-write
1280 * situation but we have to be sure NOT to bzero the storage if
1281 * no data is present.
1283 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1284 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1291 * Instantiate data buffer and possibly execute COW operation
1293 switch(chain->bref.type) {
1294 case HAMMER2_BREF_TYPE_VOLUME:
1295 case HAMMER2_BREF_TYPE_FREEMAP:
1297 * The data is embedded, no copy-on-write operation is
1300 KKASSERT(chain->dio == NULL);
1302 case HAMMER2_BREF_TYPE_INODE:
1303 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1304 case HAMMER2_BREF_TYPE_DATA:
1305 case HAMMER2_BREF_TYPE_INDIRECT:
1306 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1308 * Perform the copy-on-write operation
1310 * zero-fill or copy-on-write depending on whether
1311 * chain->data exists or not and set the dirty state for
1312 * the new buffer. hammer2_io_new() will handle the
1315 * If a dedup_off was supplied this is an existing block
1316 * and no COW, copy, or further modification is required.
1318 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1320 if (wasinitial && dedup_off == 0) {
1321 error = hammer2_io_new(hmp, chain->bref.data_off,
1322 chain->bytes, &dio);
1324 error = hammer2_io_bread(hmp, chain->bref.data_off,
1325 chain->bytes, &dio);
1327 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1330 * If an I/O error occurs make sure callers cannot accidently
1331 * modify the old buffer's contents and corrupt the filesystem.
1334 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1336 chain->error = HAMMER2_ERROR_IO;
1337 hammer2_io_brelse(&dio);
1338 hammer2_io_brelse(&chain->dio);
1343 bdata = hammer2_io_data(dio, chain->bref.data_off);
1347 * COW (unless a dedup).
1349 KKASSERT(chain->dio != NULL);
1350 if (chain->data != (void *)bdata && dedup_off == 0) {
1351 bcopy(chain->data, bdata, chain->bytes);
1353 } else if (wasinitial == 0) {
1355 * We have a problem. We were asked to COW but
1356 * we don't have any data to COW with!
1358 panic("hammer2_chain_modify: having a COW %p\n",
1363 * Retire the old buffer, replace with the new. Dirty or
1364 * redirty the new buffer.
1366 * WARNING! The system buffer cache may have already flushed
1367 * the buffer, so we must be sure to [re]dirty it
1368 * for further modification.
1370 * If dedup_off was supplied, the caller is not
1371 * expected to make any further modification to the
1375 hammer2_io_bqrelse(&chain->dio);
1376 chain->data = (void *)bdata;
1379 hammer2_io_setdirty(dio);
1382 panic("hammer2_chain_modify: illegal non-embedded type %d",
1389 * setflush on parent indicating that the parent must recurse down
1390 * to us. Do not call on chain itself which might already have it
1394 hammer2_chain_setflush(chain->parent);
1398 * Modify the chain associated with an inode.
1401 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1402 hammer2_tid_t mtid, int flags)
1404 hammer2_inode_modify(ip);
1405 hammer2_chain_modify(chain, mtid, 0, flags);
1409 * Volume header data locks
1412 hammer2_voldata_lock(hammer2_dev_t *hmp)
1414 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1418 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1420 lockmgr(&hmp->vollk, LK_RELEASE);
1424 hammer2_voldata_modify(hammer2_dev_t *hmp)
1426 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1427 atomic_add_long(&hammer2_count_modified_chains, 1);
1428 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1429 hammer2_chain_ref(&hmp->vchain);
1430 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1435 * This function returns the chain at the nearest key within the specified
1436 * range. The returned chain will be referenced but not locked.
1438 * This function will recurse through chain->rbtree as necessary and will
1439 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1440 * the iteration value is less than the current value of *key_nextp.
1442 * The caller should use (*key_nextp) to calculate the actual range of
1443 * the returned element, which will be (key_beg to *key_nextp - 1), because
1444 * there might be another element which is superior to the returned element
1447 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1448 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1449 * it will wind up being (key_end + 1).
1451 * WARNING! Must be called with child's spinlock held. Spinlock remains
1452 * held through the operation.
1454 struct hammer2_chain_find_info {
1455 hammer2_chain_t *best;
1456 hammer2_key_t key_beg;
1457 hammer2_key_t key_end;
1458 hammer2_key_t key_next;
1461 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1462 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1466 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1467 hammer2_key_t key_beg, hammer2_key_t key_end)
1469 struct hammer2_chain_find_info info;
1472 info.key_beg = key_beg;
1473 info.key_end = key_end;
1474 info.key_next = *key_nextp;
1476 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1477 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1479 *key_nextp = info.key_next;
1481 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1482 parent, key_beg, key_end, *key_nextp);
1490 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1492 struct hammer2_chain_find_info *info = data;
1493 hammer2_key_t child_beg;
1494 hammer2_key_t child_end;
1496 child_beg = child->bref.key;
1497 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1499 if (child_end < info->key_beg)
1501 if (child_beg > info->key_end)
1508 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1510 struct hammer2_chain_find_info *info = data;
1511 hammer2_chain_t *best;
1512 hammer2_key_t child_end;
1515 * WARNING! Do not discard DUPLICATED chains, it is possible that
1516 * we are catching an insertion half-way done. If a
1517 * duplicated chain turns out to be the best choice the
1518 * caller will re-check its flags after locking it.
1520 * WARNING! Layerq is scanned forwards, exact matches should keep
1521 * the existing info->best.
1523 if ((best = info->best) == NULL) {
1525 * No previous best. Assign best
1528 } else if (best->bref.key <= info->key_beg &&
1529 child->bref.key <= info->key_beg) {
1534 /*info->best = child;*/
1535 } else if (child->bref.key < best->bref.key) {
1537 * Child has a nearer key and best is not flush with key_beg.
1538 * Set best to child. Truncate key_next to the old best key.
1541 if (info->key_next > best->bref.key || info->key_next == 0)
1542 info->key_next = best->bref.key;
1543 } else if (child->bref.key == best->bref.key) {
1545 * If our current best is flush with the child then this
1546 * is an illegal overlap.
1548 * key_next will automatically be limited to the smaller of
1549 * the two end-points.
1555 * Keep the current best but truncate key_next to the child's
1558 * key_next will also automatically be limited to the smaller
1559 * of the two end-points (probably not necessary for this case
1560 * but we do it anyway).
1562 if (info->key_next > child->bref.key || info->key_next == 0)
1563 info->key_next = child->bref.key;
1567 * Always truncate key_next based on child's end-of-range.
1569 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1570 if (child_end && (info->key_next > child_end || info->key_next == 0))
1571 info->key_next = child_end;
1577 * Retrieve the specified chain from a media blockref, creating the
1578 * in-memory chain structure which reflects it.
1580 * To handle insertion races pass the INSERT_RACE flag along with the
1581 * generation number of the core. NULL will be returned if the generation
1582 * number changes before we have a chance to insert the chain. Insert
1583 * races can occur because the parent might be held shared.
1585 * Caller must hold the parent locked shared or exclusive since we may
1586 * need the parent's bref array to find our block.
1588 * WARNING! chain->pmp is always set to NULL for any chain representing
1589 * part of the super-root topology.
1592 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1593 hammer2_blockref_t *bref)
1595 hammer2_dev_t *hmp = parent->hmp;
1596 hammer2_chain_t *chain;
1600 * Allocate a chain structure representing the existing media
1601 * entry. Resulting chain has one ref and is not locked.
1603 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1604 chain = hammer2_chain_alloc(hmp, NULL, bref);
1606 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1607 /* ref'd chain returned */
1610 * Flag that the chain is in the parent's blockmap so delete/flush
1611 * knows what to do with it.
1613 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1616 * Link the chain into its parent. A spinlock is required to safely
1617 * access the RBTREE, and it is possible to collide with another
1618 * hammer2_chain_get() operation because the caller might only hold
1619 * a shared lock on the parent.
1621 KKASSERT(parent->refs > 0);
1622 error = hammer2_chain_insert(parent, chain,
1623 HAMMER2_CHAIN_INSERT_SPIN |
1624 HAMMER2_CHAIN_INSERT_RACE,
1627 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1628 kprintf("chain %p get race\n", chain);
1629 hammer2_chain_drop(chain);
1632 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1636 * Return our new chain referenced but not locked, or NULL if
1643 * Lookup initialization/completion API
1646 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1648 hammer2_chain_ref(parent);
1649 if (flags & HAMMER2_LOOKUP_SHARED) {
1650 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1651 HAMMER2_RESOLVE_SHARED);
1653 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1659 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1662 hammer2_chain_unlock(parent);
1663 hammer2_chain_drop(parent);
1668 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1670 hammer2_chain_t *oparent;
1671 hammer2_chain_t *nparent;
1674 * Be careful of order, oparent must be unlocked before nparent
1675 * is locked below to avoid a deadlock.
1678 hammer2_spin_ex(&oparent->core.spin);
1679 nparent = oparent->parent;
1680 hammer2_chain_ref(nparent);
1681 hammer2_spin_unex(&oparent->core.spin);
1683 hammer2_chain_unlock(oparent);
1684 hammer2_chain_drop(oparent);
1688 hammer2_chain_lock(nparent, how);
1695 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1696 * (*parentp) typically points to an inode but can also point to a related
1697 * indirect block and this function will recurse upwards and find the inode
1700 * (*parentp) must be exclusively locked and referenced and can be an inode
1701 * or an existing indirect block within the inode.
1703 * On return (*parentp) will be modified to point at the deepest parent chain
1704 * element encountered during the search, as a helper for an insertion or
1705 * deletion. The new (*parentp) will be locked and referenced and the old
1706 * will be unlocked and dereferenced (no change if they are both the same).
1708 * The matching chain will be returned exclusively locked. If NOLOCK is
1709 * requested the chain will be returned only referenced. Note that the
1710 * parent chain must always be locked shared or exclusive, matching the
1711 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1712 * when NOLOCK is specified but that complicates matters if *parentp must
1713 * inherit the chain.
1715 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1716 * data pointer or can otherwise be in flux.
1718 * NULL is returned if no match was found, but (*parentp) will still
1719 * potentially be adjusted.
1721 * If a fatal error occurs (typically an I/O error), a dummy chain is
1722 * returned with chain->error and error-identifying information set. This
1723 * chain will assert if you try to do anything fancy with it.
1725 * XXX Depending on where the error occurs we should allow continued iteration.
1727 * On return (*key_nextp) will point to an iterative value for key_beg.
1728 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1730 * This function will also recurse up the chain if the key is not within the
1731 * current parent's range. (*parentp) can never be set to NULL. An iteration
1732 * can simply allow (*parentp) to float inside the loop.
1734 * NOTE! chain->data is not always resolved. By default it will not be
1735 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1736 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1737 * BREF_TYPE_DATA as the device buffer can alias the logical file
1741 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1742 hammer2_key_t key_beg, hammer2_key_t key_end,
1743 int *cache_indexp, int flags)
1746 hammer2_chain_t *parent;
1747 hammer2_chain_t *chain;
1748 hammer2_blockref_t *base;
1749 hammer2_blockref_t *bref;
1750 hammer2_blockref_t bcopy;
1751 hammer2_key_t scan_beg;
1752 hammer2_key_t scan_end;
1754 int how_always = HAMMER2_RESOLVE_ALWAYS;
1755 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1758 int maxloops = 300000;
1760 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1761 how_maybe = how_always;
1762 how = HAMMER2_RESOLVE_ALWAYS;
1763 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1764 how = HAMMER2_RESOLVE_NEVER;
1766 how = HAMMER2_RESOLVE_MAYBE;
1768 if (flags & HAMMER2_LOOKUP_SHARED) {
1769 how_maybe |= HAMMER2_RESOLVE_SHARED;
1770 how_always |= HAMMER2_RESOLVE_SHARED;
1771 how |= HAMMER2_RESOLVE_SHARED;
1775 * Recurse (*parentp) upward if necessary until the parent completely
1776 * encloses the key range or we hit the inode.
1778 * This function handles races against the flusher doing a delete-
1779 * duplicate above us and re-homes the parent to the duplicate in
1780 * that case, otherwise we'd wind up recursing down a stale chain.
1785 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1786 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1787 scan_beg = parent->bref.key;
1788 scan_end = scan_beg +
1789 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1790 if (key_beg >= scan_beg && key_end <= scan_end)
1792 parent = hammer2_chain_getparent(parentp, how_maybe);
1796 if (--maxloops == 0)
1797 panic("hammer2_chain_lookup: maxloops");
1799 * Locate the blockref array. Currently we do a fully associative
1800 * search through the array.
1802 switch(parent->bref.type) {
1803 case HAMMER2_BREF_TYPE_INODE:
1805 * Special shortcut for embedded data returns the inode
1806 * itself. Callers must detect this condition and access
1807 * the embedded data (the strategy code does this for us).
1809 * This is only applicable to regular files and softlinks.
1811 if (parent->data->ipdata.meta.op_flags &
1812 HAMMER2_OPFLAG_DIRECTDATA) {
1813 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1815 *key_nextp = key_end + 1;
1818 hammer2_chain_ref(parent);
1819 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1820 hammer2_chain_lock(parent, how_always);
1821 *key_nextp = key_end + 1;
1824 base = &parent->data->ipdata.u.blockset.blockref[0];
1825 count = HAMMER2_SET_COUNT;
1827 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1828 case HAMMER2_BREF_TYPE_INDIRECT:
1830 * Handle MATCHIND on the parent
1832 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1833 scan_beg = parent->bref.key;
1834 scan_end = scan_beg +
1835 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1836 if (key_beg == scan_beg && key_end == scan_end) {
1838 hammer2_chain_ref(chain);
1839 hammer2_chain_lock(chain, how_maybe);
1840 *key_nextp = scan_end + 1;
1845 * Optimize indirect blocks in the INITIAL state to avoid
1848 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1851 if (parent->data == NULL)
1852 panic("parent->data is NULL");
1853 base = &parent->data->npdata[0];
1855 count = parent->bytes / sizeof(hammer2_blockref_t);
1857 case HAMMER2_BREF_TYPE_VOLUME:
1858 base = &parent->data->voldata.sroot_blockset.blockref[0];
1859 count = HAMMER2_SET_COUNT;
1861 case HAMMER2_BREF_TYPE_FREEMAP:
1862 base = &parent->data->blkset.blockref[0];
1863 count = HAMMER2_SET_COUNT;
1866 kprintf("hammer2_chain_lookup: unrecognized "
1867 "blockref(B) type: %d",
1870 tsleep(&base, 0, "dead", 0);
1871 panic("hammer2_chain_lookup: unrecognized "
1872 "blockref(B) type: %d",
1874 base = NULL; /* safety */
1875 count = 0; /* safety */
1879 * Merged scan to find next candidate.
1881 * hammer2_base_*() functions require the parent->core.live_* fields
1882 * to be synchronized.
1884 * We need to hold the spinlock to access the block array and RB tree
1885 * and to interlock chain creation.
1887 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1888 hammer2_chain_countbrefs(parent, base, count);
1893 hammer2_spin_ex(&parent->core.spin);
1894 chain = hammer2_combined_find(parent, base, count,
1895 cache_indexp, key_nextp,
1898 generation = parent->core.generation;
1901 * Exhausted parent chain, iterate.
1904 hammer2_spin_unex(&parent->core.spin);
1905 if (key_beg == key_end) /* short cut single-key case */
1909 * Stop if we reached the end of the iteration.
1911 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1912 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1917 * Calculate next key, stop if we reached the end of the
1918 * iteration, otherwise go up one level and loop.
1920 key_beg = parent->bref.key +
1921 ((hammer2_key_t)1 << parent->bref.keybits);
1922 if (key_beg == 0 || key_beg > key_end)
1924 parent = hammer2_chain_getparent(parentp, how_maybe);
1929 * Selected from blockref or in-memory chain.
1931 if (chain == NULL) {
1933 hammer2_spin_unex(&parent->core.spin);
1934 chain = hammer2_chain_get(parent, generation,
1936 if (chain == NULL) {
1937 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1938 parent, key_beg, key_end);
1941 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1942 hammer2_chain_drop(chain);
1946 hammer2_chain_ref(chain);
1947 hammer2_spin_unex(&parent->core.spin);
1951 * chain is referenced but not locked. We must lock the chain
1952 * to obtain definitive DUPLICATED/DELETED state
1954 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1955 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1956 hammer2_chain_lock(chain, how_maybe);
1958 hammer2_chain_lock(chain, how);
1962 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1964 * NOTE: Chain's key range is not relevant as there might be
1965 * one-offs within the range that are not deleted.
1967 * NOTE: Lookups can race delete-duplicate because
1968 * delete-duplicate does not lock the parent's core
1969 * (they just use the spinlock on the core). We must
1970 * check for races by comparing the DUPLICATED flag before
1971 * releasing the spinlock with the flag after locking the
1974 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1975 hammer2_chain_unlock(chain);
1976 hammer2_chain_drop(chain);
1977 key_beg = *key_nextp;
1978 if (key_beg == 0 || key_beg > key_end)
1984 * If the chain element is an indirect block it becomes the new
1985 * parent and we loop on it. We must maintain our top-down locks
1986 * to prevent the flusher from interfering (i.e. doing a
1987 * delete-duplicate and leaving us recursing down a deleted chain).
1989 * The parent always has to be locked with at least RESOLVE_MAYBE
1990 * so we can access its data. It might need a fixup if the caller
1991 * passed incompatible flags. Be careful not to cause a deadlock
1992 * as a data-load requires an exclusive lock.
1994 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1995 * range is within the requested key range we return the indirect
1996 * block and do NOT loop. This is usually only used to acquire
1999 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2000 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2001 hammer2_chain_unlock(parent);
2002 hammer2_chain_drop(parent);
2003 *parentp = parent = chain;
2008 * All done, return the chain.
2010 * If the caller does not want a locked chain, replace the lock with
2011 * a ref. Perhaps this can eventually be optimized to not obtain the
2012 * lock in the first place for situations where the data does not
2013 * need to be resolved.
2016 if (flags & HAMMER2_LOOKUP_NOLOCK)
2017 hammer2_chain_unlock(chain);
2024 * After having issued a lookup we can iterate all matching keys.
2026 * If chain is non-NULL we continue the iteration from just after it's index.
2028 * If chain is NULL we assume the parent was exhausted and continue the
2029 * iteration at the next parent.
2031 * If a fatal error occurs (typically an I/O error), a dummy chain is
2032 * returned with chain->error and error-identifying information set. This
2033 * chain will assert if you try to do anything fancy with it.
2035 * XXX Depending on where the error occurs we should allow continued iteration.
2037 * parent must be locked on entry and remains locked throughout. chain's
2038 * lock status must match flags. Chain is always at least referenced.
2040 * WARNING! The MATCHIND flag does not apply to this function.
2043 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2044 hammer2_key_t *key_nextp,
2045 hammer2_key_t key_beg, hammer2_key_t key_end,
2046 int *cache_indexp, int flags)
2048 hammer2_chain_t *parent;
2052 * Calculate locking flags for upward recursion.
2054 how_maybe = HAMMER2_RESOLVE_MAYBE;
2055 if (flags & HAMMER2_LOOKUP_SHARED)
2056 how_maybe |= HAMMER2_RESOLVE_SHARED;
2061 * Calculate the next index and recalculate the parent if necessary.
2064 key_beg = chain->bref.key +
2065 ((hammer2_key_t)1 << chain->bref.keybits);
2066 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2067 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2068 hammer2_chain_unlock(chain);
2070 hammer2_chain_drop(chain);
2073 * chain invalid past this point, but we can still do a
2074 * pointer comparison w/parent.
2076 * Any scan where the lookup returned degenerate data embedded
2077 * in the inode has an invalid index and must terminate.
2079 if (chain == parent)
2081 if (key_beg == 0 || key_beg > key_end)
2084 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2085 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2087 * We reached the end of the iteration.
2092 * Continue iteration with next parent unless the current
2093 * parent covers the range.
2095 key_beg = parent->bref.key +
2096 ((hammer2_key_t)1 << parent->bref.keybits);
2097 if (key_beg == 0 || key_beg > key_end)
2099 parent = hammer2_chain_getparent(parentp, how_maybe);
2105 return (hammer2_chain_lookup(parentp, key_nextp,
2107 cache_indexp, flags));
2111 * The raw scan function is similar to lookup/next but does not seek to a key.
2112 * Blockrefs are iterated via first_bref = (parent, NULL) and
2113 * next_chain = (parent, bref).
2115 * The passed-in parent must be locked and its data resolved. The function
2116 * nominally returns a locked and referenced *chainp != NULL for chains
2117 * the caller might need to recurse on (and will dipose of any *chainp passed
2118 * in). The caller must check the chain->bref.type either way.
2120 * *chainp is not set for leaf elements.
2122 * This function takes a pointer to a stack-based bref structure whos
2123 * contents is updated for each iteration. The same pointer is returned,
2124 * or NULL when the iteration is complete. *firstp must be set to 1 for
2125 * the first ieration. This function will set it to 0.
2127 hammer2_blockref_t *
2128 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2129 hammer2_blockref_t *bref, int *firstp,
2130 int *cache_indexp, int flags)
2133 hammer2_blockref_t *base;
2134 hammer2_blockref_t *bref_ptr;
2136 hammer2_key_t next_key;
2137 hammer2_chain_t *chain = NULL;
2139 int how_always = HAMMER2_RESOLVE_ALWAYS;
2140 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2143 int maxloops = 300000;
2148 * Scan flags borrowed from lookup.
2150 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2151 how_maybe = how_always;
2152 how = HAMMER2_RESOLVE_ALWAYS;
2153 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2154 how = HAMMER2_RESOLVE_NEVER;
2156 how = HAMMER2_RESOLVE_MAYBE;
2158 if (flags & HAMMER2_LOOKUP_SHARED) {
2159 how_maybe |= HAMMER2_RESOLVE_SHARED;
2160 how_always |= HAMMER2_RESOLVE_SHARED;
2161 how |= HAMMER2_RESOLVE_SHARED;
2165 * Calculate key to locate first/next element, unlocking the previous
2166 * element as we go. Be careful, the key calculation can overflow.
2168 * (also reset bref to NULL)
2174 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2175 if ((chain = *chainp) != NULL) {
2177 hammer2_chain_unlock(chain);
2178 hammer2_chain_drop(chain);
2188 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2189 if (--maxloops == 0)
2190 panic("hammer2_chain_scan: maxloops");
2192 * Locate the blockref array. Currently we do a fully associative
2193 * search through the array.
2195 switch(parent->bref.type) {
2196 case HAMMER2_BREF_TYPE_INODE:
2198 * An inode with embedded data has no sub-chains.
2200 * WARNING! Bulk scan code may pass a static chain marked
2201 * as BREF_TYPE_INODE with a copy of the volume
2202 * root blockset to snapshot the volume.
2204 if (parent->data->ipdata.meta.op_flags &
2205 HAMMER2_OPFLAG_DIRECTDATA) {
2209 base = &parent->data->ipdata.u.blockset.blockref[0];
2210 count = HAMMER2_SET_COUNT;
2212 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2213 case HAMMER2_BREF_TYPE_INDIRECT:
2215 * Optimize indirect blocks in the INITIAL state to avoid
2218 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2221 if (parent->data == NULL)
2222 panic("parent->data is NULL");
2223 base = &parent->data->npdata[0];
2225 count = parent->bytes / sizeof(hammer2_blockref_t);
2227 case HAMMER2_BREF_TYPE_VOLUME:
2228 base = &parent->data->voldata.sroot_blockset.blockref[0];
2229 count = HAMMER2_SET_COUNT;
2231 case HAMMER2_BREF_TYPE_FREEMAP:
2232 base = &parent->data->blkset.blockref[0];
2233 count = HAMMER2_SET_COUNT;
2236 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2238 base = NULL; /* safety */
2239 count = 0; /* safety */
2243 * Merged scan to find next candidate.
2245 * hammer2_base_*() functions require the parent->core.live_* fields
2246 * to be synchronized.
2248 * We need to hold the spinlock to access the block array and RB tree
2249 * and to interlock chain creation.
2251 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2252 hammer2_chain_countbrefs(parent, base, count);
2256 hammer2_spin_ex(&parent->core.spin);
2257 chain = hammer2_combined_find(parent, base, count,
2258 cache_indexp, &next_key,
2259 key, HAMMER2_KEY_MAX,
2261 generation = parent->core.generation;
2264 * Exhausted parent chain, we're done.
2266 if (bref_ptr == NULL) {
2267 hammer2_spin_unex(&parent->core.spin);
2268 KKASSERT(chain == NULL);
2274 * Copy into the supplied stack-based blockref.
2279 * Selected from blockref or in-memory chain.
2281 if (chain == NULL) {
2282 switch(bref->type) {
2283 case HAMMER2_BREF_TYPE_INODE:
2284 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2285 case HAMMER2_BREF_TYPE_INDIRECT:
2286 case HAMMER2_BREF_TYPE_VOLUME:
2287 case HAMMER2_BREF_TYPE_FREEMAP:
2289 * Recursion, always get the chain
2291 hammer2_spin_unex(&parent->core.spin);
2292 chain = hammer2_chain_get(parent, generation, bref);
2293 if (chain == NULL) {
2294 kprintf("retry scan parent %p keys %016jx\n",
2298 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2299 hammer2_chain_drop(chain);
2306 * No recursion, do not waste time instantiating
2307 * a chain, just iterate using the bref.
2309 hammer2_spin_unex(&parent->core.spin);
2314 * Recursion or not we need the chain in order to supply
2317 hammer2_chain_ref(chain);
2318 hammer2_spin_unex(&parent->core.spin);
2322 * chain is referenced but not locked. We must lock the chain
2323 * to obtain definitive DUPLICATED/DELETED state
2326 hammer2_chain_lock(chain, how);
2329 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2331 * NOTE: chain's key range is not relevant as there might be
2332 * one-offs within the range that are not deleted.
2334 * NOTE: XXX this could create problems with scans used in
2335 * situations other than mount-time recovery.
2337 * NOTE: Lookups can race delete-duplicate because
2338 * delete-duplicate does not lock the parent's core
2339 * (they just use the spinlock on the core). We must
2340 * check for races by comparing the DUPLICATED flag before
2341 * releasing the spinlock with the flag after locking the
2344 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2345 hammer2_chain_unlock(chain);
2346 hammer2_chain_drop(chain);
2359 * All done, return the bref or NULL, supply chain if necessary.
2367 * Create and return a new hammer2 system memory structure of the specified
2368 * key, type and size and insert it under (*parentp). This is a full
2369 * insertion, based on the supplied key/keybits, and may involve creating
2370 * indirect blocks and moving other chains around via delete/duplicate.
2372 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2373 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2374 * FULL. This typically means that the caller is creating the chain after
2375 * doing a hammer2_chain_lookup().
2377 * (*parentp) must be exclusive locked and may be replaced on return
2378 * depending on how much work the function had to do.
2380 * (*parentp) must not be errored or this function will assert.
2382 * (*chainp) usually starts out NULL and returns the newly created chain,
2383 * but if the caller desires the caller may allocate a disconnected chain
2384 * and pass it in instead.
2386 * This function should NOT be used to insert INDIRECT blocks. It is
2387 * typically used to create/insert inodes and data blocks.
2389 * Caller must pass-in an exclusively locked parent the new chain is to
2390 * be inserted under, and optionally pass-in a disconnected, exclusively
2391 * locked chain to insert (else we create a new chain). The function will
2392 * adjust (*parentp) as necessary, create or connect the chain, and
2393 * return an exclusively locked chain in *chainp.
2395 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2396 * and will be reassigned.
2399 hammer2_chain_create(hammer2_chain_t **parentp,
2400 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2401 hammer2_key_t key, int keybits, int type, size_t bytes,
2402 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2405 hammer2_chain_t *chain;
2406 hammer2_chain_t *parent;
2407 hammer2_blockref_t *base;
2408 hammer2_blockref_t dummy;
2412 int maxloops = 300000;
2415 * Topology may be crossing a PFS boundary.
2418 KKASSERT(hammer2_mtx_owned(&parent->lock));
2419 KKASSERT(parent->error == 0);
2423 if (chain == NULL) {
2425 * First allocate media space and construct the dummy bref,
2426 * then allocate the in-memory chain structure. Set the
2427 * INITIAL flag for fresh chains which do not have embedded
2430 * XXX for now set the check mode of the child based on
2431 * the parent or, if the parent is an inode, the
2432 * specification in the inode.
2434 bzero(&dummy, sizeof(dummy));
2437 dummy.keybits = keybits;
2438 dummy.data_off = hammer2_getradix(bytes);
2439 dummy.methods = parent->bref.methods;
2440 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2442 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2443 dummy.methods |= HAMMER2_ENC_CHECK(
2444 parent->data->ipdata.meta.check_algo);
2447 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2450 * Lock the chain manually, chain_lock will load the chain
2451 * which we do NOT want to do. (note: chain->refs is set
2452 * to 1 by chain_alloc() for us, but lockcnt is not).
2455 hammer2_mtx_ex(&chain->lock);
2457 ++curthread->td_tracker;
2460 * Set INITIAL to optimize I/O. The flag will generally be
2461 * processed when we call hammer2_chain_modify().
2463 * Recalculate bytes to reflect the actual media block
2466 bytes = (hammer2_off_t)1 <<
2467 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2468 chain->bytes = bytes;
2471 case HAMMER2_BREF_TYPE_VOLUME:
2472 case HAMMER2_BREF_TYPE_FREEMAP:
2473 panic("hammer2_chain_create: called with volume type");
2475 case HAMMER2_BREF_TYPE_INDIRECT:
2476 panic("hammer2_chain_create: cannot be used to"
2477 "create indirect block");
2479 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2480 panic("hammer2_chain_create: cannot be used to"
2481 "create freemap root or node");
2483 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2484 KKASSERT(bytes == sizeof(chain->data->bmdata));
2486 case HAMMER2_BREF_TYPE_INODE:
2487 case HAMMER2_BREF_TYPE_DATA:
2490 * leave chain->data NULL, set INITIAL
2492 KKASSERT(chain->data == NULL);
2493 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2498 * We are reattaching a previously deleted chain, possibly
2499 * under a new parent and possibly with a new key/keybits.
2500 * The chain does not have to be in a modified state. The
2501 * UPDATE flag will be set later on in this routine.
2503 * Do NOT mess with the current state of the INITIAL flag.
2505 chain->bref.key = key;
2506 chain->bref.keybits = keybits;
2507 if (chain->flags & HAMMER2_CHAIN_DELETED)
2508 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2509 KKASSERT(chain->parent == NULL);
2511 if (flags & HAMMER2_INSERT_PFSROOT)
2512 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2514 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2517 * Calculate how many entries we have in the blockref array and
2518 * determine if an indirect block is required.
2521 if (--maxloops == 0)
2522 panic("hammer2_chain_create: maxloops");
2524 switch(parent->bref.type) {
2525 case HAMMER2_BREF_TYPE_INODE:
2526 KKASSERT((parent->data->ipdata.meta.op_flags &
2527 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2528 KKASSERT(parent->data != NULL);
2529 base = &parent->data->ipdata.u.blockset.blockref[0];
2530 count = HAMMER2_SET_COUNT;
2532 case HAMMER2_BREF_TYPE_INDIRECT:
2533 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2534 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2537 base = &parent->data->npdata[0];
2538 count = parent->bytes / sizeof(hammer2_blockref_t);
2540 case HAMMER2_BREF_TYPE_VOLUME:
2541 KKASSERT(parent->data != NULL);
2542 base = &parent->data->voldata.sroot_blockset.blockref[0];
2543 count = HAMMER2_SET_COUNT;
2545 case HAMMER2_BREF_TYPE_FREEMAP:
2546 KKASSERT(parent->data != NULL);
2547 base = &parent->data->blkset.blockref[0];
2548 count = HAMMER2_SET_COUNT;
2551 panic("hammer2_chain_create: unrecognized blockref type: %d",
2559 * Make sure we've counted the brefs
2561 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2562 hammer2_chain_countbrefs(parent, base, count);
2564 KKASSERT(parent->core.live_count >= 0 &&
2565 parent->core.live_count <= count);
2568 * If no free blockref could be found we must create an indirect
2569 * block and move a number of blockrefs into it. With the parent
2570 * locked we can safely lock each child in order to delete+duplicate
2571 * it without causing a deadlock.
2573 * This may return the new indirect block or the old parent depending
2574 * on where the key falls. NULL is returned on error.
2576 if (parent->core.live_count == count) {
2577 hammer2_chain_t *nparent;
2579 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2580 mtid, type, &error);
2581 if (nparent == NULL) {
2583 hammer2_chain_drop(chain);
2587 if (parent != nparent) {
2588 hammer2_chain_unlock(parent);
2589 hammer2_chain_drop(parent);
2590 parent = *parentp = nparent;
2596 * Link the chain into its parent.
2598 if (chain->parent != NULL)
2599 panic("hammer2: hammer2_chain_create: chain already connected");
2600 KKASSERT(chain->parent == NULL);
2601 hammer2_chain_insert(parent, chain,
2602 HAMMER2_CHAIN_INSERT_SPIN |
2603 HAMMER2_CHAIN_INSERT_LIVE,
2608 * Mark the newly created chain modified. This will cause
2609 * UPDATE to be set and process the INITIAL flag.
2611 * Device buffers are not instantiated for DATA elements
2612 * as these are handled by logical buffers.
2614 * Indirect and freemap node indirect blocks are handled
2615 * by hammer2_chain_create_indirect() and not by this
2618 * Data for all other bref types is expected to be
2619 * instantiated (INODE, LEAF).
2621 switch(chain->bref.type) {
2622 case HAMMER2_BREF_TYPE_DATA:
2623 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2624 case HAMMER2_BREF_TYPE_INODE:
2625 hammer2_chain_modify(chain, mtid, dedup_off,
2626 HAMMER2_MODIFY_OPTDATA);
2630 * Remaining types are not supported by this function.
2631 * In particular, INDIRECT and LEAF_NODE types are
2632 * handled by create_indirect().
2634 panic("hammer2_chain_create: bad type: %d",
2641 * When reconnecting a chain we must set UPDATE and
2642 * setflush so the flush recognizes that it must update
2643 * the bref in the parent.
2645 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2646 hammer2_chain_ref(chain);
2647 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2652 * We must setflush(parent) to ensure that it recurses through to
2653 * chain. setflush(chain) might not work because ONFLUSH is possibly
2654 * already set in the chain (so it won't recurse up to set it in the
2657 hammer2_chain_setflush(parent);
2666 * Move the chain from its old parent to a new parent. The chain must have
2667 * already been deleted or already disconnected (or never associated) with
2668 * a parent. The chain is reassociated with the new parent and the deleted
2669 * flag will be cleared (no longer deleted). The chain's modification state
2672 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2673 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2674 * FULL. This typically means that the caller is creating the chain after
2675 * doing a hammer2_chain_lookup().
2677 * A non-NULL bref is typically passed when key and keybits must be overridden.
2678 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2679 * from a passed-in bref and uses the old chain's bref for everything else.
2681 * Neither (parent) or (chain) can be errored.
2683 * If (parent) is non-NULL then the new duplicated chain is inserted under
2686 * If (parent) is NULL then the newly duplicated chain is not inserted
2687 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2688 * passing into hammer2_chain_create() after this function returns).
2690 * WARNING! This function calls create which means it can insert indirect
2691 * blocks. This can cause other unrelated chains in the parent to
2692 * be moved to a newly inserted indirect block in addition to the
2696 hammer2_chain_rename(hammer2_blockref_t *bref,
2697 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2698 hammer2_tid_t mtid, int flags)
2701 hammer2_chain_t *parent;
2705 * WARNING! We should never resolve DATA to device buffers
2706 * (XXX allow it if the caller did?), and since
2707 * we currently do not have the logical buffer cache
2708 * buffer in-hand to fix its cached physical offset
2709 * we also force the modify code to not COW it. XXX
2712 KKASSERT(chain->parent == NULL);
2713 KKASSERT(chain->error == 0);
2716 * Now create a duplicate of the chain structure, associating
2717 * it with the same core, making it the same size, pointing it
2718 * to the same bref (the same media block).
2721 bref = &chain->bref;
2722 bytes = (hammer2_off_t)1 <<
2723 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2726 * If parent is not NULL the duplicated chain will be entered under
2727 * the parent and the UPDATE bit set to tell flush to update
2730 * We must setflush(parent) to ensure that it recurses through to
2731 * chain. setflush(chain) might not work because ONFLUSH is possibly
2732 * already set in the chain (so it won't recurse up to set it in the
2735 * Having both chains locked is extremely important for atomicy.
2737 if (parentp && (parent = *parentp) != NULL) {
2738 KKASSERT(hammer2_mtx_owned(&parent->lock));
2739 KKASSERT(parent->refs > 0);
2740 KKASSERT(parent->error == 0);
2742 hammer2_chain_create(parentp, &chain, chain->pmp,
2743 bref->key, bref->keybits, bref->type,
2744 chain->bytes, mtid, 0, flags);
2745 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2746 hammer2_chain_setflush(*parentp);
2751 * Helper function for deleting chains.
2753 * The chain is removed from the live view (the RBTREE) as well as the parent's
2754 * blockmap. Both chain and its parent must be locked.
2756 * parent may not be errored. chain can be errored.
2759 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2760 hammer2_tid_t mtid, int flags)
2764 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2765 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2766 KKASSERT(chain->parent == parent);
2769 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2771 * Chain is blockmapped, so there must be a parent.
2772 * Atomically remove the chain from the parent and remove
2773 * the blockmap entry.
2775 hammer2_blockref_t *base;
2778 KKASSERT(parent != NULL);
2779 KKASSERT(parent->error == 0);
2780 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2781 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2784 * Calculate blockmap pointer
2786 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2787 hammer2_spin_ex(&parent->core.spin);
2789 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2790 atomic_add_int(&parent->core.live_count, -1);
2791 ++parent->core.generation;
2792 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2793 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2794 --parent->core.chain_count;
2795 chain->parent = NULL;
2797 switch(parent->bref.type) {
2798 case HAMMER2_BREF_TYPE_INODE:
2800 * Access the inode's block array. However, there
2801 * is no block array if the inode is flagged
2802 * DIRECTDATA. The DIRECTDATA case typicaly only
2803 * occurs when a hardlink has been shifted up the
2804 * tree and the original inode gets replaced with
2805 * an OBJTYPE_HARDLINK placeholding inode.
2808 (parent->data->ipdata.meta.op_flags &
2809 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2811 &parent->data->ipdata.u.blockset.blockref[0];
2815 count = HAMMER2_SET_COUNT;
2817 case HAMMER2_BREF_TYPE_INDIRECT:
2818 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2820 base = &parent->data->npdata[0];
2823 count = parent->bytes / sizeof(hammer2_blockref_t);
2825 case HAMMER2_BREF_TYPE_VOLUME:
2826 base = &parent->data->voldata.
2827 sroot_blockset.blockref[0];
2828 count = HAMMER2_SET_COUNT;
2830 case HAMMER2_BREF_TYPE_FREEMAP:
2831 base = &parent->data->blkset.blockref[0];
2832 count = HAMMER2_SET_COUNT;
2837 panic("hammer2_flush_pass2: "
2838 "unrecognized blockref type: %d",
2843 * delete blockmapped chain from its parent.
2845 * The parent is not affected by any statistics in chain
2846 * which are pending synchronization. That is, there is
2847 * nothing to undo in the parent since they have not yet
2848 * been incorporated into the parent.
2850 * The parent is affected by statistics stored in inodes.
2851 * Those have already been synchronized, so they must be
2852 * undone. XXX split update possible w/delete in middle?
2855 int cache_index = -1;
2856 hammer2_base_delete(parent, base, count,
2857 &cache_index, chain);
2859 hammer2_spin_unex(&parent->core.spin);
2860 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2862 * Chain is not blockmapped but a parent is present.
2863 * Atomically remove the chain from the parent. There is
2864 * no blockmap entry to remove.
2866 * Because chain was associated with a parent but not
2867 * synchronized, the chain's *_count_up fields contain
2868 * inode adjustment statistics which must be undone.
2870 hammer2_spin_ex(&parent->core.spin);
2871 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2872 atomic_add_int(&parent->core.live_count, -1);
2873 ++parent->core.generation;
2874 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2875 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2876 --parent->core.chain_count;
2877 chain->parent = NULL;
2878 hammer2_spin_unex(&parent->core.spin);
2881 * Chain is not blockmapped and has no parent. This
2882 * is a degenerate case.
2884 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2889 * Create an indirect block that covers one or more of the elements in the
2890 * current parent. Either returns the existing parent with no locking or
2891 * ref changes or returns the new indirect block locked and referenced
2892 * and leaving the original parent lock/ref intact as well.
2894 * If an error occurs, NULL is returned and *errorp is set to the error.
2896 * The returned chain depends on where the specified key falls.
2898 * The key/keybits for the indirect mode only needs to follow three rules:
2900 * (1) That all elements underneath it fit within its key space and
2902 * (2) That all elements outside it are outside its key space.
2904 * (3) When creating the new indirect block any elements in the current
2905 * parent that fit within the new indirect block's keyspace must be
2906 * moved into the new indirect block.
2908 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2909 * keyspace the the current parent, but lookup/iteration rules will
2910 * ensure (and must ensure) that rule (2) for all parents leading up
2911 * to the nearest inode or the root volume header is adhered to. This
2912 * is accomplished by always recursing through matching keyspaces in
2913 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2915 * The current implementation calculates the current worst-case keyspace by
2916 * iterating the current parent and then divides it into two halves, choosing
2917 * whichever half has the most elements (not necessarily the half containing
2918 * the requested key).
2920 * We can also opt to use the half with the least number of elements. This
2921 * causes lower-numbered keys (aka logical file offsets) to recurse through
2922 * fewer indirect blocks and higher-numbered keys to recurse through more.
2923 * This also has the risk of not moving enough elements to the new indirect
2924 * block and being forced to create several indirect blocks before the element
2927 * Must be called with an exclusively locked parent.
2929 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2930 hammer2_key_t *keyp, int keybits,
2931 hammer2_blockref_t *base, int count);
2932 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2933 hammer2_key_t *keyp, int keybits,
2934 hammer2_blockref_t *base, int count);
2937 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2938 hammer2_key_t create_key, int create_bits,
2939 hammer2_tid_t mtid, int for_type, int *errorp)
2942 hammer2_blockref_t *base;
2943 hammer2_blockref_t *bref;
2944 hammer2_blockref_t bcopy;
2945 hammer2_chain_t *chain;
2946 hammer2_chain_t *ichain;
2947 hammer2_chain_t dummy;
2948 hammer2_key_t key = create_key;
2949 hammer2_key_t key_beg;
2950 hammer2_key_t key_end;
2951 hammer2_key_t key_next;
2952 int keybits = create_bits;
2959 int maxloops = 300000;
2962 * Calculate the base blockref pointer or NULL if the chain
2963 * is known to be empty. We need to calculate the array count
2964 * for RB lookups either way.
2968 KKASSERT(hammer2_mtx_owned(&parent->lock));
2970 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2971 base = hammer2_chain_base_and_count(parent, &count);
2974 * dummy used in later chain allocation (no longer used for lookups).
2976 bzero(&dummy, sizeof(dummy));
2979 * When creating an indirect block for a freemap node or leaf
2980 * the key/keybits must be fitted to static radix levels because
2981 * particular radix levels use particular reserved blocks in the
2984 * This routine calculates the key/radix of the indirect block
2985 * we need to create, and whether it is on the high-side or the
2988 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2989 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2990 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2993 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2998 * Normalize the key for the radix being represented, keeping the
2999 * high bits and throwing away the low bits.
3001 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3004 * How big should our new indirect block be? It has to be at least
3005 * as large as its parent.
3007 * The freemap uses a specific indirect block size.
3009 * The first indirect block level down from an inode typically
3010 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3012 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3013 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3014 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3015 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3016 nbytes = HAMMER2_IND_BYTES_MIN;
3018 nbytes = HAMMER2_IND_BYTES_MAX;
3020 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3021 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3022 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3023 nbytes = count * sizeof(hammer2_blockref_t);
3027 * Ok, create our new indirect block
3029 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3030 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3031 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3033 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3035 dummy.bref.key = key;
3036 dummy.bref.keybits = keybits;
3037 dummy.bref.data_off = hammer2_getradix(nbytes);
3038 dummy.bref.methods = parent->bref.methods;
3040 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3041 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3042 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3043 /* ichain has one ref at this point */
3046 * We have to mark it modified to allocate its block, but use
3047 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3048 * it won't be acted upon by the flush code.
3050 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3053 * Iterate the original parent and move the matching brefs into
3054 * the new indirect block.
3056 * XXX handle flushes.
3059 key_end = HAMMER2_KEY_MAX;
3061 hammer2_spin_ex(&parent->core.spin);
3067 * Parent may have been modified, relocating its block array.
3068 * Reload the base pointer.
3070 base = hammer2_chain_base_and_count(parent, &count);
3072 if (++loops > 100000) {
3073 hammer2_spin_unex(&parent->core.spin);
3074 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3075 reason, parent, base, count, key_next);
3079 * NOTE: spinlock stays intact, returned chain (if not NULL)
3080 * is not referenced or locked which means that we
3081 * cannot safely check its flagged / deletion status
3084 chain = hammer2_combined_find(parent, base, count,
3085 &cache_index, &key_next,
3088 generation = parent->core.generation;
3091 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3094 * Skip keys that are not within the key/radix of the new
3095 * indirect block. They stay in the parent.
3097 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3098 (key ^ bref->key)) != 0) {
3099 goto next_key_spinlocked;
3103 * Load the new indirect block by acquiring the related
3104 * chains (potentially from media as it might not be
3105 * in-memory). Then move it to the new parent (ichain)
3106 * via DELETE-DUPLICATE.
3108 * chain is referenced but not locked. We must lock the
3109 * chain to obtain definitive DUPLICATED/DELETED state
3113 * Use chain already present in the RBTREE
3115 hammer2_chain_ref(chain);
3116 hammer2_spin_unex(&parent->core.spin);
3117 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3120 * Get chain for blockref element. _get returns NULL
3121 * on insertion race.
3124 hammer2_spin_unex(&parent->core.spin);
3125 chain = hammer2_chain_get(parent, generation, &bcopy);
3126 if (chain == NULL) {
3128 hammer2_spin_ex(&parent->core.spin);
3131 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3132 kprintf("REASON 2\n");
3134 hammer2_chain_drop(chain);
3135 hammer2_spin_ex(&parent->core.spin);
3138 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3142 * This is always live so if the chain has been deleted
3143 * we raced someone and we have to retry.
3145 * NOTE: Lookups can race delete-duplicate because
3146 * delete-duplicate does not lock the parent's core
3147 * (they just use the spinlock on the core). We must
3148 * check for races by comparing the DUPLICATED flag before
3149 * releasing the spinlock with the flag after locking the
3152 * (note reversed logic for this one)
3154 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3155 hammer2_chain_unlock(chain);
3156 hammer2_chain_drop(chain);
3161 * Shift the chain to the indirect block.
3163 * WARNING! No reason for us to load chain data, pass NOSTATS
3164 * to prevent delete/insert from trying to access
3165 * inode stats (and thus asserting if there is no
3166 * chain->data loaded).
3168 * WARNING! The (parent, chain) deletion may modify the parent
3169 * and invalidate the base pointer.
3171 hammer2_chain_delete(parent, chain, mtid, 0);
3172 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3173 hammer2_chain_unlock(chain);
3174 hammer2_chain_drop(chain);
3175 KKASSERT(parent->refs > 0);
3177 base = NULL; /* safety */
3179 hammer2_spin_ex(&parent->core.spin);
3180 next_key_spinlocked:
3181 if (--maxloops == 0)
3182 panic("hammer2_chain_create_indirect: maxloops");
3184 if (key_next == 0 || key_next > key_end)
3189 hammer2_spin_unex(&parent->core.spin);
3192 * Insert the new indirect block into the parent now that we've
3193 * cleared out some entries in the parent. We calculated a good
3194 * insertion index in the loop above (ichain->index).
3196 * We don't have to set UPDATE here because we mark ichain
3197 * modified down below (so the normal modified -> flush -> set-moved
3198 * sequence applies).
3200 * The insertion shouldn't race as this is a completely new block
3201 * and the parent is locked.
3203 base = NULL; /* safety, parent modify may change address */
3204 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3205 hammer2_chain_insert(parent, ichain,
3206 HAMMER2_CHAIN_INSERT_SPIN |
3207 HAMMER2_CHAIN_INSERT_LIVE,
3211 * Make sure flushes propogate after our manual insertion.
3213 hammer2_chain_setflush(ichain);
3214 hammer2_chain_setflush(parent);
3217 * Figure out what to return.
3219 if (~(((hammer2_key_t)1 << keybits) - 1) &
3220 (create_key ^ key)) {
3222 * Key being created is outside the key range,
3223 * return the original parent.
3225 hammer2_chain_unlock(ichain);
3226 hammer2_chain_drop(ichain);
3229 * Otherwise its in the range, return the new parent.
3230 * (leave both the new and old parent locked).
3239 * Calculate the keybits and highside/lowside of the freemap node the
3240 * caller is creating.
3242 * This routine will specify the next higher-level freemap key/radix
3243 * representing the lowest-ordered set. By doing so, eventually all
3244 * low-ordered sets will be moved one level down.
3246 * We have to be careful here because the freemap reserves a limited
3247 * number of blocks for a limited number of levels. So we can't just
3248 * push indiscriminately.
3251 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3252 int keybits, hammer2_blockref_t *base, int count)
3254 hammer2_chain_t *chain;
3255 hammer2_blockref_t *bref;
3257 hammer2_key_t key_beg;
3258 hammer2_key_t key_end;
3259 hammer2_key_t key_next;
3263 int maxloops = 300000;
3271 * Calculate the range of keys in the array being careful to skip
3272 * slots which are overridden with a deletion.
3275 key_end = HAMMER2_KEY_MAX;
3277 hammer2_spin_ex(&parent->core.spin);
3280 if (--maxloops == 0) {
3281 panic("indkey_freemap shit %p %p:%d\n",
3282 parent, base, count);
3284 chain = hammer2_combined_find(parent, base, count,
3285 &cache_index, &key_next,
3296 * Skip deleted chains.
3298 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3299 if (key_next == 0 || key_next > key_end)
3306 * Use the full live (not deleted) element for the scan
3307 * iteration. HAMMER2 does not allow partial replacements.
3309 * XXX should be built into hammer2_combined_find().
3311 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3313 if (keybits > bref->keybits) {
3315 keybits = bref->keybits;
3316 } else if (keybits == bref->keybits && bref->key < key) {
3323 hammer2_spin_unex(&parent->core.spin);
3326 * Return the keybits for a higher-level FREEMAP_NODE covering
3330 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3331 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3333 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3334 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3336 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3337 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3339 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3340 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3342 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3343 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3345 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3346 panic("hammer2_chain_indkey_freemap: level too high");
3349 panic("hammer2_chain_indkey_freemap: bad radix");
3358 * Calculate the keybits and highside/lowside of the indirect block the
3359 * caller is creating.
3362 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3363 int keybits, hammer2_blockref_t *base, int count)
3365 hammer2_blockref_t *bref;
3366 hammer2_chain_t *chain;
3367 hammer2_key_t key_beg;
3368 hammer2_key_t key_end;
3369 hammer2_key_t key_next;
3375 int maxloops = 300000;
3382 * Calculate the range of keys in the array being careful to skip
3383 * slots which are overridden with a deletion. Once the scan
3384 * completes we will cut the key range in half and shift half the
3385 * range into the new indirect block.
3388 key_end = HAMMER2_KEY_MAX;
3390 hammer2_spin_ex(&parent->core.spin);
3393 if (--maxloops == 0) {
3394 panic("indkey_freemap shit %p %p:%d\n",
3395 parent, base, count);
3397 chain = hammer2_combined_find(parent, base, count,
3398 &cache_index, &key_next,
3409 * NOTE: No need to check DUPLICATED here because we do
3410 * not release the spinlock.
3412 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3413 if (key_next == 0 || key_next > key_end)
3420 * Use the full live (not deleted) element for the scan
3421 * iteration. HAMMER2 does not allow partial replacements.
3423 * XXX should be built into hammer2_combined_find().
3425 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3428 * Expand our calculated key range (key, keybits) to fit
3429 * the scanned key. nkeybits represents the full range
3430 * that we will later cut in half (two halves @ nkeybits - 1).
3433 if (nkeybits < bref->keybits) {
3434 if (bref->keybits > 64) {
3435 kprintf("bad bref chain %p bref %p\n",
3439 nkeybits = bref->keybits;
3441 while (nkeybits < 64 &&
3442 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3443 (key ^ bref->key)) != 0) {
3448 * If the new key range is larger we have to determine
3449 * which side of the new key range the existing keys fall
3450 * under by checking the high bit, then collapsing the
3451 * locount into the hicount or vise-versa.
3453 if (keybits != nkeybits) {
3454 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3465 * The newly scanned key will be in the lower half or the
3466 * upper half of the (new) key range.
3468 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3477 hammer2_spin_unex(&parent->core.spin);
3478 bref = NULL; /* now invalid (safety) */
3481 * Adjust keybits to represent half of the full range calculated
3482 * above (radix 63 max)
3487 * Select whichever half contains the most elements. Theoretically
3488 * we can select either side as long as it contains at least one
3489 * element (in order to ensure that a free slot is present to hold
3490 * the indirect block).
3492 if (hammer2_indirect_optimize) {
3494 * Insert node for least number of keys, this will arrange
3495 * the first few blocks of a large file or the first few
3496 * inodes in a directory with fewer indirect blocks when
3499 if (hicount < locount && hicount != 0)
3500 key |= (hammer2_key_t)1 << keybits;
3502 key &= ~(hammer2_key_t)1 << keybits;
3505 * Insert node for most number of keys, best for heavily
3508 if (hicount > locount)
3509 key |= (hammer2_key_t)1 << keybits;
3511 key &= ~(hammer2_key_t)1 << keybits;
3519 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3522 * Both parent and chain must be locked exclusively.
3524 * This function will modify the parent if the blockref requires removal
3525 * from the parent's block table.
3527 * This function is NOT recursive. Any entity already pushed into the
3528 * chain (such as an inode) may still need visibility into its contents,
3529 * as well as the ability to read and modify the contents. For example,
3530 * for an unlinked file which is still open.
3533 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3534 hammer2_tid_t mtid, int flags)
3536 KKASSERT(hammer2_mtx_owned(&chain->lock));
3539 * Nothing to do if already marked.
3541 * We need the spinlock on the core whos RBTREE contains chain
3542 * to protect against races.
3544 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3545 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3546 chain->parent == parent);
3547 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3551 * To avoid losing track of a permanent deletion we add the chain
3552 * to the delayed flush queue. If we were to flush it right now the
3553 * parent would end up in a modified state and generate I/O.
3554 * The delayed queue gives the parent a chance to be deleted to
3557 if (flags & HAMMER2_DELETE_PERMANENT) {
3558 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3559 hammer2_delayed_flush(chain);
3561 /* XXX might not be needed */
3562 hammer2_chain_setflush(chain);
3567 * Returns the index of the nearest element in the blockref array >= elm.
3568 * Returns (count) if no element could be found.
3570 * Sets *key_nextp to the next key for loop purposes but does not modify
3571 * it if the next key would be higher than the current value of *key_nextp.
3572 * Note that *key_nexp can overflow to 0, which should be tested by the
3575 * (*cache_indexp) is a heuristic and can be any value without effecting
3578 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3579 * held through the operation.
3582 hammer2_base_find(hammer2_chain_t *parent,
3583 hammer2_blockref_t *base, int count,
3584 int *cache_indexp, hammer2_key_t *key_nextp,
3585 hammer2_key_t key_beg, hammer2_key_t key_end)
3587 hammer2_blockref_t *scan;
3588 hammer2_key_t scan_end;
3593 * Require the live chain's already have their core's counted
3594 * so we can optimize operations.
3596 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3601 if (count == 0 || base == NULL)
3605 * Sequential optimization using *cache_indexp. This is the most
3608 * We can avoid trailing empty entries on live chains, otherwise
3609 * we might have to check the whole block array.
3613 limit = parent->core.live_zero;
3618 KKASSERT(i < count);
3624 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3631 * Search forwards, stop when we find a scan element which
3632 * encloses the key or until we know that there are no further
3636 if (scan->type != 0) {
3637 scan_end = scan->key +
3638 ((hammer2_key_t)1 << scan->keybits) - 1;
3639 if (scan->key > key_beg || scan_end >= key_beg)
3652 scan_end = scan->key +
3653 ((hammer2_key_t)1 << scan->keybits);
3654 if (scan_end && (*key_nextp > scan_end ||
3656 *key_nextp = scan_end;
3664 * Do a combined search and return the next match either from the blockref
3665 * array or from the in-memory chain. Sets *bresp to the returned bref in
3666 * both cases, or sets it to NULL if the search exhausted. Only returns
3667 * a non-NULL chain if the search matched from the in-memory chain.
3669 * When no in-memory chain has been found and a non-NULL bref is returned
3673 * The returned chain is not locked or referenced. Use the returned bref
3674 * to determine if the search exhausted or not. Iterate if the base find
3675 * is chosen but matches a deleted chain.
3677 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3678 * held through the operation.
3680 static hammer2_chain_t *
3681 hammer2_combined_find(hammer2_chain_t *parent,
3682 hammer2_blockref_t *base, int count,
3683 int *cache_indexp, hammer2_key_t *key_nextp,
3684 hammer2_key_t key_beg, hammer2_key_t key_end,
3685 hammer2_blockref_t **bresp)
3687 hammer2_blockref_t *bref;
3688 hammer2_chain_t *chain;
3692 * Lookup in block array and in rbtree.
3694 *key_nextp = key_end + 1;
3695 i = hammer2_base_find(parent, base, count, cache_indexp,
3696 key_nextp, key_beg, key_end);
3697 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3702 if (i == count && chain == NULL) {
3708 * Only chain matched.
3711 bref = &chain->bref;
3716 * Only blockref matched.
3718 if (chain == NULL) {
3724 * Both in-memory and blockref matched, select the nearer element.
3726 * If both are flush with the left-hand side or both are the
3727 * same distance away, select the chain. In this situation the
3728 * chain must have been loaded from the matching blockmap.
3730 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3731 chain->bref.key == base[i].key) {
3732 KKASSERT(chain->bref.key == base[i].key);
3733 bref = &chain->bref;
3738 * Select the nearer key
3740 if (chain->bref.key < base[i].key) {
3741 bref = &chain->bref;
3748 * If the bref is out of bounds we've exhausted our search.
3751 if (bref->key > key_end) {
3761 * Locate the specified block array element and delete it. The element
3764 * The spin lock on the related chain must be held.
3766 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3767 * need to be adjusted when we commit the media change.
3770 hammer2_base_delete(hammer2_chain_t *parent,
3771 hammer2_blockref_t *base, int count,
3772 int *cache_indexp, hammer2_chain_t *chain)
3774 hammer2_blockref_t *elm = &chain->bref;
3775 hammer2_key_t key_next;
3779 * Delete element. Expect the element to exist.
3781 * XXX see caller, flush code not yet sophisticated enough to prevent
3782 * re-flushed in some cases.
3784 key_next = 0; /* max range */
3785 i = hammer2_base_find(parent, base, count, cache_indexp,
3786 &key_next, elm->key, elm->key);
3787 if (i == count || base[i].type == 0 ||
3788 base[i].key != elm->key ||
3789 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3790 base[i].keybits != elm->keybits)) {
3791 hammer2_spin_unex(&parent->core.spin);
3792 panic("delete base %p element not found at %d/%d elm %p\n",
3793 base, i, count, elm);
3798 * Update stats and zero the entry
3800 parent->bref.data_count -= base[i].data_count;
3801 parent->bref.data_count -= (hammer2_off_t)1 <<
3802 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3803 parent->bref.inode_count -= base[i].inode_count;
3804 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3805 parent->bref.inode_count -= 1;
3807 bzero(&base[i], sizeof(*base));
3810 * We can only optimize parent->core.live_zero for live chains.
3812 if (parent->core.live_zero == i + 1) {
3813 while (--i >= 0 && base[i].type == 0)
3815 parent->core.live_zero = i + 1;
3819 * Clear appropriate blockmap flags in chain.
3821 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3822 HAMMER2_CHAIN_BMAPUPD);
3826 * Insert the specified element. The block array must not already have the
3827 * element and must have space available for the insertion.
3829 * The spin lock on the related chain must be held.
3831 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3832 * need to be adjusted when we commit the media change.
3835 hammer2_base_insert(hammer2_chain_t *parent,
3836 hammer2_blockref_t *base, int count,
3837 int *cache_indexp, hammer2_chain_t *chain)
3839 hammer2_blockref_t *elm = &chain->bref;
3840 hammer2_key_t key_next;
3849 * Insert new element. Expect the element to not already exist
3850 * unless we are replacing it.
3852 * XXX see caller, flush code not yet sophisticated enough to prevent
3853 * re-flushed in some cases.
3855 key_next = 0; /* max range */
3856 i = hammer2_base_find(parent, base, count, cache_indexp,
3857 &key_next, elm->key, elm->key);
3860 * Shortcut fill optimization, typical ordered insertion(s) may not
3863 KKASSERT(i >= 0 && i <= count);
3866 * Set appropriate blockmap flags in chain.
3868 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3871 * Update stats and zero the entry
3873 parent->bref.data_count += elm->data_count;
3874 parent->bref.data_count += (hammer2_off_t)1 <<
3875 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3876 parent->bref.inode_count += elm->inode_count;
3877 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3878 parent->bref.inode_count += 1;
3882 * We can only optimize parent->core.live_zero for live chains.
3884 if (i == count && parent->core.live_zero < count) {
3885 i = parent->core.live_zero++;
3890 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3891 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3892 hammer2_spin_unex(&parent->core.spin);
3893 panic("insert base %p overlapping elements at %d elm %p\n",
3898 * Try to find an empty slot before or after.
3902 while (j > 0 || k < count) {
3904 if (j >= 0 && base[j].type == 0) {
3908 bcopy(&base[j+1], &base[j],
3909 (i - j - 1) * sizeof(*base));
3915 if (k < count && base[k].type == 0) {
3916 bcopy(&base[i], &base[i+1],
3917 (k - i) * sizeof(hammer2_blockref_t));
3921 * We can only update parent->core.live_zero for live
3924 if (parent->core.live_zero <= k)
3925 parent->core.live_zero = k + 1;
3930 panic("hammer2_base_insert: no room!");
3937 for (l = 0; l < count; ++l) {
3939 key_next = base[l].key +
3940 ((hammer2_key_t)1 << base[l].keybits) - 1;
3944 while (++l < count) {
3946 if (base[l].key <= key_next)
3947 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3948 key_next = base[l].key +
3949 ((hammer2_key_t)1 << base[l].keybits) - 1;
3959 * Sort the blockref array for the chain. Used by the flush code to
3960 * sort the blockref[] array.
3962 * The chain must be exclusively locked AND spin-locked.
3964 typedef hammer2_blockref_t *hammer2_blockref_p;
3968 hammer2_base_sort_callback(const void *v1, const void *v2)
3970 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3971 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3974 * Make sure empty elements are placed at the end of the array
3976 if (bref1->type == 0) {
3977 if (bref2->type == 0)
3980 } else if (bref2->type == 0) {
3987 if (bref1->key < bref2->key)
3989 if (bref1->key > bref2->key)
3995 hammer2_base_sort(hammer2_chain_t *chain)
3997 hammer2_blockref_t *base;
4000 switch(chain->bref.type) {
4001 case HAMMER2_BREF_TYPE_INODE:
4003 * Special shortcut for embedded data returns the inode
4004 * itself. Callers must detect this condition and access
4005 * the embedded data (the strategy code does this for us).
4007 * This is only applicable to regular files and softlinks.
4009 if (chain->data->ipdata.meta.op_flags &
4010 HAMMER2_OPFLAG_DIRECTDATA) {
4013 base = &chain->data->ipdata.u.blockset.blockref[0];
4014 count = HAMMER2_SET_COUNT;
4016 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4017 case HAMMER2_BREF_TYPE_INDIRECT:
4019 * Optimize indirect blocks in the INITIAL state to avoid
4022 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4023 base = &chain->data->npdata[0];
4024 count = chain->bytes / sizeof(hammer2_blockref_t);
4026 case HAMMER2_BREF_TYPE_VOLUME:
4027 base = &chain->data->voldata.sroot_blockset.blockref[0];
4028 count = HAMMER2_SET_COUNT;
4030 case HAMMER2_BREF_TYPE_FREEMAP:
4031 base = &chain->data->blkset.blockref[0];
4032 count = HAMMER2_SET_COUNT;
4035 kprintf("hammer2_chain_lookup: unrecognized "
4036 "blockref(A) type: %d",
4039 tsleep(&base, 0, "dead", 0);
4040 panic("hammer2_chain_lookup: unrecognized "
4041 "blockref(A) type: %d",
4043 base = NULL; /* safety */
4044 count = 0; /* safety */
4046 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4052 * Chain memory management
4055 hammer2_chain_wait(hammer2_chain_t *chain)
4057 tsleep(chain, 0, "chnflw", 1);
4060 const hammer2_media_data_t *
4061 hammer2_chain_rdata(hammer2_chain_t *chain)
4063 KKASSERT(chain->data != NULL);
4064 return (chain->data);
4067 hammer2_media_data_t *
4068 hammer2_chain_wdata(hammer2_chain_t *chain)
4070 KKASSERT(chain->data != NULL);
4071 return (chain->data);
4075 * Set the check data for a chain. This can be a heavy-weight operation
4076 * and typically only runs on-flush. For file data check data is calculated
4077 * when the logical buffers are flushed.
4080 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4082 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4084 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4085 case HAMMER2_CHECK_NONE:
4087 case HAMMER2_CHECK_DISABLED:
4089 case HAMMER2_CHECK_ISCSI32:
4090 chain->bref.check.iscsi32.value =
4091 hammer2_icrc32(bdata, chain->bytes);
4093 case HAMMER2_CHECK_CRC64:
4094 chain->bref.check.crc64.value = 0;
4097 case HAMMER2_CHECK_SHA192:
4099 SHA256_CTX hash_ctx;
4101 uint8_t digest[SHA256_DIGEST_LENGTH];
4102 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4105 SHA256_Init(&hash_ctx);
4106 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4107 SHA256_Final(u.digest, &hash_ctx);
4108 u.digest64[2] ^= u.digest64[3];
4110 chain->bref.check.sha192.data,
4111 sizeof(chain->bref.check.sha192.data));
4114 case HAMMER2_CHECK_FREEMAP:
4115 chain->bref.check.freemap.icrc32 =
4116 hammer2_icrc32(bdata, chain->bytes);
4119 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4120 chain->bref.methods);
4126 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4130 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4133 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4134 case HAMMER2_CHECK_NONE:
4137 case HAMMER2_CHECK_DISABLED:
4140 case HAMMER2_CHECK_ISCSI32:
4141 r = (chain->bref.check.iscsi32.value ==
4142 hammer2_icrc32(bdata, chain->bytes));
4144 case HAMMER2_CHECK_CRC64:
4145 r = (chain->bref.check.crc64.value == 0);
4148 case HAMMER2_CHECK_SHA192:
4150 SHA256_CTX hash_ctx;
4152 uint8_t digest[SHA256_DIGEST_LENGTH];
4153 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4156 SHA256_Init(&hash_ctx);
4157 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4158 SHA256_Final(u.digest, &hash_ctx);
4159 u.digest64[2] ^= u.digest64[3];
4161 chain->bref.check.sha192.data,
4162 sizeof(chain->bref.check.sha192.data)) == 0) {
4169 case HAMMER2_CHECK_FREEMAP:
4170 r = (chain->bref.check.freemap.icrc32 ==
4171 hammer2_icrc32(bdata, chain->bytes));
4173 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4174 chain->bref.check.freemap.icrc32,
4175 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4177 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4178 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4183 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4184 chain->bref.methods);
4192 * The caller presents a shared-locked (parent, chain) where the chain
4193 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4194 * structure representing the inode locked to prevent
4195 * consolidation/deconsolidation races.
4197 * We locate the hardlink in the current or a common parent directory.
4199 * If we are unable to locate the hardlink, EIO is returned and
4200 * (*chainp) is unlocked and dropped.
4203 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4204 hammer2_chain_t **parentp,
4205 hammer2_chain_t **chainp,
4208 hammer2_chain_t *parent;
4209 hammer2_chain_t *rchain;
4210 hammer2_key_t key_dummy;
4212 int cache_index = -1;
4215 * Obtain the key for the hardlink from *chainp.
4218 lhc = rchain->data->ipdata.meta.inum;
4219 hammer2_chain_unlock(rchain);
4220 hammer2_chain_drop(rchain);
4225 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4227 &cache_index, flags);
4232 * Iterate parents, handle parent rename races by retrying
4240 parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4243 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4245 if (parent->parent == NULL)
4247 parent = parent->parent;
4248 hammer2_chain_ref(parent);
4249 hammer2_chain_unlock(*parentp);
4250 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4252 if ((*parentp)->parent == parent) {
4253 hammer2_chain_drop(*parentp);
4256 hammer2_chain_unlock(parent);
4257 hammer2_chain_drop(parent);
4258 hammer2_chain_lock(*parentp,
4259 HAMMER2_RESOLVE_ALWAYS |
4261 parent = NULL; /* safety */
4269 return (rchain ? EINVAL : 0);
4273 * Used by the bulkscan code to snapshot the synchronized storage for
4274 * a volume, allowing it to be scanned concurrently against normal
4278 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4280 hammer2_chain_t *copy;
4282 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4283 switch(chain->bref.type) {
4284 case HAMMER2_BREF_TYPE_VOLUME:
4285 copy->data = kmalloc(sizeof(copy->data->voldata),
4288 hammer2_spin_ex(&chain->core.spin);
4289 copy->data->voldata = chain->data->voldata;
4290 hammer2_spin_unex(&chain->core.spin);
4292 case HAMMER2_BREF_TYPE_FREEMAP:
4293 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4296 hammer2_spin_ex(&chain->core.spin);
4297 copy->data->blkset = chain->data->blkset;
4298 hammer2_spin_unex(&chain->core.spin);
4307 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4309 switch(copy->bref.type) {
4310 case HAMMER2_BREF_TYPE_VOLUME:
4311 case HAMMER2_BREF_TYPE_FREEMAP:
4312 KKASSERT(copy->data);
4313 kfree(copy->data, copy->hmp->mchain);
4318 hammer2_chain_drop(copy);
4322 * Create a snapshot of the specified {parent, ochain} with the specified
4323 * label. The originating hammer2_inode must be exclusively locked for
4326 * The ioctl code has already synced the filesystem.
4329 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4333 const hammer2_inode_data_t *ripdata;
4334 hammer2_inode_data_t *wipdata;
4335 hammer2_chain_t *nchain;
4336 hammer2_inode_t *nip;
4345 kprintf("snapshot %s\n", pmp->name);
4347 name_len = strlen(pmp->name);
4348 lhc = hammer2_dirhash(pmp->name, name_len);
4353 ripdata = &chain->data->ipdata;
4355 opfs_clid = ripdata->meta.pfs_clid;
4360 * Create the snapshot directory under the super-root
4362 * Set PFS type, generate a unique filesystem id, and generate
4363 * a cluster id. Use the same clid when snapshotting a PFS root,
4364 * which theoretically allows the snapshot to be used as part of
4365 * the same cluster (perhaps as a cache).
4367 * Copy the (flushed) blockref array. Theoretically we could use
4368 * chain_duplicate() but it becomes difficult to disentangle
4369 * the shared core so for now just brute-force it.
4374 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4375 pmp->name, name_len, 0,
4377 HAMMER2_INSERT_PFSROOT, &error);
4380 hammer2_inode_modify(nip);
4381 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4382 hammer2_chain_modify(nchain, mtid, 0, 0);
4383 wipdata = &nchain->data->ipdata;
4385 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4386 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4387 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4388 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4391 * Give the snapshot its own private cluster id. As a
4392 * snapshot no further synchronization with the original
4393 * cluster will be done.
4396 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4397 nip->meta.pfs_clid = opfs_clid;
4399 kern_uuidgen(&nip->meta.pfs_clid, 1);
4401 kern_uuidgen(&nip->meta.pfs_clid, 1);
4402 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4404 /* XXX hack blockset copy */
4405 /* XXX doesn't work with real cluster */
4406 wipdata->meta = nip->meta;
4407 wipdata->u.blockset = ripdata->u.blockset;
4408 hammer2_flush(nchain, 1);
4409 hammer2_chain_unlock(nchain);
4410 hammer2_chain_drop(nchain);
4411 hammer2_inode_unlock(nip);