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 (key=%016jx)",
299 chain, xchain, chain->bref.key));
300 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
301 chain->parent = parent;
302 ++parent->core.chain_count;
303 ++parent->core.generation; /* XXX incs for _get() too, XXX */
306 * We have to keep track of the effective live-view blockref count
307 * so the create code knows when to push an indirect block.
309 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
310 atomic_add_int(&parent->core.live_count, 1);
312 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
313 hammer2_spin_unex(&parent->core.spin);
318 * Drop the caller's reference to the chain. When the ref count drops to
319 * zero this function will try to disassociate the chain from its parent and
320 * deallocate it, then recursely drop the parent using the implied ref
321 * from the chain's chain->parent.
323 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
326 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 KKASSERT(chain->refs > 0);
345 chain = hammer2_chain_lastdrop(chain);
347 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
349 /* retry the same chain */
355 * Safe handling of the 1->0 transition on chain. Returns a chain for
356 * recursive drop or NULL, possibly returning the same chain if the atomic
359 * Whem two chains need to be recursively dropped we use the chain
360 * we would otherwise free to placehold the additional chain. It's a bit
361 * convoluted but we can't just recurse without potentially blowing out
364 * The chain cannot be freed if it has any children.
365 * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
366 * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
368 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
372 hammer2_chain_lastdrop(hammer2_chain_t *chain)
376 hammer2_chain_t *parent;
377 hammer2_chain_t *rdrop;
380 * Critical field access.
382 hammer2_spin_ex(&chain->core.spin);
386 * If the chain has a parent the UPDATE bit prevents scrapping
387 * as the chain is needed to properly flush the parent. Try
388 * to complete the 1->0 transition and return NULL. Retry
389 * (return chain) if we are unable to complete the 1->0
390 * transition, else return NULL (nothing more to do).
392 * If the chain has a parent the MODIFIED bit prevents
395 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
396 HAMMER2_CHAIN_MODIFIED)) {
397 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
398 hammer2_spin_unex(&chain->core.spin);
401 hammer2_spin_unex(&chain->core.spin);
405 /* spinlock still held */
408 * The chain has no parent and can be flagged for destruction.
409 * Since it has no parent, UPDATE can also be cleared.
411 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
412 if (chain->flags & HAMMER2_CHAIN_UPDATE)
413 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
416 * If the chain has children or if it has been MODIFIED and
417 * also recorded for DEDUP, we must still flush the chain.
419 * In the case where it has children, the DESTROY flag test
420 * in the flush code will prevent unnecessary flushes of
421 * MODIFIED chains that are not flagged DEDUP so don't worry
424 if (chain->core.chain_count ||
425 (chain->flags & (HAMMER2_CHAIN_MODIFIED |
426 HAMMER2_CHAIN_DEDUP)) ==
427 (HAMMER2_CHAIN_MODIFIED |
428 HAMMER2_CHAIN_DEDUP)) {
430 * Put on flushq (should ensure refs > 1), retry
433 hammer2_spin_unex(&chain->core.spin);
434 hammer2_delayed_flush(chain);
435 return(chain); /* retry drop */
439 * Otherwise we can scrap the MODIFIED bit if it is set,
440 * and continue along the freeing path.
442 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
443 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
444 atomic_add_long(&hammer2_count_modified_chains, -1);
446 /* spinlock still held */
450 * If any children exist we must leave the chain intact with refs == 0.
451 * They exist because chains are retained below us which have refs or
452 * may require flushing. This case can occur when parent != NULL.
454 * Retry (return chain) if we fail to transition the refs to 0, else
455 * return NULL indication nothing more to do.
457 if (chain->core.chain_count) {
458 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
459 hammer2_spin_unex(&chain->core.spin);
462 hammer2_spin_unex(&chain->core.spin);
466 /* spinlock still held */
467 /* no chains left under us */
470 * chain->core has no children left so no accessors can get to our
471 * chain from there. Now we have to lock the parent core to interlock
472 * remaining possible accessors that might bump chain's refs before
473 * we can safely drop chain's refs with intent to free the chain.
476 pmp = chain->pmp; /* can be NULL */
480 * Spinlock the parent and try to drop the last ref on chain.
481 * On success remove chain from its parent, otherwise return NULL.
483 * (normal core locks are top-down recursive but we define core
484 * spinlocks as bottom-up recursive, so this is safe).
486 if ((parent = chain->parent) != NULL) {
487 hammer2_spin_ex(&parent->core.spin);
488 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
489 /* 1->0 transition failed, retry */
490 hammer2_spin_unex(&parent->core.spin);
491 hammer2_spin_unex(&chain->core.spin);
496 * 1->0 transition successful, remove chain from the
499 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
500 RB_REMOVE(hammer2_chain_tree,
501 &parent->core.rbtree, chain);
502 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
503 --parent->core.chain_count;
504 chain->parent = NULL;
508 * If our chain was the last chain in the parent's core the
509 * core is now empty and its parent might have to be
510 * re-dropped if it has 0 refs.
512 if (parent->core.chain_count == 0) {
514 atomic_add_int(&rdrop->refs, 1);
516 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
520 hammer2_spin_unex(&parent->core.spin);
521 parent = NULL; /* safety */
525 * Successful 1->0 transition and the chain can be destroyed now.
527 * We still have the core spinlock, and core's chain_count is 0.
528 * Any parent spinlock is gone.
530 hammer2_spin_unex(&chain->core.spin);
531 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
532 chain->core.chain_count == 0);
535 * All spin locks are gone, no pointers remain to the chain, finish
538 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
539 HAMMER2_CHAIN_MODIFIED)) == 0);
540 hammer2_chain_drop_data(chain, 1);
542 KKASSERT(chain->dio == NULL);
545 * Once chain resources are gone we can use the now dead chain
546 * structure to placehold what might otherwise require a recursive
547 * drop, because we have potentially two things to drop and can only
548 * return one directly.
550 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
551 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
553 kfree(chain, hmp->mchain);
557 * Possible chaining loop when parent re-drop needed.
563 * On either last lock release or last drop
566 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
568 /*hammer2_dev_t *hmp = chain->hmp;*/
570 switch(chain->bref.type) {
571 case HAMMER2_BREF_TYPE_VOLUME:
572 case HAMMER2_BREF_TYPE_FREEMAP:
577 KKASSERT(chain->data == NULL);
583 * Lock a referenced chain element, acquiring its data with I/O if necessary,
584 * and specify how you would like the data to be resolved.
586 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
588 * The lock is allowed to recurse, multiple locking ops will aggregate
589 * the requested resolve types. Once data is assigned it will not be
590 * removed until the last unlock.
592 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
593 * (typically used to avoid device/logical buffer
596 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
597 * the INITIAL-create state (indirect blocks only).
599 * Do not resolve data elements for DATA chains.
600 * (typically used to avoid device/logical buffer
603 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
605 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
606 * it will be locked exclusive.
608 * NOTE: Embedded elements (volume header, inodes) are always resolved
611 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
612 * element will instantiate and zero its buffer, and flush it on
615 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
616 * so as not to instantiate a device buffer, which could alias against
617 * a logical file buffer. However, if ALWAYS is specified the
618 * device buffer will be instantiated anyway.
620 * WARNING! This function blocks on I/O if data needs to be fetched. This
621 * blocking can run concurrent with other compatible lock holders
622 * who do not need data returning. The lock is not upgraded to
623 * exclusive during a data fetch, a separate bit is used to
624 * interlock I/O. However, an exclusive lock holder can still count
625 * on being interlocked against an I/O fetch managed by a shared
629 hammer2_chain_lock(hammer2_chain_t *chain, int how)
632 * Ref and lock the element. Recursive locks are allowed.
634 KKASSERT(chain->refs > 0);
635 atomic_add_int(&chain->lockcnt, 1);
638 * Get the appropriate lock.
640 if (how & HAMMER2_RESOLVE_SHARED)
641 hammer2_mtx_sh(&chain->lock);
643 hammer2_mtx_ex(&chain->lock);
644 ++curthread->td_tracker;
647 * If we already have a valid data pointer no further action is
654 * Do we have to resolve the data?
656 switch(how & HAMMER2_RESOLVE_MASK) {
657 case HAMMER2_RESOLVE_NEVER:
659 case HAMMER2_RESOLVE_MAYBE:
660 if (chain->flags & HAMMER2_CHAIN_INITIAL)
662 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
665 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
667 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
671 case HAMMER2_RESOLVE_ALWAYS:
677 * Caller requires data
679 hammer2_chain_load_data(chain);
683 * Downgrade an exclusive chain lock to a shared chain lock.
685 * NOTE: There is no upgrade equivalent due to the ease of
686 * deadlocks in that direction.
689 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
691 hammer2_mtx_downgrade(&chain->lock);
695 * Obtains a second shared lock on the chain, does not account the second
696 * shared lock as being owned by the current thread.
698 * Caller must already own a shared lock on this chain.
700 * The lock function is required to obtain the second shared lock without
701 * blocking on pending exclusive requests.
704 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
706 hammer2_mtx_sh_again(&chain->lock);
707 atomic_add_int(&chain->lockcnt, 1);
708 /* do not count in td_tracker for this thread */
712 * Accounts for a shared lock that was pushed to us as being owned by our
716 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
718 ++curthread->td_tracker;
722 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
723 * may be of any type.
725 * Once chain->data is set it cannot be disposed of until all locks are
729 hammer2_chain_load_data(hammer2_chain_t *chain)
731 hammer2_blockref_t *bref;
737 * Degenerate case, data already present.
743 KKASSERT(hmp != NULL);
746 * Gain the IOINPROG bit, interlocked block.
752 oflags = chain->flags;
754 if (oflags & HAMMER2_CHAIN_IOINPROG) {
755 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
756 tsleep_interlock(&chain->flags, 0);
757 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
758 tsleep(&chain->flags, PINTERLOCKED,
763 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
764 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
772 * We own CHAIN_IOINPROG
774 * Degenerate case if we raced another load.
780 * We must resolve to a device buffer, either by issuing I/O or
781 * by creating a zero-fill element. We do not mark the buffer
782 * dirty when creating a zero-fill element (the hammer2_chain_modify()
783 * API must still be used to do that).
785 * The device buffer is variable-sized in powers of 2 down
786 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
787 * chunk always contains buffers of the same size. (XXX)
789 * The minimum physical IO size may be larger than the variable
795 * The getblk() optimization can only be used on newly created
796 * elements if the physical block size matches the request.
798 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
799 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
802 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
804 hammer2_adjreadcounter(&chain->bref, chain->bytes);
807 chain->error = HAMMER2_ERROR_IO;
808 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
809 (intmax_t)bref->data_off, error);
810 hammer2_io_bqrelse(&chain->dio);
816 * NOTE: A locked chain's data cannot be modified without first
817 * calling hammer2_chain_modify().
821 * Clear INITIAL. In this case we used io_new() and the buffer has
822 * been zero'd and marked dirty.
824 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
825 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
826 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
827 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
828 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
830 * check data not currently synchronized due to
831 * modification. XXX assumes data stays in the buffer
832 * cache, which might not be true (need biodep on flush
833 * to calculate crc? or simple crc?).
836 if (hammer2_chain_testcheck(chain, bdata) == 0) {
837 kprintf("chain %016jx.%02x meth=%02x "
838 "CHECK FAIL %08x (flags=%08x)\n",
839 chain->bref.data_off,
842 hammer2_icrc32(bdata, chain->bytes),
844 chain->error = HAMMER2_ERROR_CHECK;
849 * Setup the data pointer, either pointing it to an embedded data
850 * structure and copying the data from the buffer, or pointing it
853 * The buffer is not retained when copying to an embedded data
854 * structure in order to avoid potential deadlocks or recursions
855 * on the same physical buffer.
857 * WARNING! Other threads can start using the data the instant we
858 * set chain->data non-NULL.
860 switch (bref->type) {
861 case HAMMER2_BREF_TYPE_VOLUME:
862 case HAMMER2_BREF_TYPE_FREEMAP:
864 * Copy data from bp to embedded buffer
866 panic("hammer2_chain_lock: called on unresolved volume header");
868 case HAMMER2_BREF_TYPE_INODE:
869 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
870 case HAMMER2_BREF_TYPE_INDIRECT:
871 case HAMMER2_BREF_TYPE_DATA:
872 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
875 * Point data at the device buffer and leave dio intact.
877 chain->data = (void *)bdata;
882 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
889 oflags = chain->flags;
890 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
891 HAMMER2_CHAIN_IOSIGNAL);
892 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
893 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
894 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
895 wakeup(&chain->flags);
902 * Unlock and deref a chain element.
904 * On the last lock release any non-embedded data (chain->dio) will be
908 hammer2_chain_unlock(hammer2_chain_t *chain)
910 hammer2_mtx_state_t ostate;
914 --curthread->td_tracker;
916 * If multiple locks are present (or being attempted) on this
917 * particular chain we can just unlock, drop refs, and return.
919 * Otherwise fall-through on the 1->0 transition.
922 lockcnt = chain->lockcnt;
923 KKASSERT(lockcnt > 0);
926 if (atomic_cmpset_int(&chain->lockcnt,
927 lockcnt, lockcnt - 1)) {
928 hammer2_mtx_unlock(&chain->lock);
932 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
939 * On the 1->0 transition we upgrade the core lock (if necessary)
940 * to exclusive for terminal processing. If after upgrading we find
941 * that lockcnt is non-zero, another thread is racing us and will
942 * handle the unload for us later on, so just cleanup and return
943 * leaving the data/io intact
945 * Otherwise if lockcnt is still 0 it is possible for it to become
946 * non-zero and race, but since we hold the core->lock exclusively
947 * all that will happen is that the chain will be reloaded after we
950 ostate = hammer2_mtx_upgrade(&chain->lock);
951 if (chain->lockcnt) {
952 hammer2_mtx_unlock(&chain->lock);
957 * Shortcut the case if the data is embedded or not resolved.
958 * Only drop non-DIO-based data if the chain is not modified.
960 * Do NOT NULL out chain->data (e.g. inode data), it might be
963 if (chain->dio == NULL) {
964 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
965 hammer2_chain_drop_data(chain, 0);
966 hammer2_mtx_unlock(&chain->lock);
973 if (hammer2_io_isdirty(chain->dio)) {
974 switch(chain->bref.type) {
975 case HAMMER2_BREF_TYPE_DATA:
976 counterp = &hammer2_iod_file_write;
978 case HAMMER2_BREF_TYPE_INODE:
979 counterp = &hammer2_iod_meta_write;
981 case HAMMER2_BREF_TYPE_INDIRECT:
982 counterp = &hammer2_iod_indr_write;
984 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
985 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
986 counterp = &hammer2_iod_fmap_write;
989 counterp = &hammer2_iod_volu_write;
992 *counterp += chain->bytes;
998 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1002 hammer2_io_bqrelse(&chain->dio);
1003 hammer2_mtx_unlock(&chain->lock);
1007 * Helper to obtain the blockref[] array base and count for a chain.
1009 * XXX Not widely used yet, various use cases need to be validated and
1010 * converted to use this function.
1013 hammer2_blockref_t *
1014 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1016 hammer2_blockref_t *base;
1019 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1022 switch(parent->bref.type) {
1023 case HAMMER2_BREF_TYPE_INODE:
1024 count = HAMMER2_SET_COUNT;
1026 case HAMMER2_BREF_TYPE_INDIRECT:
1027 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1028 count = parent->bytes / sizeof(hammer2_blockref_t);
1030 case HAMMER2_BREF_TYPE_VOLUME:
1031 count = HAMMER2_SET_COUNT;
1033 case HAMMER2_BREF_TYPE_FREEMAP:
1034 count = HAMMER2_SET_COUNT;
1037 panic("hammer2_chain_create_indirect: "
1038 "unrecognized blockref type: %d",
1044 switch(parent->bref.type) {
1045 case HAMMER2_BREF_TYPE_INODE:
1046 base = &parent->data->ipdata.u.blockset.blockref[0];
1047 count = HAMMER2_SET_COUNT;
1049 case HAMMER2_BREF_TYPE_INDIRECT:
1050 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1051 base = &parent->data->npdata[0];
1052 count = parent->bytes / sizeof(hammer2_blockref_t);
1054 case HAMMER2_BREF_TYPE_VOLUME:
1055 base = &parent->data->voldata.
1056 sroot_blockset.blockref[0];
1057 count = HAMMER2_SET_COUNT;
1059 case HAMMER2_BREF_TYPE_FREEMAP:
1060 base = &parent->data->blkset.blockref[0];
1061 count = HAMMER2_SET_COUNT;
1064 panic("hammer2_chain_create_indirect: "
1065 "unrecognized blockref type: %d",
1077 * This counts the number of live blockrefs in a block array and
1078 * also calculates the point at which all remaining blockrefs are empty.
1079 * This routine can only be called on a live chain (DUPLICATED flag not set).
1081 * NOTE: Flag is not set until after the count is complete, allowing
1082 * callers to test the flag without holding the spinlock.
1084 * NOTE: If base is NULL the related chain is still in the INITIAL
1085 * state and there are no blockrefs to count.
1087 * NOTE: live_count may already have some counts accumulated due to
1088 * creation and deletion and could even be initially negative.
1091 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1092 hammer2_blockref_t *base, int count)
1094 hammer2_spin_ex(&chain->core.spin);
1095 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1097 while (--count >= 0) {
1098 if (base[count].type)
1101 chain->core.live_zero = count + 1;
1102 while (count >= 0) {
1103 if (base[count].type)
1104 atomic_add_int(&chain->core.live_count,
1109 chain->core.live_zero = 0;
1111 /* else do not modify live_count */
1112 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1114 hammer2_spin_unex(&chain->core.spin);
1118 * Resize the chain's physical storage allocation in-place. This function does
1119 * not adjust the data pointer and must be followed by (typically) a
1120 * hammer2_chain_modify() call to copy any old data over and adjust the
1123 * Chains can be resized smaller without reallocating the storage. Resizing
1124 * larger will reallocate the storage. Excess or prior storage is reclaimed
1125 * asynchronously at a later time.
1127 * Must be passed an exclusively locked parent and chain.
1129 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1130 * to avoid instantiating a device buffer that conflicts with the vnode data
1131 * buffer. However, because H2 can compress or encrypt data, the chain may
1132 * have a dio assigned to it in those situations, and they do not conflict.
1134 * XXX return error if cannot resize.
1137 hammer2_chain_resize(hammer2_inode_t *ip,
1138 hammer2_chain_t *parent, hammer2_chain_t *chain,
1139 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1140 int nradix, int flags)
1149 * Only data and indirect blocks can be resized for now.
1150 * (The volu root, inodes, and freemap elements use a fixed size).
1152 KKASSERT(chain != &hmp->vchain);
1153 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1154 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1155 KKASSERT(chain->parent == parent);
1158 * Nothing to do if the element is already the proper size
1160 obytes = chain->bytes;
1161 nbytes = 1U << nradix;
1162 if (obytes == nbytes)
1166 * Make sure the old data is instantiated so we can copy it. If this
1167 * is a data block, the device data may be superfluous since the data
1168 * might be in a logical block, but compressed or encrypted data is
1171 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1173 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1176 * Relocate the block, even if making it smaller (because different
1177 * block sizes may be in different regions).
1179 * (data blocks only, we aren't copying the storage here).
1181 hammer2_freemap_alloc(chain, nbytes);
1182 chain->bytes = nbytes;
1183 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1186 * We don't want the followup chain_modify() to try to copy data
1187 * from the old (wrong-sized) buffer. It won't know how much to
1188 * copy. This case should only occur during writes when the
1189 * originator already has the data to write in-hand.
1192 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1193 hammer2_io_brelse(&chain->dio);
1199 * Set the chain modified so its data can be changed by the caller.
1201 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1202 * is a CLC (cluster level change) field and is not updated by parent
1203 * propagation during a flush.
1205 * If the caller passes a non-zero dedup_off we assign data_off to that
1206 * instead of allocating a ne block. Caller must not modify the data already
1207 * present at the target offset.
1210 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1211 hammer2_off_t dedup_off, int flags)
1213 hammer2_blockref_t obref;
1222 obref = chain->bref;
1223 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1226 * Data is not optional for freemap chains (we must always be sure
1227 * to copy the data on COW storage allocations).
1229 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1230 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1231 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1232 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1236 * Data must be resolved if already assigned, unless explicitly
1237 * flagged otherwise.
1239 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1240 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1241 hammer2_chain_load_data(chain);
1245 * Set MODIFIED to indicate that the chain has been modified.
1246 * Set UPDATE to ensure that the blockref is updated in the parent.
1248 if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1249 (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1251 * Modified already set but a new allocation is needed
1252 * anyway because we recorded this data_off for possible
1256 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1258 * Must set modified bit.
1260 atomic_add_long(&hammer2_count_modified_chains, 1);
1261 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1262 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1266 * Already flagged modified, no new allocation is needed.
1272 * Flag parent update required, clear DEDUP flag (already processed
1275 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1276 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1277 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1280 * The modification or re-modification requires an allocation and
1283 * If dedup_off is non-zero, caller already has a data offset
1284 * containing the caller's desired data. The dedup offset is
1285 * allowed to be in a partially free state and we must be sure
1286 * to reset it to a fully allocated state to force two bulkfree
1287 * passes to free it again.
1289 * XXX can a chain already be marked MODIFIED without a data
1290 * assignment? If not, assert here instead of testing the case.
1292 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1293 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1297 chain->bref.data_off = dedup_off;
1298 chain->bytes = 1 << (dedup_off &
1299 HAMMER2_OFF_MASK_RADIX);
1300 atomic_set_int(&chain->flags,
1301 HAMMER2_CHAIN_DEDUP);
1302 hammer2_freemap_adjust(hmp, &chain->bref,
1303 HAMMER2_FREEMAP_DORECOVER);
1305 hammer2_freemap_alloc(chain, chain->bytes);
1307 /* XXX failed allocation */
1312 * Update mirror_tid and modify_tid. modify_tid is only updated
1313 * if not passed as zero (during flushes, parent propagation passes
1316 * NOTE: chain->pmp could be the device spmp.
1318 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1320 chain->bref.modify_tid = mtid;
1323 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1324 * requires updating as well as to tell the delete code that the
1325 * chain's blockref might not exactly match (in terms of physical size
1326 * or block offset) the one in the parent's blocktable. The base key
1327 * of course will still match.
1329 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1330 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1333 * Short-cut data blocks which the caller does not need an actual
1334 * data reference to (aka OPTDATA), as long as the chain does not
1335 * already have a data pointer to the data. This generally means
1336 * that the modifications are being done via the logical buffer cache.
1337 * The INITIAL flag relates only to the device data buffer and thus
1338 * remains unchange in this situation.
1340 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1341 (flags & HAMMER2_MODIFY_OPTDATA) &&
1342 chain->data == NULL) {
1347 * Clearing the INITIAL flag (for indirect blocks) indicates that
1348 * we've processed the uninitialized storage allocation.
1350 * If this flag is already clear we are likely in a copy-on-write
1351 * situation but we have to be sure NOT to bzero the storage if
1352 * no data is present.
1354 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1355 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1362 * Instantiate data buffer and possibly execute COW operation
1364 switch(chain->bref.type) {
1365 case HAMMER2_BREF_TYPE_VOLUME:
1366 case HAMMER2_BREF_TYPE_FREEMAP:
1368 * The data is embedded, no copy-on-write operation is
1371 KKASSERT(chain->dio == NULL);
1373 case HAMMER2_BREF_TYPE_INODE:
1374 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1375 case HAMMER2_BREF_TYPE_DATA:
1376 case HAMMER2_BREF_TYPE_INDIRECT:
1377 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1379 * Perform the copy-on-write operation
1381 * zero-fill or copy-on-write depending on whether
1382 * chain->data exists or not and set the dirty state for
1383 * the new buffer. hammer2_io_new() will handle the
1386 * If a dedup_off was supplied this is an existing block
1387 * and no COW, copy, or further modification is required.
1389 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1391 if (wasinitial && dedup_off == 0) {
1392 error = hammer2_io_new(hmp, chain->bref.data_off,
1393 chain->bytes, &dio);
1395 error = hammer2_io_bread(hmp, chain->bref.data_off,
1396 chain->bytes, &dio);
1398 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1401 * If an I/O error occurs make sure callers cannot accidently
1402 * modify the old buffer's contents and corrupt the filesystem.
1405 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1407 chain->error = HAMMER2_ERROR_IO;
1408 hammer2_io_brelse(&dio);
1409 hammer2_io_brelse(&chain->dio);
1414 bdata = hammer2_io_data(dio, chain->bref.data_off);
1418 * COW (unless a dedup).
1420 KKASSERT(chain->dio != NULL);
1421 if (chain->data != (void *)bdata && dedup_off == 0) {
1422 bcopy(chain->data, bdata, chain->bytes);
1424 } else if (wasinitial == 0) {
1426 * We have a problem. We were asked to COW but
1427 * we don't have any data to COW with!
1429 panic("hammer2_chain_modify: having a COW %p\n",
1434 * Retire the old buffer, replace with the new. Dirty or
1435 * redirty the new buffer.
1437 * WARNING! The system buffer cache may have already flushed
1438 * the buffer, so we must be sure to [re]dirty it
1439 * for further modification.
1441 * If dedup_off was supplied, the caller is not
1442 * expected to make any further modification to the
1446 hammer2_io_bqrelse(&chain->dio);
1447 chain->data = (void *)bdata;
1450 hammer2_io_setdirty(dio);
1453 panic("hammer2_chain_modify: illegal non-embedded type %d",
1460 * setflush on parent indicating that the parent must recurse down
1461 * to us. Do not call on chain itself which might already have it
1465 hammer2_chain_setflush(chain->parent);
1469 * Modify the chain associated with an inode.
1472 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1473 hammer2_tid_t mtid, int flags)
1475 hammer2_inode_modify(ip);
1476 hammer2_chain_modify(chain, mtid, 0, flags);
1480 * Volume header data locks
1483 hammer2_voldata_lock(hammer2_dev_t *hmp)
1485 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1489 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1491 lockmgr(&hmp->vollk, LK_RELEASE);
1495 hammer2_voldata_modify(hammer2_dev_t *hmp)
1497 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1498 atomic_add_long(&hammer2_count_modified_chains, 1);
1499 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1500 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1505 * This function returns the chain at the nearest key within the specified
1506 * range. The returned chain will be referenced but not locked.
1508 * This function will recurse through chain->rbtree as necessary and will
1509 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1510 * the iteration value is less than the current value of *key_nextp.
1512 * The caller should use (*key_nextp) to calculate the actual range of
1513 * the returned element, which will be (key_beg to *key_nextp - 1), because
1514 * there might be another element which is superior to the returned element
1517 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1518 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1519 * it will wind up being (key_end + 1).
1521 * WARNING! Must be called with child's spinlock held. Spinlock remains
1522 * held through the operation.
1524 struct hammer2_chain_find_info {
1525 hammer2_chain_t *best;
1526 hammer2_key_t key_beg;
1527 hammer2_key_t key_end;
1528 hammer2_key_t key_next;
1531 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1532 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1536 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1537 hammer2_key_t key_beg, hammer2_key_t key_end)
1539 struct hammer2_chain_find_info info;
1542 info.key_beg = key_beg;
1543 info.key_end = key_end;
1544 info.key_next = *key_nextp;
1546 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1547 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1549 *key_nextp = info.key_next;
1551 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1552 parent, key_beg, key_end, *key_nextp);
1560 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1562 struct hammer2_chain_find_info *info = data;
1563 hammer2_key_t child_beg;
1564 hammer2_key_t child_end;
1566 child_beg = child->bref.key;
1567 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1569 if (child_end < info->key_beg)
1571 if (child_beg > info->key_end)
1578 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1580 struct hammer2_chain_find_info *info = data;
1581 hammer2_chain_t *best;
1582 hammer2_key_t child_end;
1585 * WARNING! Do not discard DUPLICATED chains, it is possible that
1586 * we are catching an insertion half-way done. If a
1587 * duplicated chain turns out to be the best choice the
1588 * caller will re-check its flags after locking it.
1590 * WARNING! Layerq is scanned forwards, exact matches should keep
1591 * the existing info->best.
1593 if ((best = info->best) == NULL) {
1595 * No previous best. Assign best
1598 } else if (best->bref.key <= info->key_beg &&
1599 child->bref.key <= info->key_beg) {
1604 /*info->best = child;*/
1605 } else if (child->bref.key < best->bref.key) {
1607 * Child has a nearer key and best is not flush with key_beg.
1608 * Set best to child. Truncate key_next to the old best key.
1611 if (info->key_next > best->bref.key || info->key_next == 0)
1612 info->key_next = best->bref.key;
1613 } else if (child->bref.key == best->bref.key) {
1615 * If our current best is flush with the child then this
1616 * is an illegal overlap.
1618 * key_next will automatically be limited to the smaller of
1619 * the two end-points.
1625 * Keep the current best but truncate key_next to the child's
1628 * key_next will also automatically be limited to the smaller
1629 * of the two end-points (probably not necessary for this case
1630 * but we do it anyway).
1632 if (info->key_next > child->bref.key || info->key_next == 0)
1633 info->key_next = child->bref.key;
1637 * Always truncate key_next based on child's end-of-range.
1639 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1640 if (child_end && (info->key_next > child_end || info->key_next == 0))
1641 info->key_next = child_end;
1647 * Retrieve the specified chain from a media blockref, creating the
1648 * in-memory chain structure which reflects it.
1650 * To handle insertion races pass the INSERT_RACE flag along with the
1651 * generation number of the core. NULL will be returned if the generation
1652 * number changes before we have a chance to insert the chain. Insert
1653 * races can occur because the parent might be held shared.
1655 * Caller must hold the parent locked shared or exclusive since we may
1656 * need the parent's bref array to find our block.
1658 * WARNING! chain->pmp is always set to NULL for any chain representing
1659 * part of the super-root topology.
1662 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1663 hammer2_blockref_t *bref)
1665 hammer2_dev_t *hmp = parent->hmp;
1666 hammer2_chain_t *chain;
1670 * Allocate a chain structure representing the existing media
1671 * entry. Resulting chain has one ref and is not locked.
1673 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1674 chain = hammer2_chain_alloc(hmp, NULL, bref);
1676 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1677 /* ref'd chain returned */
1680 * Flag that the chain is in the parent's blockmap so delete/flush
1681 * knows what to do with it.
1683 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1686 * Link the chain into its parent. A spinlock is required to safely
1687 * access the RBTREE, and it is possible to collide with another
1688 * hammer2_chain_get() operation because the caller might only hold
1689 * a shared lock on the parent.
1691 KKASSERT(parent->refs > 0);
1692 error = hammer2_chain_insert(parent, chain,
1693 HAMMER2_CHAIN_INSERT_SPIN |
1694 HAMMER2_CHAIN_INSERT_RACE,
1697 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1698 kprintf("chain %p get race\n", chain);
1699 hammer2_chain_drop(chain);
1702 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1706 * Return our new chain referenced but not locked, or NULL if
1713 * Lookup initialization/completion API
1716 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1718 hammer2_chain_ref(parent);
1719 if (flags & HAMMER2_LOOKUP_SHARED) {
1720 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1721 HAMMER2_RESOLVE_SHARED);
1723 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1729 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1732 hammer2_chain_unlock(parent);
1733 hammer2_chain_drop(parent);
1738 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1740 hammer2_chain_t *oparent;
1741 hammer2_chain_t *nparent;
1744 * Be careful of order, oparent must be unlocked before nparent
1745 * is locked below to avoid a deadlock.
1748 hammer2_spin_ex(&oparent->core.spin);
1749 nparent = oparent->parent;
1750 hammer2_chain_ref(nparent);
1751 hammer2_spin_unex(&oparent->core.spin);
1753 hammer2_chain_unlock(oparent);
1754 hammer2_chain_drop(oparent);
1758 hammer2_chain_lock(nparent, how);
1765 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1766 * (*parentp) typically points to an inode but can also point to a related
1767 * indirect block and this function will recurse upwards and find the inode
1770 * (*parentp) must be exclusively locked and referenced and can be an inode
1771 * or an existing indirect block within the inode.
1773 * On return (*parentp) will be modified to point at the deepest parent chain
1774 * element encountered during the search, as a helper for an insertion or
1775 * deletion. The new (*parentp) will be locked and referenced and the old
1776 * will be unlocked and dereferenced (no change if they are both the same).
1778 * The matching chain will be returned exclusively locked. If NOLOCK is
1779 * requested the chain will be returned only referenced. Note that the
1780 * parent chain must always be locked shared or exclusive, matching the
1781 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1782 * when NOLOCK is specified but that complicates matters if *parentp must
1783 * inherit the chain.
1785 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1786 * data pointer or can otherwise be in flux.
1788 * NULL is returned if no match was found, but (*parentp) will still
1789 * potentially be adjusted.
1791 * If a fatal error occurs (typically an I/O error), a dummy chain is
1792 * returned with chain->error and error-identifying information set. This
1793 * chain will assert if you try to do anything fancy with it.
1795 * XXX Depending on where the error occurs we should allow continued iteration.
1797 * On return (*key_nextp) will point to an iterative value for key_beg.
1798 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1800 * This function will also recurse up the chain if the key is not within the
1801 * current parent's range. (*parentp) can never be set to NULL. An iteration
1802 * can simply allow (*parentp) to float inside the loop.
1804 * NOTE! chain->data is not always resolved. By default it will not be
1805 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1806 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1807 * BREF_TYPE_DATA as the device buffer can alias the logical file
1811 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1812 hammer2_key_t key_beg, hammer2_key_t key_end,
1813 int *cache_indexp, int flags)
1816 hammer2_chain_t *parent;
1817 hammer2_chain_t *chain;
1818 hammer2_blockref_t *base;
1819 hammer2_blockref_t *bref;
1820 hammer2_blockref_t bcopy;
1821 hammer2_key_t scan_beg;
1822 hammer2_key_t scan_end;
1824 int how_always = HAMMER2_RESOLVE_ALWAYS;
1825 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1828 int maxloops = 300000;
1830 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1831 how_maybe = how_always;
1832 how = HAMMER2_RESOLVE_ALWAYS;
1833 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1834 how = HAMMER2_RESOLVE_NEVER;
1836 how = HAMMER2_RESOLVE_MAYBE;
1838 if (flags & HAMMER2_LOOKUP_SHARED) {
1839 how_maybe |= HAMMER2_RESOLVE_SHARED;
1840 how_always |= HAMMER2_RESOLVE_SHARED;
1841 how |= HAMMER2_RESOLVE_SHARED;
1845 * Recurse (*parentp) upward if necessary until the parent completely
1846 * encloses the key range or we hit the inode.
1848 * This function handles races against the flusher doing a delete-
1849 * duplicate above us and re-homes the parent to the duplicate in
1850 * that case, otherwise we'd wind up recursing down a stale chain.
1855 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1856 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1857 scan_beg = parent->bref.key;
1858 scan_end = scan_beg +
1859 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1860 if (key_beg >= scan_beg && key_end <= scan_end)
1862 parent = hammer2_chain_getparent(parentp, how_maybe);
1866 if (--maxloops == 0)
1867 panic("hammer2_chain_lookup: maxloops");
1869 * Locate the blockref array. Currently we do a fully associative
1870 * search through the array.
1872 switch(parent->bref.type) {
1873 case HAMMER2_BREF_TYPE_INODE:
1875 * Special shortcut for embedded data returns the inode
1876 * itself. Callers must detect this condition and access
1877 * the embedded data (the strategy code does this for us).
1879 * This is only applicable to regular files and softlinks.
1881 if (parent->data->ipdata.meta.op_flags &
1882 HAMMER2_OPFLAG_DIRECTDATA) {
1883 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1885 *key_nextp = key_end + 1;
1888 hammer2_chain_ref(parent);
1889 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1890 hammer2_chain_lock(parent, how_always);
1891 *key_nextp = key_end + 1;
1894 base = &parent->data->ipdata.u.blockset.blockref[0];
1895 count = HAMMER2_SET_COUNT;
1897 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1898 case HAMMER2_BREF_TYPE_INDIRECT:
1900 * Handle MATCHIND on the parent
1902 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1903 scan_beg = parent->bref.key;
1904 scan_end = scan_beg +
1905 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1906 if (key_beg == scan_beg && key_end == scan_end) {
1908 hammer2_chain_ref(chain);
1909 hammer2_chain_lock(chain, how_maybe);
1910 *key_nextp = scan_end + 1;
1915 * Optimize indirect blocks in the INITIAL state to avoid
1918 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1921 if (parent->data == NULL)
1922 panic("parent->data is NULL");
1923 base = &parent->data->npdata[0];
1925 count = parent->bytes / sizeof(hammer2_blockref_t);
1927 case HAMMER2_BREF_TYPE_VOLUME:
1928 base = &parent->data->voldata.sroot_blockset.blockref[0];
1929 count = HAMMER2_SET_COUNT;
1931 case HAMMER2_BREF_TYPE_FREEMAP:
1932 base = &parent->data->blkset.blockref[0];
1933 count = HAMMER2_SET_COUNT;
1936 kprintf("hammer2_chain_lookup: unrecognized "
1937 "blockref(B) type: %d",
1940 tsleep(&base, 0, "dead", 0);
1941 panic("hammer2_chain_lookup: unrecognized "
1942 "blockref(B) type: %d",
1944 base = NULL; /* safety */
1945 count = 0; /* safety */
1949 * Merged scan to find next candidate.
1951 * hammer2_base_*() functions require the parent->core.live_* fields
1952 * to be synchronized.
1954 * We need to hold the spinlock to access the block array and RB tree
1955 * and to interlock chain creation.
1957 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1958 hammer2_chain_countbrefs(parent, base, count);
1963 hammer2_spin_ex(&parent->core.spin);
1964 chain = hammer2_combined_find(parent, base, count,
1965 cache_indexp, key_nextp,
1968 generation = parent->core.generation;
1971 * Exhausted parent chain, iterate.
1974 hammer2_spin_unex(&parent->core.spin);
1975 if (key_beg == key_end) /* short cut single-key case */
1979 * Stop if we reached the end of the iteration.
1981 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1982 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1987 * Calculate next key, stop if we reached the end of the
1988 * iteration, otherwise go up one level and loop.
1990 key_beg = parent->bref.key +
1991 ((hammer2_key_t)1 << parent->bref.keybits);
1992 if (key_beg == 0 || key_beg > key_end)
1994 parent = hammer2_chain_getparent(parentp, how_maybe);
1999 * Selected from blockref or in-memory chain.
2001 if (chain == NULL) {
2003 hammer2_spin_unex(&parent->core.spin);
2004 chain = hammer2_chain_get(parent, generation,
2006 if (chain == NULL) {
2007 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2008 parent, key_beg, key_end);
2011 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2012 hammer2_chain_drop(chain);
2016 hammer2_chain_ref(chain);
2017 hammer2_spin_unex(&parent->core.spin);
2021 * chain is referenced but not locked. We must lock the chain
2022 * to obtain definitive DUPLICATED/DELETED state
2024 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2025 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2026 hammer2_chain_lock(chain, how_maybe);
2028 hammer2_chain_lock(chain, how);
2032 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2034 * NOTE: Chain's key range is not relevant as there might be
2035 * one-offs within the range that are not deleted.
2037 * NOTE: Lookups can race delete-duplicate because
2038 * delete-duplicate does not lock the parent's core
2039 * (they just use the spinlock on the core). We must
2040 * check for races by comparing the DUPLICATED flag before
2041 * releasing the spinlock with the flag after locking the
2044 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2045 hammer2_chain_unlock(chain);
2046 hammer2_chain_drop(chain);
2047 key_beg = *key_nextp;
2048 if (key_beg == 0 || key_beg > key_end)
2054 * If the chain element is an indirect block it becomes the new
2055 * parent and we loop on it. We must maintain our top-down locks
2056 * to prevent the flusher from interfering (i.e. doing a
2057 * delete-duplicate and leaving us recursing down a deleted chain).
2059 * The parent always has to be locked with at least RESOLVE_MAYBE
2060 * so we can access its data. It might need a fixup if the caller
2061 * passed incompatible flags. Be careful not to cause a deadlock
2062 * as a data-load requires an exclusive lock.
2064 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2065 * range is within the requested key range we return the indirect
2066 * block and do NOT loop. This is usually only used to acquire
2069 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2070 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2071 hammer2_chain_unlock(parent);
2072 hammer2_chain_drop(parent);
2073 *parentp = parent = chain;
2078 * All done, return the chain.
2080 * If the caller does not want a locked chain, replace the lock with
2081 * a ref. Perhaps this can eventually be optimized to not obtain the
2082 * lock in the first place for situations where the data does not
2083 * need to be resolved.
2086 if (flags & HAMMER2_LOOKUP_NOLOCK)
2087 hammer2_chain_unlock(chain);
2094 * After having issued a lookup we can iterate all matching keys.
2096 * If chain is non-NULL we continue the iteration from just after it's index.
2098 * If chain is NULL we assume the parent was exhausted and continue the
2099 * iteration at the next parent.
2101 * If a fatal error occurs (typically an I/O error), a dummy chain is
2102 * returned with chain->error and error-identifying information set. This
2103 * chain will assert if you try to do anything fancy with it.
2105 * XXX Depending on where the error occurs we should allow continued iteration.
2107 * parent must be locked on entry and remains locked throughout. chain's
2108 * lock status must match flags. Chain is always at least referenced.
2110 * WARNING! The MATCHIND flag does not apply to this function.
2113 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2114 hammer2_key_t *key_nextp,
2115 hammer2_key_t key_beg, hammer2_key_t key_end,
2116 int *cache_indexp, int flags)
2118 hammer2_chain_t *parent;
2122 * Calculate locking flags for upward recursion.
2124 how_maybe = HAMMER2_RESOLVE_MAYBE;
2125 if (flags & HAMMER2_LOOKUP_SHARED)
2126 how_maybe |= HAMMER2_RESOLVE_SHARED;
2131 * Calculate the next index and recalculate the parent if necessary.
2134 key_beg = chain->bref.key +
2135 ((hammer2_key_t)1 << chain->bref.keybits);
2136 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2137 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2138 hammer2_chain_unlock(chain);
2140 hammer2_chain_drop(chain);
2143 * chain invalid past this point, but we can still do a
2144 * pointer comparison w/parent.
2146 * Any scan where the lookup returned degenerate data embedded
2147 * in the inode has an invalid index and must terminate.
2149 if (chain == parent)
2151 if (key_beg == 0 || key_beg > key_end)
2154 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2155 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2157 * We reached the end of the iteration.
2162 * Continue iteration with next parent unless the current
2163 * parent covers the range.
2165 key_beg = parent->bref.key +
2166 ((hammer2_key_t)1 << parent->bref.keybits);
2167 if (key_beg == 0 || key_beg > key_end)
2169 parent = hammer2_chain_getparent(parentp, how_maybe);
2175 return (hammer2_chain_lookup(parentp, key_nextp,
2177 cache_indexp, flags));
2181 * The raw scan function is similar to lookup/next but does not seek to a key.
2182 * Blockrefs are iterated via first_bref = (parent, NULL) and
2183 * next_chain = (parent, bref).
2185 * The passed-in parent must be locked and its data resolved. The function
2186 * nominally returns a locked and referenced *chainp != NULL for chains
2187 * the caller might need to recurse on (and will dipose of any *chainp passed
2188 * in). The caller must check the chain->bref.type either way.
2190 * *chainp is not set for leaf elements.
2192 * This function takes a pointer to a stack-based bref structure whos
2193 * contents is updated for each iteration. The same pointer is returned,
2194 * or NULL when the iteration is complete. *firstp must be set to 1 for
2195 * the first ieration. This function will set it to 0.
2197 hammer2_blockref_t *
2198 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2199 hammer2_blockref_t *bref, int *firstp,
2200 int *cache_indexp, int flags)
2203 hammer2_blockref_t *base;
2204 hammer2_blockref_t *bref_ptr;
2206 hammer2_key_t next_key;
2207 hammer2_chain_t *chain = NULL;
2209 int how_always = HAMMER2_RESOLVE_ALWAYS;
2210 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2213 int maxloops = 300000;
2218 * Scan flags borrowed from lookup.
2220 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2221 how_maybe = how_always;
2222 how = HAMMER2_RESOLVE_ALWAYS;
2223 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2224 how = HAMMER2_RESOLVE_NEVER;
2226 how = HAMMER2_RESOLVE_MAYBE;
2228 if (flags & HAMMER2_LOOKUP_SHARED) {
2229 how_maybe |= HAMMER2_RESOLVE_SHARED;
2230 how_always |= HAMMER2_RESOLVE_SHARED;
2231 how |= HAMMER2_RESOLVE_SHARED;
2235 * Calculate key to locate first/next element, unlocking the previous
2236 * element as we go. Be careful, the key calculation can overflow.
2238 * (also reset bref to NULL)
2244 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2245 if ((chain = *chainp) != NULL) {
2247 hammer2_chain_unlock(chain);
2248 hammer2_chain_drop(chain);
2258 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2259 if (--maxloops == 0)
2260 panic("hammer2_chain_scan: maxloops");
2262 * Locate the blockref array. Currently we do a fully associative
2263 * search through the array.
2265 switch(parent->bref.type) {
2266 case HAMMER2_BREF_TYPE_INODE:
2268 * An inode with embedded data has no sub-chains.
2270 * WARNING! Bulk scan code may pass a static chain marked
2271 * as BREF_TYPE_INODE with a copy of the volume
2272 * root blockset to snapshot the volume.
2274 if (parent->data->ipdata.meta.op_flags &
2275 HAMMER2_OPFLAG_DIRECTDATA) {
2279 base = &parent->data->ipdata.u.blockset.blockref[0];
2280 count = HAMMER2_SET_COUNT;
2282 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2283 case HAMMER2_BREF_TYPE_INDIRECT:
2285 * Optimize indirect blocks in the INITIAL state to avoid
2288 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2291 if (parent->data == NULL)
2292 panic("parent->data is NULL");
2293 base = &parent->data->npdata[0];
2295 count = parent->bytes / sizeof(hammer2_blockref_t);
2297 case HAMMER2_BREF_TYPE_VOLUME:
2298 base = &parent->data->voldata.sroot_blockset.blockref[0];
2299 count = HAMMER2_SET_COUNT;
2301 case HAMMER2_BREF_TYPE_FREEMAP:
2302 base = &parent->data->blkset.blockref[0];
2303 count = HAMMER2_SET_COUNT;
2306 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2308 base = NULL; /* safety */
2309 count = 0; /* safety */
2313 * Merged scan to find next candidate.
2315 * hammer2_base_*() functions require the parent->core.live_* fields
2316 * to be synchronized.
2318 * We need to hold the spinlock to access the block array and RB tree
2319 * and to interlock chain creation.
2321 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2322 hammer2_chain_countbrefs(parent, base, count);
2326 hammer2_spin_ex(&parent->core.spin);
2327 chain = hammer2_combined_find(parent, base, count,
2328 cache_indexp, &next_key,
2329 key, HAMMER2_KEY_MAX,
2331 generation = parent->core.generation;
2334 * Exhausted parent chain, we're done.
2336 if (bref_ptr == NULL) {
2337 hammer2_spin_unex(&parent->core.spin);
2338 KKASSERT(chain == NULL);
2344 * Copy into the supplied stack-based blockref.
2349 * Selected from blockref or in-memory chain.
2351 if (chain == NULL) {
2352 switch(bref->type) {
2353 case HAMMER2_BREF_TYPE_INODE:
2354 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2355 case HAMMER2_BREF_TYPE_INDIRECT:
2356 case HAMMER2_BREF_TYPE_VOLUME:
2357 case HAMMER2_BREF_TYPE_FREEMAP:
2359 * Recursion, always get the chain
2361 hammer2_spin_unex(&parent->core.spin);
2362 chain = hammer2_chain_get(parent, generation, bref);
2363 if (chain == NULL) {
2364 kprintf("retry scan parent %p keys %016jx\n",
2368 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2369 hammer2_chain_drop(chain);
2376 * No recursion, do not waste time instantiating
2377 * a chain, just iterate using the bref.
2379 hammer2_spin_unex(&parent->core.spin);
2384 * Recursion or not we need the chain in order to supply
2387 hammer2_chain_ref(chain);
2388 hammer2_spin_unex(&parent->core.spin);
2392 * chain is referenced but not locked. We must lock the chain
2393 * to obtain definitive DUPLICATED/DELETED state
2396 hammer2_chain_lock(chain, how);
2399 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2401 * NOTE: chain's key range is not relevant as there might be
2402 * one-offs within the range that are not deleted.
2404 * NOTE: XXX this could create problems with scans used in
2405 * situations other than mount-time recovery.
2407 * NOTE: Lookups can race delete-duplicate because
2408 * delete-duplicate does not lock the parent's core
2409 * (they just use the spinlock on the core). We must
2410 * check for races by comparing the DUPLICATED flag before
2411 * releasing the spinlock with the flag after locking the
2414 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2415 hammer2_chain_unlock(chain);
2416 hammer2_chain_drop(chain);
2429 * All done, return the bref or NULL, supply chain if necessary.
2437 * Create and return a new hammer2 system memory structure of the specified
2438 * key, type and size and insert it under (*parentp). This is a full
2439 * insertion, based on the supplied key/keybits, and may involve creating
2440 * indirect blocks and moving other chains around via delete/duplicate.
2442 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2443 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2444 * FULL. This typically means that the caller is creating the chain after
2445 * doing a hammer2_chain_lookup().
2447 * (*parentp) must be exclusive locked and may be replaced on return
2448 * depending on how much work the function had to do.
2450 * (*parentp) must not be errored or this function will assert.
2452 * (*chainp) usually starts out NULL and returns the newly created chain,
2453 * but if the caller desires the caller may allocate a disconnected chain
2454 * and pass it in instead.
2456 * This function should NOT be used to insert INDIRECT blocks. It is
2457 * typically used to create/insert inodes and data blocks.
2459 * Caller must pass-in an exclusively locked parent the new chain is to
2460 * be inserted under, and optionally pass-in a disconnected, exclusively
2461 * locked chain to insert (else we create a new chain). The function will
2462 * adjust (*parentp) as necessary, create or connect the chain, and
2463 * return an exclusively locked chain in *chainp.
2465 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2466 * and will be reassigned.
2469 hammer2_chain_create(hammer2_chain_t **parentp,
2470 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2471 hammer2_key_t key, int keybits, int type, size_t bytes,
2472 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2475 hammer2_chain_t *chain;
2476 hammer2_chain_t *parent;
2477 hammer2_blockref_t *base;
2478 hammer2_blockref_t dummy;
2482 int maxloops = 300000;
2485 * Topology may be crossing a PFS boundary.
2488 KKASSERT(hammer2_mtx_owned(&parent->lock));
2489 KKASSERT(parent->error == 0);
2493 if (chain == NULL) {
2495 * First allocate media space and construct the dummy bref,
2496 * then allocate the in-memory chain structure. Set the
2497 * INITIAL flag for fresh chains which do not have embedded
2500 * XXX for now set the check mode of the child based on
2501 * the parent or, if the parent is an inode, the
2502 * specification in the inode.
2504 bzero(&dummy, sizeof(dummy));
2507 dummy.keybits = keybits;
2508 dummy.data_off = hammer2_getradix(bytes);
2509 dummy.methods = parent->bref.methods;
2510 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2512 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2513 dummy.methods |= HAMMER2_ENC_CHECK(
2514 parent->data->ipdata.meta.check_algo);
2517 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2520 * Lock the chain manually, chain_lock will load the chain
2521 * which we do NOT want to do. (note: chain->refs is set
2522 * to 1 by chain_alloc() for us, but lockcnt is not).
2525 hammer2_mtx_ex(&chain->lock);
2527 ++curthread->td_tracker;
2530 * Set INITIAL to optimize I/O. The flag will generally be
2531 * processed when we call hammer2_chain_modify().
2533 * Recalculate bytes to reflect the actual media block
2536 bytes = (hammer2_off_t)1 <<
2537 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2538 chain->bytes = bytes;
2541 case HAMMER2_BREF_TYPE_VOLUME:
2542 case HAMMER2_BREF_TYPE_FREEMAP:
2543 panic("hammer2_chain_create: called with volume type");
2545 case HAMMER2_BREF_TYPE_INDIRECT:
2546 panic("hammer2_chain_create: cannot be used to"
2547 "create indirect block");
2549 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2550 panic("hammer2_chain_create: cannot be used to"
2551 "create freemap root or node");
2553 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2554 KKASSERT(bytes == sizeof(chain->data->bmdata));
2556 case HAMMER2_BREF_TYPE_INODE:
2557 case HAMMER2_BREF_TYPE_DATA:
2560 * leave chain->data NULL, set INITIAL
2562 KKASSERT(chain->data == NULL);
2563 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2568 * We are reattaching a previously deleted chain, possibly
2569 * under a new parent and possibly with a new key/keybits.
2570 * The chain does not have to be in a modified state. The
2571 * UPDATE flag will be set later on in this routine.
2573 * Do NOT mess with the current state of the INITIAL flag.
2575 chain->bref.key = key;
2576 chain->bref.keybits = keybits;
2577 if (chain->flags & HAMMER2_CHAIN_DELETED)
2578 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2579 KKASSERT(chain->parent == NULL);
2581 if (flags & HAMMER2_INSERT_PFSROOT)
2582 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2584 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2587 * Calculate how many entries we have in the blockref array and
2588 * determine if an indirect block is required.
2591 if (--maxloops == 0)
2592 panic("hammer2_chain_create: maxloops");
2594 switch(parent->bref.type) {
2595 case HAMMER2_BREF_TYPE_INODE:
2596 if ((parent->data->ipdata.meta.op_flags &
2597 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2598 kprintf("hammer2: parent set for direct-data! "
2599 "pkey=%016jx ckey=%016jx\n",
2603 KKASSERT((parent->data->ipdata.meta.op_flags &
2604 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2605 KKASSERT(parent->data != NULL);
2606 base = &parent->data->ipdata.u.blockset.blockref[0];
2607 count = HAMMER2_SET_COUNT;
2609 case HAMMER2_BREF_TYPE_INDIRECT:
2610 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2611 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2614 base = &parent->data->npdata[0];
2615 count = parent->bytes / sizeof(hammer2_blockref_t);
2617 case HAMMER2_BREF_TYPE_VOLUME:
2618 KKASSERT(parent->data != NULL);
2619 base = &parent->data->voldata.sroot_blockset.blockref[0];
2620 count = HAMMER2_SET_COUNT;
2622 case HAMMER2_BREF_TYPE_FREEMAP:
2623 KKASSERT(parent->data != NULL);
2624 base = &parent->data->blkset.blockref[0];
2625 count = HAMMER2_SET_COUNT;
2628 panic("hammer2_chain_create: unrecognized blockref type: %d",
2636 * Make sure we've counted the brefs
2638 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2639 hammer2_chain_countbrefs(parent, base, count);
2641 KKASSERT(parent->core.live_count >= 0 &&
2642 parent->core.live_count <= count);
2645 * If no free blockref could be found we must create an indirect
2646 * block and move a number of blockrefs into it. With the parent
2647 * locked we can safely lock each child in order to delete+duplicate
2648 * it without causing a deadlock.
2650 * This may return the new indirect block or the old parent depending
2651 * on where the key falls. NULL is returned on error.
2653 if (parent->core.live_count == count) {
2654 hammer2_chain_t *nparent;
2656 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2657 mtid, type, &error);
2658 if (nparent == NULL) {
2660 hammer2_chain_drop(chain);
2664 if (parent != nparent) {
2665 hammer2_chain_unlock(parent);
2666 hammer2_chain_drop(parent);
2667 parent = *parentp = nparent;
2673 * Link the chain into its parent.
2675 if (chain->parent != NULL)
2676 panic("hammer2: hammer2_chain_create: chain already connected");
2677 KKASSERT(chain->parent == NULL);
2678 hammer2_chain_insert(parent, chain,
2679 HAMMER2_CHAIN_INSERT_SPIN |
2680 HAMMER2_CHAIN_INSERT_LIVE,
2685 * Mark the newly created chain modified. This will cause
2686 * UPDATE to be set and process the INITIAL flag.
2688 * Device buffers are not instantiated for DATA elements
2689 * as these are handled by logical buffers.
2691 * Indirect and freemap node indirect blocks are handled
2692 * by hammer2_chain_create_indirect() and not by this
2695 * Data for all other bref types is expected to be
2696 * instantiated (INODE, LEAF).
2698 switch(chain->bref.type) {
2699 case HAMMER2_BREF_TYPE_DATA:
2700 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2701 case HAMMER2_BREF_TYPE_INODE:
2702 hammer2_chain_modify(chain, mtid, dedup_off,
2703 HAMMER2_MODIFY_OPTDATA);
2707 * Remaining types are not supported by this function.
2708 * In particular, INDIRECT and LEAF_NODE types are
2709 * handled by create_indirect().
2711 panic("hammer2_chain_create: bad type: %d",
2718 * When reconnecting a chain we must set UPDATE and
2719 * setflush so the flush recognizes that it must update
2720 * the bref in the parent.
2722 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
2723 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2727 * We must setflush(parent) to ensure that it recurses through to
2728 * chain. setflush(chain) might not work because ONFLUSH is possibly
2729 * already set in the chain (so it won't recurse up to set it in the
2732 hammer2_chain_setflush(parent);
2741 * Move the chain from its old parent to a new parent. The chain must have
2742 * already been deleted or already disconnected (or never associated) with
2743 * a parent. The chain is reassociated with the new parent and the deleted
2744 * flag will be cleared (no longer deleted). The chain's modification state
2747 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2748 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2749 * FULL. This typically means that the caller is creating the chain after
2750 * doing a hammer2_chain_lookup().
2752 * A non-NULL bref is typically passed when key and keybits must be overridden.
2753 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2754 * from a passed-in bref and uses the old chain's bref for everything else.
2756 * Neither (parent) or (chain) can be errored.
2758 * If (parent) is non-NULL then the new duplicated chain is inserted under
2761 * If (parent) is NULL then the newly duplicated chain is not inserted
2762 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2763 * passing into hammer2_chain_create() after this function returns).
2765 * WARNING! This function calls create which means it can insert indirect
2766 * blocks. This can cause other unrelated chains in the parent to
2767 * be moved to a newly inserted indirect block in addition to the
2771 hammer2_chain_rename(hammer2_blockref_t *bref,
2772 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2773 hammer2_tid_t mtid, int flags)
2776 hammer2_chain_t *parent;
2780 * WARNING! We should never resolve DATA to device buffers
2781 * (XXX allow it if the caller did?), and since
2782 * we currently do not have the logical buffer cache
2783 * buffer in-hand to fix its cached physical offset
2784 * we also force the modify code to not COW it. XXX
2787 KKASSERT(chain->parent == NULL);
2788 KKASSERT(chain->error == 0);
2791 * Now create a duplicate of the chain structure, associating
2792 * it with the same core, making it the same size, pointing it
2793 * to the same bref (the same media block).
2796 bref = &chain->bref;
2797 bytes = (hammer2_off_t)1 <<
2798 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2801 * If parent is not NULL the duplicated chain will be entered under
2802 * the parent and the UPDATE bit set to tell flush to update
2805 * We must setflush(parent) to ensure that it recurses through to
2806 * chain. setflush(chain) might not work because ONFLUSH is possibly
2807 * already set in the chain (so it won't recurse up to set it in the
2810 * Having both chains locked is extremely important for atomicy.
2812 if (parentp && (parent = *parentp) != NULL) {
2813 KKASSERT(hammer2_mtx_owned(&parent->lock));
2814 KKASSERT(parent->refs > 0);
2815 KKASSERT(parent->error == 0);
2817 hammer2_chain_create(parentp, &chain, chain->pmp,
2818 bref->key, bref->keybits, bref->type,
2819 chain->bytes, mtid, 0, flags);
2820 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2821 hammer2_chain_setflush(*parentp);
2826 * Helper function for deleting chains.
2828 * The chain is removed from the live view (the RBTREE) as well as the parent's
2829 * blockmap. Both chain and its parent must be locked.
2831 * parent may not be errored. chain can be errored.
2834 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2835 hammer2_tid_t mtid, int flags)
2839 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2840 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2841 KKASSERT(chain->parent == parent);
2844 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2846 * Chain is blockmapped, so there must be a parent.
2847 * Atomically remove the chain from the parent and remove
2848 * the blockmap entry. The parent must be set modified
2849 * to remove the blockmap entry.
2851 hammer2_blockref_t *base;
2854 KKASSERT(parent != NULL);
2855 KKASSERT(parent->error == 0);
2856 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2857 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2860 * Calculate blockmap pointer
2862 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2863 hammer2_spin_ex(&parent->core.spin);
2865 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2866 atomic_add_int(&parent->core.live_count, -1);
2867 ++parent->core.generation;
2868 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2869 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2870 --parent->core.chain_count;
2871 chain->parent = NULL;
2873 switch(parent->bref.type) {
2874 case HAMMER2_BREF_TYPE_INODE:
2876 * Access the inode's block array. However, there
2877 * is no block array if the inode is flagged
2878 * DIRECTDATA. The DIRECTDATA case typicaly only
2879 * occurs when a hardlink has been shifted up the
2880 * tree and the original inode gets replaced with
2881 * an OBJTYPE_HARDLINK placeholding inode.
2884 (parent->data->ipdata.meta.op_flags &
2885 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2887 &parent->data->ipdata.u.blockset.blockref[0];
2891 count = HAMMER2_SET_COUNT;
2893 case HAMMER2_BREF_TYPE_INDIRECT:
2894 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2896 base = &parent->data->npdata[0];
2899 count = parent->bytes / sizeof(hammer2_blockref_t);
2901 case HAMMER2_BREF_TYPE_VOLUME:
2902 base = &parent->data->voldata.
2903 sroot_blockset.blockref[0];
2904 count = HAMMER2_SET_COUNT;
2906 case HAMMER2_BREF_TYPE_FREEMAP:
2907 base = &parent->data->blkset.blockref[0];
2908 count = HAMMER2_SET_COUNT;
2913 panic("hammer2_flush_pass2: "
2914 "unrecognized blockref type: %d",
2919 * delete blockmapped chain from its parent.
2921 * The parent is not affected by any statistics in chain
2922 * which are pending synchronization. That is, there is
2923 * nothing to undo in the parent since they have not yet
2924 * been incorporated into the parent.
2926 * The parent is affected by statistics stored in inodes.
2927 * Those have already been synchronized, so they must be
2928 * undone. XXX split update possible w/delete in middle?
2931 int cache_index = -1;
2932 hammer2_base_delete(parent, base, count,
2933 &cache_index, chain);
2935 hammer2_spin_unex(&parent->core.spin);
2936 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2938 * Chain is not blockmapped but a parent is present.
2939 * Atomically remove the chain from the parent. There is
2940 * no blockmap entry to remove.
2942 * Because chain was associated with a parent but not
2943 * synchronized, the chain's *_count_up fields contain
2944 * inode adjustment statistics which must be undone.
2946 hammer2_spin_ex(&parent->core.spin);
2947 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2948 atomic_add_int(&parent->core.live_count, -1);
2949 ++parent->core.generation;
2950 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2951 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2952 --parent->core.chain_count;
2953 chain->parent = NULL;
2954 hammer2_spin_unex(&parent->core.spin);
2957 * Chain is not blockmapped and has no parent. This
2958 * is a degenerate case.
2960 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2965 * Create an indirect block that covers one or more of the elements in the
2966 * current parent. Either returns the existing parent with no locking or
2967 * ref changes or returns the new indirect block locked and referenced
2968 * and leaving the original parent lock/ref intact as well.
2970 * If an error occurs, NULL is returned and *errorp is set to the error.
2972 * The returned chain depends on where the specified key falls.
2974 * The key/keybits for the indirect mode only needs to follow three rules:
2976 * (1) That all elements underneath it fit within its key space and
2978 * (2) That all elements outside it are outside its key space.
2980 * (3) When creating the new indirect block any elements in the current
2981 * parent that fit within the new indirect block's keyspace must be
2982 * moved into the new indirect block.
2984 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2985 * keyspace the the current parent, but lookup/iteration rules will
2986 * ensure (and must ensure) that rule (2) for all parents leading up
2987 * to the nearest inode or the root volume header is adhered to. This
2988 * is accomplished by always recursing through matching keyspaces in
2989 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2991 * The current implementation calculates the current worst-case keyspace by
2992 * iterating the current parent and then divides it into two halves, choosing
2993 * whichever half has the most elements (not necessarily the half containing
2994 * the requested key).
2996 * We can also opt to use the half with the least number of elements. This
2997 * causes lower-numbered keys (aka logical file offsets) to recurse through
2998 * fewer indirect blocks and higher-numbered keys to recurse through more.
2999 * This also has the risk of not moving enough elements to the new indirect
3000 * block and being forced to create several indirect blocks before the element
3003 * Must be called with an exclusively locked parent.
3005 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3006 hammer2_key_t *keyp, int keybits,
3007 hammer2_blockref_t *base, int count);
3008 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3009 hammer2_key_t *keyp, int keybits,
3010 hammer2_blockref_t *base, int count);
3013 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3014 hammer2_key_t create_key, int create_bits,
3015 hammer2_tid_t mtid, int for_type, int *errorp)
3018 hammer2_blockref_t *base;
3019 hammer2_blockref_t *bref;
3020 hammer2_blockref_t bcopy;
3021 hammer2_chain_t *chain;
3022 hammer2_chain_t *ichain;
3023 hammer2_chain_t dummy;
3024 hammer2_key_t key = create_key;
3025 hammer2_key_t key_beg;
3026 hammer2_key_t key_end;
3027 hammer2_key_t key_next;
3028 int keybits = create_bits;
3035 int maxloops = 300000;
3038 * Calculate the base blockref pointer or NULL if the chain
3039 * is known to be empty. We need to calculate the array count
3040 * for RB lookups either way.
3044 KKASSERT(hammer2_mtx_owned(&parent->lock));
3046 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3047 base = hammer2_chain_base_and_count(parent, &count);
3050 * dummy used in later chain allocation (no longer used for lookups).
3052 bzero(&dummy, sizeof(dummy));
3055 * When creating an indirect block for a freemap node or leaf
3056 * the key/keybits must be fitted to static radix levels because
3057 * particular radix levels use particular reserved blocks in the
3060 * This routine calculates the key/radix of the indirect block
3061 * we need to create, and whether it is on the high-side or the
3064 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3065 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3066 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3069 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3074 * Normalize the key for the radix being represented, keeping the
3075 * high bits and throwing away the low bits.
3077 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3080 * How big should our new indirect block be? It has to be at least
3081 * as large as its parent.
3083 * The freemap uses a specific indirect block size.
3085 * The first indirect block level down from an inode typically
3086 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3088 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3089 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3090 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3091 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3092 nbytes = HAMMER2_IND_BYTES_MIN;
3094 nbytes = HAMMER2_IND_BYTES_MAX;
3096 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3097 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3098 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3099 nbytes = count * sizeof(hammer2_blockref_t);
3103 * Ok, create our new indirect block
3105 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3106 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3107 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3109 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3111 dummy.bref.key = key;
3112 dummy.bref.keybits = keybits;
3113 dummy.bref.data_off = hammer2_getradix(nbytes);
3114 dummy.bref.methods = parent->bref.methods;
3116 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3117 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3118 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3119 /* ichain has one ref at this point */
3122 * We have to mark it modified to allocate its block, but use
3123 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3124 * it won't be acted upon by the flush code.
3126 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3129 * Iterate the original parent and move the matching brefs into
3130 * the new indirect block.
3132 * XXX handle flushes.
3135 key_end = HAMMER2_KEY_MAX;
3137 hammer2_spin_ex(&parent->core.spin);
3143 * Parent may have been modified, relocating its block array.
3144 * Reload the base pointer.
3146 base = hammer2_chain_base_and_count(parent, &count);
3148 if (++loops > 100000) {
3149 hammer2_spin_unex(&parent->core.spin);
3150 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3151 reason, parent, base, count, key_next);
3155 * NOTE: spinlock stays intact, returned chain (if not NULL)
3156 * is not referenced or locked which means that we
3157 * cannot safely check its flagged / deletion status
3160 chain = hammer2_combined_find(parent, base, count,
3161 &cache_index, &key_next,
3164 generation = parent->core.generation;
3167 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3170 * Skip keys that are not within the key/radix of the new
3171 * indirect block. They stay in the parent.
3173 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3174 (key ^ bref->key)) != 0) {
3175 goto next_key_spinlocked;
3179 * Load the new indirect block by acquiring the related
3180 * chains (potentially from media as it might not be
3181 * in-memory). Then move it to the new parent (ichain)
3182 * via DELETE-DUPLICATE.
3184 * chain is referenced but not locked. We must lock the
3185 * chain to obtain definitive DUPLICATED/DELETED state
3189 * Use chain already present in the RBTREE
3191 hammer2_chain_ref(chain);
3192 hammer2_spin_unex(&parent->core.spin);
3193 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3196 * Get chain for blockref element. _get returns NULL
3197 * on insertion race.
3200 hammer2_spin_unex(&parent->core.spin);
3201 chain = hammer2_chain_get(parent, generation, &bcopy);
3202 if (chain == NULL) {
3204 hammer2_spin_ex(&parent->core.spin);
3207 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3208 kprintf("REASON 2\n");
3210 hammer2_chain_drop(chain);
3211 hammer2_spin_ex(&parent->core.spin);
3214 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3218 * This is always live so if the chain has been deleted
3219 * we raced someone and we have to retry.
3221 * NOTE: Lookups can race delete-duplicate because
3222 * delete-duplicate does not lock the parent's core
3223 * (they just use the spinlock on the core). We must
3224 * check for races by comparing the DUPLICATED flag before
3225 * releasing the spinlock with the flag after locking the
3228 * (note reversed logic for this one)
3230 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3231 hammer2_chain_unlock(chain);
3232 hammer2_chain_drop(chain);
3237 * Shift the chain to the indirect block.
3239 * WARNING! No reason for us to load chain data, pass NOSTATS
3240 * to prevent delete/insert from trying to access
3241 * inode stats (and thus asserting if there is no
3242 * chain->data loaded).
3244 * WARNING! The (parent, chain) deletion may modify the parent
3245 * and invalidate the base pointer.
3247 hammer2_chain_delete(parent, chain, mtid, 0);
3248 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3249 hammer2_chain_unlock(chain);
3250 hammer2_chain_drop(chain);
3251 KKASSERT(parent->refs > 0);
3253 base = NULL; /* safety */
3255 hammer2_spin_ex(&parent->core.spin);
3256 next_key_spinlocked:
3257 if (--maxloops == 0)
3258 panic("hammer2_chain_create_indirect: maxloops");
3260 if (key_next == 0 || key_next > key_end)
3265 hammer2_spin_unex(&parent->core.spin);
3268 * Insert the new indirect block into the parent now that we've
3269 * cleared out some entries in the parent. We calculated a good
3270 * insertion index in the loop above (ichain->index).
3272 * We don't have to set UPDATE here because we mark ichain
3273 * modified down below (so the normal modified -> flush -> set-moved
3274 * sequence applies).
3276 * The insertion shouldn't race as this is a completely new block
3277 * and the parent is locked.
3279 base = NULL; /* safety, parent modify may change address */
3280 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3281 hammer2_chain_insert(parent, ichain,
3282 HAMMER2_CHAIN_INSERT_SPIN |
3283 HAMMER2_CHAIN_INSERT_LIVE,
3287 * Make sure flushes propogate after our manual insertion.
3289 hammer2_chain_setflush(ichain);
3290 hammer2_chain_setflush(parent);
3293 * Figure out what to return.
3295 if (~(((hammer2_key_t)1 << keybits) - 1) &
3296 (create_key ^ key)) {
3298 * Key being created is outside the key range,
3299 * return the original parent.
3301 hammer2_chain_unlock(ichain);
3302 hammer2_chain_drop(ichain);
3305 * Otherwise its in the range, return the new parent.
3306 * (leave both the new and old parent locked).
3315 * Calculate the keybits and highside/lowside of the freemap node the
3316 * caller is creating.
3318 * This routine will specify the next higher-level freemap key/radix
3319 * representing the lowest-ordered set. By doing so, eventually all
3320 * low-ordered sets will be moved one level down.
3322 * We have to be careful here because the freemap reserves a limited
3323 * number of blocks for a limited number of levels. So we can't just
3324 * push indiscriminately.
3327 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3328 int keybits, hammer2_blockref_t *base, int count)
3330 hammer2_chain_t *chain;
3331 hammer2_blockref_t *bref;
3333 hammer2_key_t key_beg;
3334 hammer2_key_t key_end;
3335 hammer2_key_t key_next;
3339 int maxloops = 300000;
3347 * Calculate the range of keys in the array being careful to skip
3348 * slots which are overridden with a deletion.
3351 key_end = HAMMER2_KEY_MAX;
3353 hammer2_spin_ex(&parent->core.spin);
3356 if (--maxloops == 0) {
3357 panic("indkey_freemap shit %p %p:%d\n",
3358 parent, base, count);
3360 chain = hammer2_combined_find(parent, base, count,
3361 &cache_index, &key_next,
3372 * Skip deleted chains.
3374 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3375 if (key_next == 0 || key_next > key_end)
3382 * Use the full live (not deleted) element for the scan
3383 * iteration. HAMMER2 does not allow partial replacements.
3385 * XXX should be built into hammer2_combined_find().
3387 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3389 if (keybits > bref->keybits) {
3391 keybits = bref->keybits;
3392 } else if (keybits == bref->keybits && bref->key < key) {
3399 hammer2_spin_unex(&parent->core.spin);
3402 * Return the keybits for a higher-level FREEMAP_NODE covering
3406 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3407 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3409 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3410 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3412 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3413 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3415 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3416 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3418 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3419 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3421 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3422 panic("hammer2_chain_indkey_freemap: level too high");
3425 panic("hammer2_chain_indkey_freemap: bad radix");
3434 * Calculate the keybits and highside/lowside of the indirect block the
3435 * caller is creating.
3438 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3439 int keybits, hammer2_blockref_t *base, int count)
3441 hammer2_blockref_t *bref;
3442 hammer2_chain_t *chain;
3443 hammer2_key_t key_beg;
3444 hammer2_key_t key_end;
3445 hammer2_key_t key_next;
3451 int maxloops = 300000;
3458 * Calculate the range of keys in the array being careful to skip
3459 * slots which are overridden with a deletion. Once the scan
3460 * completes we will cut the key range in half and shift half the
3461 * range into the new indirect block.
3464 key_end = HAMMER2_KEY_MAX;
3466 hammer2_spin_ex(&parent->core.spin);
3469 if (--maxloops == 0) {
3470 panic("indkey_freemap shit %p %p:%d\n",
3471 parent, base, count);
3473 chain = hammer2_combined_find(parent, base, count,
3474 &cache_index, &key_next,
3485 * NOTE: No need to check DUPLICATED here because we do
3486 * not release the spinlock.
3488 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3489 if (key_next == 0 || key_next > key_end)
3496 * Use the full live (not deleted) element for the scan
3497 * iteration. HAMMER2 does not allow partial replacements.
3499 * XXX should be built into hammer2_combined_find().
3501 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3504 * Expand our calculated key range (key, keybits) to fit
3505 * the scanned key. nkeybits represents the full range
3506 * that we will later cut in half (two halves @ nkeybits - 1).
3509 if (nkeybits < bref->keybits) {
3510 if (bref->keybits > 64) {
3511 kprintf("bad bref chain %p bref %p\n",
3515 nkeybits = bref->keybits;
3517 while (nkeybits < 64 &&
3518 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3519 (key ^ bref->key)) != 0) {
3524 * If the new key range is larger we have to determine
3525 * which side of the new key range the existing keys fall
3526 * under by checking the high bit, then collapsing the
3527 * locount into the hicount or vise-versa.
3529 if (keybits != nkeybits) {
3530 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3541 * The newly scanned key will be in the lower half or the
3542 * upper half of the (new) key range.
3544 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3553 hammer2_spin_unex(&parent->core.spin);
3554 bref = NULL; /* now invalid (safety) */
3557 * Adjust keybits to represent half of the full range calculated
3558 * above (radix 63 max)
3563 * Select whichever half contains the most elements. Theoretically
3564 * we can select either side as long as it contains at least one
3565 * element (in order to ensure that a free slot is present to hold
3566 * the indirect block).
3568 if (hammer2_indirect_optimize) {
3570 * Insert node for least number of keys, this will arrange
3571 * the first few blocks of a large file or the first few
3572 * inodes in a directory with fewer indirect blocks when
3575 if (hicount < locount && hicount != 0)
3576 key |= (hammer2_key_t)1 << keybits;
3578 key &= ~(hammer2_key_t)1 << keybits;
3581 * Insert node for most number of keys, best for heavily
3584 if (hicount > locount)
3585 key |= (hammer2_key_t)1 << keybits;
3587 key &= ~(hammer2_key_t)1 << keybits;
3595 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3598 * Both parent and chain must be locked exclusively.
3600 * This function will modify the parent if the blockref requires removal
3601 * from the parent's block table.
3603 * This function is NOT recursive. Any entity already pushed into the
3604 * chain (such as an inode) may still need visibility into its contents,
3605 * as well as the ability to read and modify the contents. For example,
3606 * for an unlinked file which is still open.
3609 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3610 hammer2_tid_t mtid, int flags)
3612 KKASSERT(hammer2_mtx_owned(&chain->lock));
3615 * Nothing to do if already marked.
3617 * We need the spinlock on the core whos RBTREE contains chain
3618 * to protect against races.
3620 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3621 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3622 chain->parent == parent);
3623 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3627 * Permanent deletions mark the chain as destroyed. H
3629 if (flags & HAMMER2_DELETE_PERMANENT) {
3630 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3632 /* XXX might not be needed */
3633 hammer2_chain_setflush(chain);
3638 * Returns the index of the nearest element in the blockref array >= elm.
3639 * Returns (count) if no element could be found.
3641 * Sets *key_nextp to the next key for loop purposes but does not modify
3642 * it if the next key would be higher than the current value of *key_nextp.
3643 * Note that *key_nexp can overflow to 0, which should be tested by the
3646 * (*cache_indexp) is a heuristic and can be any value without effecting
3649 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3650 * held through the operation.
3653 hammer2_base_find(hammer2_chain_t *parent,
3654 hammer2_blockref_t *base, int count,
3655 int *cache_indexp, hammer2_key_t *key_nextp,
3656 hammer2_key_t key_beg, hammer2_key_t key_end)
3658 hammer2_blockref_t *scan;
3659 hammer2_key_t scan_end;
3664 * Require the live chain's already have their core's counted
3665 * so we can optimize operations.
3667 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3672 if (count == 0 || base == NULL)
3676 * Sequential optimization using *cache_indexp. This is the most
3679 * We can avoid trailing empty entries on live chains, otherwise
3680 * we might have to check the whole block array.
3684 limit = parent->core.live_zero;
3689 KKASSERT(i < count);
3695 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3702 * Search forwards, stop when we find a scan element which
3703 * encloses the key or until we know that there are no further
3707 if (scan->type != 0) {
3708 scan_end = scan->key +
3709 ((hammer2_key_t)1 << scan->keybits) - 1;
3710 if (scan->key > key_beg || scan_end >= key_beg)
3723 scan_end = scan->key +
3724 ((hammer2_key_t)1 << scan->keybits);
3725 if (scan_end && (*key_nextp > scan_end ||
3727 *key_nextp = scan_end;
3735 * Do a combined search and return the next match either from the blockref
3736 * array or from the in-memory chain. Sets *bresp to the returned bref in
3737 * both cases, or sets it to NULL if the search exhausted. Only returns
3738 * a non-NULL chain if the search matched from the in-memory chain.
3740 * When no in-memory chain has been found and a non-NULL bref is returned
3744 * The returned chain is not locked or referenced. Use the returned bref
3745 * to determine if the search exhausted or not. Iterate if the base find
3746 * is chosen but matches a deleted chain.
3748 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3749 * held through the operation.
3751 static hammer2_chain_t *
3752 hammer2_combined_find(hammer2_chain_t *parent,
3753 hammer2_blockref_t *base, int count,
3754 int *cache_indexp, hammer2_key_t *key_nextp,
3755 hammer2_key_t key_beg, hammer2_key_t key_end,
3756 hammer2_blockref_t **bresp)
3758 hammer2_blockref_t *bref;
3759 hammer2_chain_t *chain;
3763 * Lookup in block array and in rbtree.
3765 *key_nextp = key_end + 1;
3766 i = hammer2_base_find(parent, base, count, cache_indexp,
3767 key_nextp, key_beg, key_end);
3768 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3773 if (i == count && chain == NULL) {
3779 * Only chain matched.
3782 bref = &chain->bref;
3787 * Only blockref matched.
3789 if (chain == NULL) {
3795 * Both in-memory and blockref matched, select the nearer element.
3797 * If both are flush with the left-hand side or both are the
3798 * same distance away, select the chain. In this situation the
3799 * chain must have been loaded from the matching blockmap.
3801 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3802 chain->bref.key == base[i].key) {
3803 KKASSERT(chain->bref.key == base[i].key);
3804 bref = &chain->bref;
3809 * Select the nearer key
3811 if (chain->bref.key < base[i].key) {
3812 bref = &chain->bref;
3819 * If the bref is out of bounds we've exhausted our search.
3822 if (bref->key > key_end) {
3832 * Locate the specified block array element and delete it. The element
3835 * The spin lock on the related chain must be held.
3837 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3838 * need to be adjusted when we commit the media change.
3841 hammer2_base_delete(hammer2_chain_t *parent,
3842 hammer2_blockref_t *base, int count,
3843 int *cache_indexp, hammer2_chain_t *chain)
3845 hammer2_blockref_t *elm = &chain->bref;
3846 hammer2_key_t key_next;
3850 * Delete element. Expect the element to exist.
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);
3858 if (i == count || base[i].type == 0 ||
3859 base[i].key != elm->key ||
3860 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3861 base[i].keybits != elm->keybits)) {
3862 hammer2_spin_unex(&parent->core.spin);
3863 panic("delete base %p element not found at %d/%d elm %p\n",
3864 base, i, count, elm);
3869 * Update stats and zero the entry
3871 parent->bref.data_count -= base[i].data_count;
3872 parent->bref.data_count -= (hammer2_off_t)1 <<
3873 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3874 parent->bref.inode_count -= base[i].inode_count;
3875 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3876 parent->bref.inode_count -= 1;
3878 bzero(&base[i], sizeof(*base));
3881 * We can only optimize parent->core.live_zero for live chains.
3883 if (parent->core.live_zero == i + 1) {
3884 while (--i >= 0 && base[i].type == 0)
3886 parent->core.live_zero = i + 1;
3890 * Clear appropriate blockmap flags in chain.
3892 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3893 HAMMER2_CHAIN_BMAPUPD);
3897 * Insert the specified element. The block array must not already have the
3898 * element and must have space available for the insertion.
3900 * The spin lock on the related chain must be held.
3902 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3903 * need to be adjusted when we commit the media change.
3906 hammer2_base_insert(hammer2_chain_t *parent,
3907 hammer2_blockref_t *base, int count,
3908 int *cache_indexp, hammer2_chain_t *chain)
3910 hammer2_blockref_t *elm = &chain->bref;
3911 hammer2_key_t key_next;
3920 * Insert new element. Expect the element to not already exist
3921 * unless we are replacing it.
3923 * XXX see caller, flush code not yet sophisticated enough to prevent
3924 * re-flushed in some cases.
3926 key_next = 0; /* max range */
3927 i = hammer2_base_find(parent, base, count, cache_indexp,
3928 &key_next, elm->key, elm->key);
3931 * Shortcut fill optimization, typical ordered insertion(s) may not
3934 KKASSERT(i >= 0 && i <= count);
3937 * Set appropriate blockmap flags in chain.
3939 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3942 * Update stats and zero the entry
3944 parent->bref.data_count += elm->data_count;
3945 parent->bref.data_count += (hammer2_off_t)1 <<
3946 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3947 parent->bref.inode_count += elm->inode_count;
3948 if (elm->type == HAMMER2_BREF_TYPE_INODE)
3949 parent->bref.inode_count += 1;
3953 * We can only optimize parent->core.live_zero for live chains.
3955 if (i == count && parent->core.live_zero < count) {
3956 i = parent->core.live_zero++;
3961 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3962 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3963 hammer2_spin_unex(&parent->core.spin);
3964 panic("insert base %p overlapping elements at %d elm %p\n",
3969 * Try to find an empty slot before or after.
3973 while (j > 0 || k < count) {
3975 if (j >= 0 && base[j].type == 0) {
3979 bcopy(&base[j+1], &base[j],
3980 (i - j - 1) * sizeof(*base));
3986 if (k < count && base[k].type == 0) {
3987 bcopy(&base[i], &base[i+1],
3988 (k - i) * sizeof(hammer2_blockref_t));
3992 * We can only update parent->core.live_zero for live
3995 if (parent->core.live_zero <= k)
3996 parent->core.live_zero = k + 1;
4001 panic("hammer2_base_insert: no room!");
4008 for (l = 0; l < count; ++l) {
4010 key_next = base[l].key +
4011 ((hammer2_key_t)1 << base[l].keybits) - 1;
4015 while (++l < count) {
4017 if (base[l].key <= key_next)
4018 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4019 key_next = base[l].key +
4020 ((hammer2_key_t)1 << base[l].keybits) - 1;
4030 * Sort the blockref array for the chain. Used by the flush code to
4031 * sort the blockref[] array.
4033 * The chain must be exclusively locked AND spin-locked.
4035 typedef hammer2_blockref_t *hammer2_blockref_p;
4039 hammer2_base_sort_callback(const void *v1, const void *v2)
4041 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4042 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4045 * Make sure empty elements are placed at the end of the array
4047 if (bref1->type == 0) {
4048 if (bref2->type == 0)
4051 } else if (bref2->type == 0) {
4058 if (bref1->key < bref2->key)
4060 if (bref1->key > bref2->key)
4066 hammer2_base_sort(hammer2_chain_t *chain)
4068 hammer2_blockref_t *base;
4071 switch(chain->bref.type) {
4072 case HAMMER2_BREF_TYPE_INODE:
4074 * Special shortcut for embedded data returns the inode
4075 * itself. Callers must detect this condition and access
4076 * the embedded data (the strategy code does this for us).
4078 * This is only applicable to regular files and softlinks.
4080 if (chain->data->ipdata.meta.op_flags &
4081 HAMMER2_OPFLAG_DIRECTDATA) {
4084 base = &chain->data->ipdata.u.blockset.blockref[0];
4085 count = HAMMER2_SET_COUNT;
4087 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4088 case HAMMER2_BREF_TYPE_INDIRECT:
4090 * Optimize indirect blocks in the INITIAL state to avoid
4093 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4094 base = &chain->data->npdata[0];
4095 count = chain->bytes / sizeof(hammer2_blockref_t);
4097 case HAMMER2_BREF_TYPE_VOLUME:
4098 base = &chain->data->voldata.sroot_blockset.blockref[0];
4099 count = HAMMER2_SET_COUNT;
4101 case HAMMER2_BREF_TYPE_FREEMAP:
4102 base = &chain->data->blkset.blockref[0];
4103 count = HAMMER2_SET_COUNT;
4106 kprintf("hammer2_chain_lookup: unrecognized "
4107 "blockref(A) type: %d",
4110 tsleep(&base, 0, "dead", 0);
4111 panic("hammer2_chain_lookup: unrecognized "
4112 "blockref(A) type: %d",
4114 base = NULL; /* safety */
4115 count = 0; /* safety */
4117 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4123 * Chain memory management
4126 hammer2_chain_wait(hammer2_chain_t *chain)
4128 tsleep(chain, 0, "chnflw", 1);
4131 const hammer2_media_data_t *
4132 hammer2_chain_rdata(hammer2_chain_t *chain)
4134 KKASSERT(chain->data != NULL);
4135 return (chain->data);
4138 hammer2_media_data_t *
4139 hammer2_chain_wdata(hammer2_chain_t *chain)
4141 KKASSERT(chain->data != NULL);
4142 return (chain->data);
4146 * Set the check data for a chain. This can be a heavy-weight operation
4147 * and typically only runs on-flush. For file data check data is calculated
4148 * when the logical buffers are flushed.
4151 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4153 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4155 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4156 case HAMMER2_CHECK_NONE:
4158 case HAMMER2_CHECK_DISABLED:
4160 case HAMMER2_CHECK_ISCSI32:
4161 chain->bref.check.iscsi32.value =
4162 hammer2_icrc32(bdata, chain->bytes);
4164 case HAMMER2_CHECK_CRC64:
4165 chain->bref.check.crc64.value = 0;
4168 case HAMMER2_CHECK_SHA192:
4170 SHA256_CTX hash_ctx;
4172 uint8_t digest[SHA256_DIGEST_LENGTH];
4173 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4176 SHA256_Init(&hash_ctx);
4177 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4178 SHA256_Final(u.digest, &hash_ctx);
4179 u.digest64[2] ^= u.digest64[3];
4181 chain->bref.check.sha192.data,
4182 sizeof(chain->bref.check.sha192.data));
4185 case HAMMER2_CHECK_FREEMAP:
4186 chain->bref.check.freemap.icrc32 =
4187 hammer2_icrc32(bdata, chain->bytes);
4190 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4191 chain->bref.methods);
4197 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4201 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4204 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4205 case HAMMER2_CHECK_NONE:
4208 case HAMMER2_CHECK_DISABLED:
4211 case HAMMER2_CHECK_ISCSI32:
4212 r = (chain->bref.check.iscsi32.value ==
4213 hammer2_icrc32(bdata, chain->bytes));
4215 case HAMMER2_CHECK_CRC64:
4216 r = (chain->bref.check.crc64.value == 0);
4219 case HAMMER2_CHECK_SHA192:
4221 SHA256_CTX hash_ctx;
4223 uint8_t digest[SHA256_DIGEST_LENGTH];
4224 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4227 SHA256_Init(&hash_ctx);
4228 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4229 SHA256_Final(u.digest, &hash_ctx);
4230 u.digest64[2] ^= u.digest64[3];
4232 chain->bref.check.sha192.data,
4233 sizeof(chain->bref.check.sha192.data)) == 0) {
4240 case HAMMER2_CHECK_FREEMAP:
4241 r = (chain->bref.check.freemap.icrc32 ==
4242 hammer2_icrc32(bdata, chain->bytes));
4244 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4245 chain->bref.check.freemap.icrc32,
4246 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4248 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4249 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4254 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4255 chain->bref.methods);
4263 * The caller presents a shared-locked (parent, chain) where the chain
4264 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4265 * structure representing the inode locked to prevent
4266 * consolidation/deconsolidation races.
4268 * The flags passed in are LOOKUP flags, not RESOLVE flags. Only
4269 * HAMMER2_LOOKUP_SHARED is supported.
4271 * We locate the hardlink in the current or a common parent directory.
4273 * If we are unable to locate the hardlink, EIO is returned and
4274 * (*chainp) is unlocked and dropped.
4277 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4278 hammer2_chain_t **parentp,
4279 hammer2_chain_t **chainp,
4282 hammer2_chain_t *parent;
4283 hammer2_chain_t *rchain;
4284 hammer2_key_t key_dummy;
4286 int cache_index = -1;
4289 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
4290 HAMMER2_RESOLVE_SHARED : 0;
4293 * Obtain the key for the hardlink from *chainp.
4296 lhc = rchain->data->ipdata.meta.inum;
4297 hammer2_chain_unlock(rchain);
4298 hammer2_chain_drop(rchain);
4304 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4306 &cache_index, flags);
4311 * Iterate parents, handle parent rename races by retrying
4317 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4322 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4325 if (parent->parent == NULL)
4327 parent = parent->parent;
4328 hammer2_chain_ref(parent);
4329 hammer2_chain_unlock(*parentp);
4330 hammer2_chain_lock(parent,
4331 HAMMER2_RESOLVE_ALWAYS |
4333 if ((*parentp)->parent == parent) {
4334 hammer2_chain_drop(*parentp);
4338 hammer2_chain_unlock(parent);
4339 hammer2_chain_drop(parent);
4340 hammer2_chain_lock(*parentp,
4341 HAMMER2_RESOLVE_ALWAYS |
4350 return (rchain ? 0 : EINVAL);
4354 * Used by the bulkscan code to snapshot the synchronized storage for
4355 * a volume, allowing it to be scanned concurrently against normal
4359 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4361 hammer2_chain_t *copy;
4363 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4364 switch(chain->bref.type) {
4365 case HAMMER2_BREF_TYPE_VOLUME:
4366 copy->data = kmalloc(sizeof(copy->data->voldata),
4369 hammer2_spin_ex(&chain->core.spin);
4370 copy->data->voldata = chain->data->voldata;
4371 hammer2_spin_unex(&chain->core.spin);
4373 case HAMMER2_BREF_TYPE_FREEMAP:
4374 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4377 hammer2_spin_ex(&chain->core.spin);
4378 copy->data->blkset = chain->data->blkset;
4379 hammer2_spin_unex(&chain->core.spin);
4388 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4390 switch(copy->bref.type) {
4391 case HAMMER2_BREF_TYPE_VOLUME:
4392 case HAMMER2_BREF_TYPE_FREEMAP:
4393 KKASSERT(copy->data);
4394 kfree(copy->data, copy->hmp->mchain);
4399 hammer2_chain_drop(copy);
4403 * Create a snapshot of the specified {parent, ochain} with the specified
4404 * label. The originating hammer2_inode must be exclusively locked for
4407 * The ioctl code has already synced the filesystem.
4410 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4414 const hammer2_inode_data_t *ripdata;
4415 hammer2_inode_data_t *wipdata;
4416 hammer2_chain_t *nchain;
4417 hammer2_inode_t *nip;
4426 kprintf("snapshot %s\n", pmp->name);
4428 name_len = strlen(pmp->name);
4429 lhc = hammer2_dirhash(pmp->name, name_len);
4434 ripdata = &chain->data->ipdata;
4436 opfs_clid = ripdata->meta.pfs_clid;
4441 * Create the snapshot directory under the super-root
4443 * Set PFS type, generate a unique filesystem id, and generate
4444 * a cluster id. Use the same clid when snapshotting a PFS root,
4445 * which theoretically allows the snapshot to be used as part of
4446 * the same cluster (perhaps as a cache).
4448 * Copy the (flushed) blockref array. Theoretically we could use
4449 * chain_duplicate() but it becomes difficult to disentangle
4450 * the shared core so for now just brute-force it.
4455 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4456 pmp->name, name_len, 0,
4458 HAMMER2_INSERT_PFSROOT, &error);
4461 hammer2_inode_modify(nip);
4462 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4463 hammer2_chain_modify(nchain, mtid, 0, 0);
4464 wipdata = &nchain->data->ipdata;
4466 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4467 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4468 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4469 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4472 * Give the snapshot its own private cluster id. As a
4473 * snapshot no further synchronization with the original
4474 * cluster will be done.
4477 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4478 nip->meta.pfs_clid = opfs_clid;
4480 kern_uuidgen(&nip->meta.pfs_clid, 1);
4482 kern_uuidgen(&nip->meta.pfs_clid, 1);
4483 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4485 /* XXX hack blockset copy */
4486 /* XXX doesn't work with real cluster */
4487 wipdata->meta = nip->meta;
4488 wipdata->u.blockset = ripdata->u.blockset;
4489 hammer2_flush(nchain, 1);
4490 hammer2_chain_unlock(nchain);
4491 hammer2_chain_drop(nchain);
4492 hammer2_inode_unlock(nip);