2 * Copyright (c) 2011-2019 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 hammer2_chain_t *hammer2_chain_create_indirect(
68 hammer2_chain_t *parent,
69 hammer2_key_t key, int keybits,
70 hammer2_tid_t mtid, int for_type, int *errorp);
71 static void hammer2_chain_rename_obref(hammer2_chain_t **parentp,
72 hammer2_chain_t *chain, hammer2_tid_t mtid,
73 int flags, hammer2_blockref_t *obref);
74 static int hammer2_chain_delete_obref(hammer2_chain_t *parent,
75 hammer2_chain_t *chain,
76 hammer2_tid_t mtid, int flags,
77 hammer2_blockref_t *obref);
78 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain);
79 static hammer2_chain_t *hammer2_combined_find(
80 hammer2_chain_t *parent,
81 hammer2_blockref_t *base, int count,
82 hammer2_key_t *key_nextp,
83 hammer2_key_t key_beg, hammer2_key_t key_end,
84 hammer2_blockref_t **bresp);
87 * There are many degenerate situations where an extreme rate of console
88 * output can occur from warnings and errors. Make sure this output does
89 * not impede operations.
91 static struct krate krate_h2chk = { .freq = 5 };
92 static struct krate krate_h2me = { .freq = 1 };
93 static struct krate krate_h2em = { .freq = 1 };
96 * Basic RBTree for chains (core.rbtree).
98 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
101 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
103 hammer2_key_t c1_beg;
104 hammer2_key_t c1_end;
105 hammer2_key_t c2_beg;
106 hammer2_key_t c2_end;
109 * Compare chains. Overlaps are not supposed to happen and catch
110 * any software issues early we count overlaps as a match.
112 c1_beg = chain1->bref.key;
113 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
114 c2_beg = chain2->bref.key;
115 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
117 if (c1_end < c2_beg) /* fully to the left */
119 if (c1_beg > c2_end) /* fully to the right */
121 return(0); /* overlap (must not cross edge boundary) */
125 * Assert that a chain has no media data associated with it.
128 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
130 KKASSERT(chain->dio == NULL);
131 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
132 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
134 panic("hammer2_chain_assert_no_data: chain %p still has data",
140 * Make a chain visible to the flusher. The flusher operates using a top-down
141 * recursion based on the ONFLUSH flag. It locates MODIFIED and UPDATE chains,
142 * flushes them, and updates blocks back to the volume root.
144 * This routine sets the ONFLUSH flag upward from the triggering chain until
145 * it hits an inode root or the volume root. Inode chains serve as inflection
146 * points, requiring the flusher to bridge across trees. Inodes include
147 * regular inodes, PFS roots (pmp->iroot), and the media super root
151 hammer2_chain_setflush(hammer2_chain_t *chain)
153 hammer2_chain_t *parent;
155 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
156 hammer2_spin_sh(&chain->core.spin);
157 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
158 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
159 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
161 if ((parent = chain->parent) == NULL)
163 hammer2_spin_sh(&parent->core.spin);
164 hammer2_spin_unsh(&chain->core.spin);
167 hammer2_spin_unsh(&chain->core.spin);
172 * Allocate a new disconnected chain element representing the specified
173 * bref. chain->refs is set to 1 and the passed bref is copied to
174 * chain->bref. chain->bytes is derived from the bref.
176 * chain->pmp inherits pmp unless the chain is an inode (other than the
179 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
182 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
183 hammer2_blockref_t *bref)
185 hammer2_chain_t *chain;
189 * Special case - radix of 0 indicates a chain that does not
190 * need a data reference (context is completely embedded in the
193 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
194 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
198 atomic_add_long(&hammer2_chain_allocs, 1);
201 * Construct the appropriate system structure.
204 case HAMMER2_BREF_TYPE_DIRENT:
205 case HAMMER2_BREF_TYPE_INODE:
206 case HAMMER2_BREF_TYPE_INDIRECT:
207 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
208 case HAMMER2_BREF_TYPE_DATA:
209 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
210 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
212 case HAMMER2_BREF_TYPE_VOLUME:
213 case HAMMER2_BREF_TYPE_FREEMAP:
215 * Only hammer2_chain_bulksnap() calls this function with these
218 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
222 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
227 * Initialize the new chain structure. pmp must be set to NULL for
228 * chains belonging to the super-root topology of a device mount.
230 if (pmp == hmp->spmp)
237 chain->bytes = bytes;
239 chain->flags = HAMMER2_CHAIN_ALLOCATED;
240 lockinit(&chain->diolk, "chdio", 0, 0);
243 * Set the PFS boundary flag if this chain represents a PFS root.
245 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
246 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
247 hammer2_chain_core_init(chain);
253 * Initialize a chain's core structure. This structure used to be allocated
254 * but is now embedded.
256 * The core is not locked. No additional refs on the chain are made.
257 * (trans) must not be NULL if (core) is not NULL.
260 hammer2_chain_core_init(hammer2_chain_t *chain)
263 * Fresh core under nchain (no multi-homing of ochain's
266 RB_INIT(&chain->core.rbtree); /* live chains */
267 hammer2_mtx_init(&chain->lock, "h2chain");
271 * Add a reference to a chain element, preventing its destruction.
273 * (can be called with spinlock held)
276 hammer2_chain_ref(hammer2_chain_t *chain)
278 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
280 * Just flag that the chain was used and should be recycled
281 * on the LRU if it encounters it later.
283 if (chain->flags & HAMMER2_CHAIN_ONLRU)
284 atomic_set_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
288 * REMOVED - reduces contention, lru_list is more heuristical
291 * 0->non-zero transition must ensure that chain is removed
294 * NOTE: Already holding lru_spin here so we cannot call
295 * hammer2_chain_ref() to get it off lru_list, do
298 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
299 hammer2_pfs_t *pmp = chain->pmp;
300 hammer2_spin_ex(&pmp->lru_spin);
301 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
302 atomic_add_int(&pmp->lru_count, -1);
303 atomic_clear_int(&chain->flags,
304 HAMMER2_CHAIN_ONLRU);
305 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
307 hammer2_spin_unex(&pmp->lru_spin);
314 * Ref a locked chain and force the data to be held across an unlock.
315 * Chain must be currently locked. The user of the chain who desires
316 * to release the hold must call hammer2_chain_lock_unhold() to relock
317 * and unhold the chain, then unlock normally, or may simply call
318 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
321 hammer2_chain_ref_hold(hammer2_chain_t *chain)
323 atomic_add_int(&chain->lockcnt, 1);
324 hammer2_chain_ref(chain);
328 * Insert the chain in the core rbtree.
330 * Normal insertions are placed in the live rbtree. Insertion of a deleted
331 * chain is a special case used by the flush code that is placed on the
332 * unstaged deleted list to avoid confusing the live view.
334 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
335 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
336 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
340 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
341 int flags, int generation)
343 hammer2_chain_t *xchain;
346 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
347 hammer2_spin_ex(&parent->core.spin);
350 * Interlocked by spinlock, check for race
352 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
353 parent->core.generation != generation) {
354 error = HAMMER2_ERROR_EAGAIN;
361 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
362 KASSERT(xchain == NULL,
363 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
364 chain, xchain, chain->bref.key));
365 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
366 chain->parent = parent;
367 ++parent->core.chain_count;
368 ++parent->core.generation; /* XXX incs for _get() too, XXX */
371 * We have to keep track of the effective live-view blockref count
372 * so the create code knows when to push an indirect block.
374 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
375 atomic_add_int(&parent->core.live_count, 1);
377 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
378 hammer2_spin_unex(&parent->core.spin);
383 * Drop the caller's reference to the chain. When the ref count drops to
384 * zero this function will try to disassociate the chain from its parent and
385 * deallocate it, then recursely drop the parent using the implied ref
386 * from the chain's chain->parent.
388 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
389 * races an acquisition by another cpu. Therefore we can loop if we are
390 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
391 * race against another drop.
393 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
395 static void hammer2_chain_lru_flush(hammer2_pfs_t *pmp);
398 hammer2_chain_drop(hammer2_chain_t *chain)
402 if (hammer2_debug & 0x200000)
405 KKASSERT(chain->refs > 0);
413 if (hammer2_mtx_ex_try(&chain->lock) == 0)
414 chain = hammer2_chain_lastdrop(chain, 0);
415 /* retry the same chain, or chain from lastdrop */
417 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
419 /* retry the same chain */
426 * Unhold a held and probably not-locked chain, ensure that the data is
427 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
428 * lock and then simply unlocking the chain.
431 hammer2_chain_unhold(hammer2_chain_t *chain)
437 lockcnt = chain->lockcnt;
440 if (atomic_cmpset_int(&chain->lockcnt,
441 lockcnt, lockcnt - 1)) {
444 } else if (hammer2_mtx_ex_try(&chain->lock) == 0) {
445 hammer2_chain_unlock(chain);
449 * This situation can easily occur on SMP due to
450 * the gap inbetween the 1->0 transition and the
451 * final unlock. We cannot safely block on the
452 * mutex because lockcnt might go above 1.
454 * XXX Sleep for one tick if it takes too long.
457 if (iter > 1000 + hz) {
458 kprintf("hammer2: h2race1 %p\n", chain);
461 tsleep(&iter, 0, "h2race1", 1);
469 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
471 hammer2_chain_unhold(chain);
472 hammer2_chain_drop(chain);
476 hammer2_chain_rehold(hammer2_chain_t *chain)
478 hammer2_chain_lock(chain, HAMMER2_RESOLVE_SHARED);
479 atomic_add_int(&chain->lockcnt, 1);
480 hammer2_chain_unlock(chain);
484 * Handles the (potential) last drop of chain->refs from 1->0. Called with
485 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
486 * possible against refs and lockcnt. We must dispose of the mutex on chain.
488 * This function returns an unlocked chain for recursive drop or NULL. It
489 * can return the same chain if it determines it has raced another ref.
493 * When two chains need to be recursively dropped we use the chain we
494 * would otherwise free to placehold the additional chain. It's a bit
495 * convoluted but we can't just recurse without potentially blowing out
498 * The chain cannot be freed if it has any children.
499 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
500 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
501 * Any dedup registration can remain intact.
503 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
507 hammer2_chain_lastdrop(hammer2_chain_t *chain, int depth)
511 hammer2_chain_t *parent;
512 hammer2_chain_t *rdrop;
515 * We need chain's spinlock to interlock the sub-tree test.
516 * We already have chain's mutex, protecting chain->parent.
518 * Remember that chain->refs can be in flux.
520 hammer2_spin_ex(&chain->core.spin);
522 if (chain->parent != NULL) {
524 * If the chain has a parent the UPDATE bit prevents scrapping
525 * as the chain is needed to properly flush the parent. Try
526 * to complete the 1->0 transition and return NULL. Retry
527 * (return chain) if we are unable to complete the 1->0
528 * transition, else return NULL (nothing more to do).
530 * If the chain has a parent the MODIFIED bit prevents
533 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
535 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
536 HAMMER2_CHAIN_MODIFIED)) {
537 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
538 hammer2_spin_unex(&chain->core.spin);
539 hammer2_chain_assert_no_data(chain);
540 hammer2_mtx_unlock(&chain->lock);
543 hammer2_spin_unex(&chain->core.spin);
544 hammer2_mtx_unlock(&chain->lock);
548 /* spinlock still held */
549 } else if (chain->bref.type == HAMMER2_BREF_TYPE_VOLUME ||
550 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP) {
552 * Retain the static vchain and fchain. Clear bits that
553 * are not relevant. Do not clear the MODIFIED bit,
554 * and certainly do not put it on the delayed-flush queue.
556 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
559 * The chain has no parent and can be flagged for destruction.
560 * Since it has no parent, UPDATE can also be cleared.
562 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
563 if (chain->flags & HAMMER2_CHAIN_UPDATE)
564 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
567 * If the chain has children we must propagate the DESTROY
568 * flag downward and rip the disconnected topology apart.
569 * This is accomplished by calling hammer2_flush() on the
572 * Any dedup is already handled by the underlying DIO, so
573 * we do not have to specifically flush it here.
575 if (chain->core.chain_count) {
576 hammer2_spin_unex(&chain->core.spin);
577 hammer2_flush(chain, HAMMER2_FLUSH_TOP |
579 hammer2_mtx_unlock(&chain->lock);
581 return(chain); /* retry drop */
585 * Otherwise we can scrap the MODIFIED bit if it is set,
586 * and continue along the freeing path.
588 * Be sure to clean-out any dedup bits. Without a parent
589 * this chain will no longer be visible to the flush code.
590 * Easy check data_off to avoid the volume root.
592 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
593 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
594 atomic_add_long(&hammer2_count_modified_chains, -1);
596 hammer2_pfs_memory_wakeup(chain->pmp);
598 /* spinlock still held */
601 /* spinlock still held */
604 * If any children exist we must leave the chain intact with refs == 0.
605 * They exist because chains are retained below us which have refs or
606 * may require flushing.
608 * Retry (return chain) if we fail to transition the refs to 0, else
609 * return NULL indication nothing more to do.
611 * Chains with children are NOT put on the LRU list.
613 if (chain->core.chain_count) {
614 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
615 hammer2_spin_unex(&chain->core.spin);
616 hammer2_chain_assert_no_data(chain);
617 hammer2_mtx_unlock(&chain->lock);
620 hammer2_spin_unex(&chain->core.spin);
621 hammer2_mtx_unlock(&chain->lock);
625 /* spinlock still held */
626 /* no chains left under us */
629 * chain->core has no children left so no accessors can get to our
630 * chain from there. Now we have to lock the parent core to interlock
631 * remaining possible accessors that might bump chain's refs before
632 * we can safely drop chain's refs with intent to free the chain.
635 pmp = chain->pmp; /* can be NULL */
638 parent = chain->parent;
641 * WARNING! chain's spin lock is still held here, and other spinlocks
642 * will be acquired and released in the code below. We
643 * cannot be making fancy procedure calls!
647 * We can cache the chain if it is associated with a pmp
648 * and not flagged as being destroyed or requesting a full
649 * release. In this situation the chain is not removed
650 * from its parent, i.e. it can still be looked up.
652 * We intentionally do not cache DATA chains because these
653 * were likely used to load data into the logical buffer cache
654 * and will not be accessed again for some time.
657 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
659 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
661 hammer2_spin_ex(&parent->core.spin);
662 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
664 * 1->0 transition failed, retry. Do not drop
665 * the chain's data yet!
668 hammer2_spin_unex(&parent->core.spin);
669 hammer2_spin_unex(&chain->core.spin);
670 hammer2_mtx_unlock(&chain->lock);
678 hammer2_chain_assert_no_data(chain);
681 * Make sure we are on the LRU list, clean up excessive
682 * LRU entries. We can only really drop one but there might
683 * be other entries that we can remove from the lru_list
686 * NOTE: HAMMER2_CHAIN_ONLRU may only be safely set when
687 * chain->core.spin AND pmp->lru_spin are held, but
688 * can be safely cleared only holding pmp->lru_spin.
690 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
691 hammer2_spin_ex(&pmp->lru_spin);
692 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
693 atomic_set_int(&chain->flags,
694 HAMMER2_CHAIN_ONLRU);
695 TAILQ_INSERT_TAIL(&pmp->lru_list,
697 atomic_add_int(&pmp->lru_count, 1);
699 if (pmp->lru_count < HAMMER2_LRU_LIMIT)
700 depth = 1; /* disable lru_list flush */
701 hammer2_spin_unex(&pmp->lru_spin);
703 /* disable lru flush */
708 hammer2_spin_unex(&parent->core.spin);
709 parent = NULL; /* safety */
711 hammer2_spin_unex(&chain->core.spin);
712 hammer2_mtx_unlock(&chain->lock);
715 * lru_list hysteresis (see above for depth overrides).
716 * Note that depth also prevents excessive lastdrop recursion.
719 hammer2_chain_lru_flush(pmp);
726 * Make sure we are not on the LRU list.
728 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
729 hammer2_spin_ex(&pmp->lru_spin);
730 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
731 atomic_add_int(&pmp->lru_count, -1);
732 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
733 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
735 hammer2_spin_unex(&pmp->lru_spin);
739 * Spinlock the parent and try to drop the last ref on chain.
740 * On success determine if we should dispose of the chain
741 * (remove the chain from its parent, etc).
743 * (normal core locks are top-down recursive but we define
744 * core spinlocks as bottom-up recursive, so this is safe).
747 hammer2_spin_ex(&parent->core.spin);
748 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
750 * 1->0 transition failed, retry.
752 hammer2_spin_unex(&parent->core.spin);
753 hammer2_spin_unex(&chain->core.spin);
754 hammer2_mtx_unlock(&chain->lock);
760 * 1->0 transition successful, parent spin held to prevent
761 * new lookups, chain spinlock held to protect parent field.
762 * Remove chain from the parent.
764 * If the chain is being removed from the parent's btree but
765 * is not bmapped, we have to adjust live_count downward. If
766 * it is bmapped then the blockref is retained in the parent
767 * as is its associated live_count. This case can occur when
768 * a chain added to the topology is unable to flush and is
769 * then later deleted.
771 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
772 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
773 (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
774 atomic_add_int(&parent->core.live_count, -1);
776 RB_REMOVE(hammer2_chain_tree,
777 &parent->core.rbtree, chain);
778 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
779 --parent->core.chain_count;
780 chain->parent = NULL;
784 * If our chain was the last chain in the parent's core the
785 * core is now empty and its parent might have to be
786 * re-dropped if it has 0 refs.
788 if (parent->core.chain_count == 0) {
790 atomic_add_int(&rdrop->refs, 1);
792 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
796 hammer2_spin_unex(&parent->core.spin);
797 parent = NULL; /* safety */
803 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
805 * 1->0 transition failed, retry.
807 hammer2_spin_unex(&parent->core.spin);
808 hammer2_spin_unex(&chain->core.spin);
809 hammer2_mtx_unlock(&chain->lock);
816 * Successful 1->0 transition, no parent, no children... no way for
817 * anyone to ref this chain any more. We can clean-up and free it.
819 * We still have the core spinlock, and core's chain_count is 0.
820 * Any parent spinlock is gone.
822 hammer2_spin_unex(&chain->core.spin);
823 hammer2_chain_assert_no_data(chain);
824 hammer2_mtx_unlock(&chain->lock);
825 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
826 chain->core.chain_count == 0);
829 * All locks are gone, no pointers remain to the chain, finish
832 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
833 HAMMER2_CHAIN_MODIFIED)) == 0);
836 * Once chain resources are gone we can use the now dead chain
837 * structure to placehold what might otherwise require a recursive
838 * drop, because we have potentially two things to drop and can only
839 * return one directly.
841 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
842 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
844 kfree(chain, hmp->mchain);
848 * Possible chaining loop when parent re-drop needed.
854 * Heuristical flush of the LRU, try to reduce the number of entries
855 * on the LRU to (HAMMER2_LRU_LIMIT * 2 / 3). This procedure is called
856 * only when lru_count exceeds HAMMER2_LRU_LIMIT.
860 hammer2_chain_lru_flush(hammer2_pfs_t *pmp)
862 hammer2_chain_t *chain;
866 hammer2_spin_ex(&pmp->lru_spin);
867 while (pmp->lru_count > HAMMER2_LRU_LIMIT * 2 / 3) {
869 * Pick a chain off the lru_list, just recycle it quickly
870 * if LRUHINT is set (the chain was ref'd but left on
871 * the lru_list, so cycle to the end).
873 chain = TAILQ_FIRST(&pmp->lru_list);
874 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
876 if (chain->flags & HAMMER2_CHAIN_LRUHINT) {
877 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
878 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
884 * Ok, we are off the LRU. We must adjust refs before we
885 * can safely clear the ONLRU flag.
887 atomic_add_int(&pmp->lru_count, -1);
888 if (atomic_cmpset_int(&chain->refs, 0, 1)) {
889 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
890 atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
893 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
896 hammer2_spin_unex(&pmp->lru_spin);
901 * If we picked a chain off the lru list we may be able to lastdrop
902 * it. Use a depth of 1 to prevent excessive lastdrop recursion.
912 if (hammer2_mtx_ex_try(&chain->lock) == 0)
913 chain = hammer2_chain_lastdrop(chain, 1);
914 /* retry the same chain, or chain from lastdrop */
916 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
918 /* retry the same chain */
926 * On last lock release.
928 static hammer2_io_t *
929 hammer2_chain_drop_data(hammer2_chain_t *chain)
933 if ((dio = chain->dio) != NULL) {
937 switch(chain->bref.type) {
938 case HAMMER2_BREF_TYPE_VOLUME:
939 case HAMMER2_BREF_TYPE_FREEMAP:
942 if (chain->data != NULL) {
943 hammer2_spin_unex(&chain->core.spin);
944 panic("chain data not null: "
945 "chain %p bref %016jx.%02x "
946 "refs %d parent %p dio %p data %p",
947 chain, chain->bref.data_off,
948 chain->bref.type, chain->refs,
950 chain->dio, chain->data);
952 KKASSERT(chain->data == NULL);
960 * Lock a referenced chain element, acquiring its data with I/O if necessary,
961 * and specify how you would like the data to be resolved.
963 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
965 * The lock is allowed to recurse, multiple locking ops will aggregate
966 * the requested resolve types. Once data is assigned it will not be
967 * removed until the last unlock.
969 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
970 * (typically used to avoid device/logical buffer
973 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
974 * the INITIAL-create state (indirect blocks only).
976 * Do not resolve data elements for DATA chains.
977 * (typically used to avoid device/logical buffer
980 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
982 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
983 * it will be locked exclusive.
985 * HAMMER2_RESOLVE_NONBLOCK- (flag) The chain is locked non-blocking. If
986 * the lock fails, EAGAIN is returned.
988 * NOTE: Embedded elements (volume header, inodes) are always resolved
991 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
992 * element will instantiate and zero its buffer, and flush it on
995 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
996 * so as not to instantiate a device buffer, which could alias against
997 * a logical file buffer. However, if ALWAYS is specified the
998 * device buffer will be instantiated anyway.
1000 * NOTE: The return value is always 0 unless NONBLOCK is specified, in which
1001 * case it can be either 0 or EAGAIN.
1003 * WARNING! This function blocks on I/O if data needs to be fetched. This
1004 * blocking can run concurrent with other compatible lock holders
1005 * who do not need data returning. The lock is not upgraded to
1006 * exclusive during a data fetch, a separate bit is used to
1007 * interlock I/O. However, an exclusive lock holder can still count
1008 * on being interlocked against an I/O fetch managed by a shared
1012 hammer2_chain_lock(hammer2_chain_t *chain, int how)
1014 KKASSERT(chain->refs > 0);
1016 if (how & HAMMER2_RESOLVE_NONBLOCK) {
1018 * We still have to bump lockcnt before acquiring the lock,
1019 * even for non-blocking operation, because the unlock code
1020 * live-loops on lockcnt == 1 when dropping the last lock.
1022 * If the non-blocking operation fails we have to use an
1023 * unhold sequence to undo the mess.
1025 * NOTE: LOCKAGAIN must always succeed without blocking,
1026 * even if NONBLOCK is specified.
1028 atomic_add_int(&chain->lockcnt, 1);
1029 if (how & HAMMER2_RESOLVE_SHARED) {
1030 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1031 hammer2_mtx_sh_again(&chain->lock);
1033 if (hammer2_mtx_sh_try(&chain->lock) != 0) {
1034 hammer2_chain_unhold(chain);
1039 if (hammer2_mtx_ex_try(&chain->lock) != 0) {
1040 hammer2_chain_unhold(chain);
1046 * Get the appropriate lock. If LOCKAGAIN is flagged with
1047 * SHARED the caller expects a shared lock to already be
1048 * present and we are giving it another ref. This case must
1049 * importantly not block if there is a pending exclusive lock
1052 atomic_add_int(&chain->lockcnt, 1);
1053 if (how & HAMMER2_RESOLVE_SHARED) {
1054 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1055 hammer2_mtx_sh_again(&chain->lock);
1057 hammer2_mtx_sh(&chain->lock);
1060 hammer2_mtx_ex(&chain->lock);
1065 * If we already have a valid data pointer make sure the data is
1066 * synchronized to the current cpu, and then no further action is
1071 hammer2_io_bkvasync(chain->dio);
1076 * Do we have to resolve the data? This is generally only
1077 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
1078 * Other BREF types expects the data to be there.
1080 switch(how & HAMMER2_RESOLVE_MASK) {
1081 case HAMMER2_RESOLVE_NEVER:
1083 case HAMMER2_RESOLVE_MAYBE:
1084 if (chain->flags & HAMMER2_CHAIN_INITIAL)
1086 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1089 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
1091 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
1095 case HAMMER2_RESOLVE_ALWAYS:
1101 * Caller requires data
1103 hammer2_chain_load_data(chain);
1109 * Lock the chain, retain the hold, and drop the data persistence count.
1110 * The data should remain valid because we never transitioned lockcnt
1114 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
1116 hammer2_chain_lock(chain, how);
1117 atomic_add_int(&chain->lockcnt, -1);
1122 * Downgrade an exclusive chain lock to a shared chain lock.
1124 * NOTE: There is no upgrade equivalent due to the ease of
1125 * deadlocks in that direction.
1128 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1130 hammer2_mtx_downgrade(&chain->lock);
1135 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1136 * may be of any type.
1138 * Once chain->data is set it cannot be disposed of until all locks are
1141 * Make sure the data is synchronized to the current cpu.
1144 hammer2_chain_load_data(hammer2_chain_t *chain)
1146 hammer2_blockref_t *bref;
1153 * Degenerate case, data already present, or chain has no media
1154 * reference to load.
1156 KKASSERT(chain->lock.mtx_lock & MTX_MASK);
1159 hammer2_io_bkvasync(chain->dio);
1162 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1166 KKASSERT(hmp != NULL);
1169 * Gain the IOINPROG bit, interlocked block.
1175 oflags = chain->flags;
1177 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1178 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1179 tsleep_interlock(&chain->flags, 0);
1180 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1181 tsleep(&chain->flags, PINTERLOCKED,
1186 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1187 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1195 * We own CHAIN_IOINPROG
1197 * Degenerate case if we raced another load.
1201 hammer2_io_bkvasync(chain->dio);
1206 * We must resolve to a device buffer, either by issuing I/O or
1207 * by creating a zero-fill element. We do not mark the buffer
1208 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1209 * API must still be used to do that).
1211 * The device buffer is variable-sized in powers of 2 down
1212 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1213 * chunk always contains buffers of the same size. (XXX)
1215 * The minimum physical IO size may be larger than the variable
1218 bref = &chain->bref;
1221 * The getblk() optimization can only be used on newly created
1222 * elements if the physical block size matches the request.
1224 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1225 error = hammer2_io_new(hmp, bref->type,
1226 bref->data_off, chain->bytes,
1229 error = hammer2_io_bread(hmp, bref->type,
1230 bref->data_off, chain->bytes,
1232 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1235 chain->error = HAMMER2_ERROR_EIO;
1236 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1237 (intmax_t)bref->data_off, error);
1238 hammer2_io_bqrelse(&chain->dio);
1244 * This isn't perfect and can be ignored on OSs which do not have
1245 * an indication as to whether a buffer is coming from cache or
1246 * if I/O was actually issued for the read. TESTEDGOOD will work
1247 * pretty well without the B_IOISSUED logic because chains are
1248 * cached, but in that situation (without B_IOISSUED) it will not
1249 * detect whether a re-read via I/O is corrupted verses the original
1252 * We can't re-run the CRC on every fresh lock. That would be
1253 * insanely expensive.
1255 * If the underlying kernel buffer covers the entire chain we can
1256 * use the B_IOISSUED indication to determine if we have to re-run
1257 * the CRC on chain data for chains that managed to stay cached
1258 * across the kernel disposal of the original buffer.
1260 if ((dio = chain->dio) != NULL && dio->bp) {
1261 struct buf *bp = dio->bp;
1263 if (dio->psize == chain->bytes &&
1264 (bp->b_flags & B_IOISSUED)) {
1265 atomic_clear_int(&chain->flags,
1266 HAMMER2_CHAIN_TESTEDGOOD);
1267 bp->b_flags &= ~B_IOISSUED;
1272 * NOTE: A locked chain's data cannot be modified without first
1273 * calling hammer2_chain_modify().
1277 * Clear INITIAL. In this case we used io_new() and the buffer has
1278 * been zero'd and marked dirty.
1280 * NOTE: hammer2_io_data() call issues bkvasync()
1282 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1284 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1285 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1286 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1287 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1289 * check data not currently synchronized due to
1290 * modification. XXX assumes data stays in the buffer
1291 * cache, which might not be true (need biodep on flush
1292 * to calculate crc? or simple crc?).
1294 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1295 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1296 chain->error = HAMMER2_ERROR_CHECK;
1298 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1303 * Setup the data pointer, either pointing it to an embedded data
1304 * structure and copying the data from the buffer, or pointing it
1307 * The buffer is not retained when copying to an embedded data
1308 * structure in order to avoid potential deadlocks or recursions
1309 * on the same physical buffer.
1311 * WARNING! Other threads can start using the data the instant we
1312 * set chain->data non-NULL.
1314 switch (bref->type) {
1315 case HAMMER2_BREF_TYPE_VOLUME:
1316 case HAMMER2_BREF_TYPE_FREEMAP:
1318 * Copy data from bp to embedded buffer
1320 panic("hammer2_chain_load_data: unresolved volume header");
1322 case HAMMER2_BREF_TYPE_DIRENT:
1323 KKASSERT(chain->bytes != 0);
1325 case HAMMER2_BREF_TYPE_INODE:
1326 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1327 case HAMMER2_BREF_TYPE_INDIRECT:
1328 case HAMMER2_BREF_TYPE_DATA:
1329 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1332 * Point data at the device buffer and leave dio intact.
1334 chain->data = (void *)bdata;
1339 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1346 oflags = chain->flags;
1347 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1348 HAMMER2_CHAIN_IOSIGNAL);
1349 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1350 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1351 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1352 wakeup(&chain->flags);
1359 * Unlock and deref a chain element.
1361 * Remember that the presence of children under chain prevent the chain's
1362 * destruction but do not add additional references, so the dio will still
1366 hammer2_chain_unlock(hammer2_chain_t *chain)
1373 * If multiple locks are present (or being attempted) on this
1374 * particular chain we can just unlock, drop refs, and return.
1376 * Otherwise fall-through on the 1->0 transition.
1379 lockcnt = chain->lockcnt;
1380 KKASSERT(lockcnt > 0);
1383 if (atomic_cmpset_int(&chain->lockcnt,
1384 lockcnt, lockcnt - 1)) {
1385 hammer2_mtx_unlock(&chain->lock);
1388 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1389 /* while holding the mutex exclusively */
1390 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1394 * This situation can easily occur on SMP due to
1395 * the gap inbetween the 1->0 transition and the
1396 * final unlock. We cannot safely block on the
1397 * mutex because lockcnt might go above 1.
1399 * XXX Sleep for one tick if it takes too long.
1401 if (++iter > 1000) {
1402 if (iter > 1000 + hz) {
1403 kprintf("hammer2: h2race2 %p\n", chain);
1406 tsleep(&iter, 0, "h2race2", 1);
1414 * Last unlock / mutex upgraded to exclusive. Drop the data
1417 dio = hammer2_chain_drop_data(chain);
1419 hammer2_io_bqrelse(&dio);
1420 hammer2_mtx_unlock(&chain->lock);
1424 * Unlock and hold chain data intact
1427 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1429 atomic_add_int(&chain->lockcnt, 1);
1430 hammer2_chain_unlock(chain);
1434 * Helper to obtain the blockref[] array base and count for a chain.
1436 * XXX Not widely used yet, various use cases need to be validated and
1437 * converted to use this function.
1440 hammer2_blockref_t *
1441 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1443 hammer2_blockref_t *base;
1446 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1449 switch(parent->bref.type) {
1450 case HAMMER2_BREF_TYPE_INODE:
1451 count = HAMMER2_SET_COUNT;
1453 case HAMMER2_BREF_TYPE_INDIRECT:
1454 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1455 count = parent->bytes / sizeof(hammer2_blockref_t);
1457 case HAMMER2_BREF_TYPE_VOLUME:
1458 count = HAMMER2_SET_COUNT;
1460 case HAMMER2_BREF_TYPE_FREEMAP:
1461 count = HAMMER2_SET_COUNT;
1464 panic("hammer2_chain_base_and_count: "
1465 "unrecognized blockref type: %d",
1471 switch(parent->bref.type) {
1472 case HAMMER2_BREF_TYPE_INODE:
1473 base = &parent->data->ipdata.u.blockset.blockref[0];
1474 count = HAMMER2_SET_COUNT;
1476 case HAMMER2_BREF_TYPE_INDIRECT:
1477 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1478 base = &parent->data->npdata[0];
1479 count = parent->bytes / sizeof(hammer2_blockref_t);
1481 case HAMMER2_BREF_TYPE_VOLUME:
1482 base = &parent->data->voldata.
1483 sroot_blockset.blockref[0];
1484 count = HAMMER2_SET_COUNT;
1486 case HAMMER2_BREF_TYPE_FREEMAP:
1487 base = &parent->data->blkset.blockref[0];
1488 count = HAMMER2_SET_COUNT;
1491 panic("hammer2_chain_base_and_count: "
1492 "unrecognized blockref type: %d",
1504 * This counts the number of live blockrefs in a block array and
1505 * also calculates the point at which all remaining blockrefs are empty.
1506 * This routine can only be called on a live chain.
1508 * Caller holds the chain locked, but possibly with a shared lock. We
1509 * must use an exclusive spinlock to prevent corruption.
1511 * NOTE: Flag is not set until after the count is complete, allowing
1512 * callers to test the flag without holding the spinlock.
1514 * NOTE: If base is NULL the related chain is still in the INITIAL
1515 * state and there are no blockrefs to count.
1517 * NOTE: live_count may already have some counts accumulated due to
1518 * creation and deletion and could even be initially negative.
1521 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1522 hammer2_blockref_t *base, int count)
1524 hammer2_spin_ex(&chain->core.spin);
1525 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1527 while (--count >= 0) {
1528 if (base[count].type != HAMMER2_BREF_TYPE_EMPTY)
1531 chain->core.live_zero = count + 1;
1532 while (count >= 0) {
1533 if (base[count].type != HAMMER2_BREF_TYPE_EMPTY)
1534 atomic_add_int(&chain->core.live_count,
1539 chain->core.live_zero = 0;
1541 /* else do not modify live_count */
1542 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1544 hammer2_spin_unex(&chain->core.spin);
1548 * Resize the chain's physical storage allocation in-place. This function does
1549 * not usually adjust the data pointer and must be followed by (typically) a
1550 * hammer2_chain_modify() call to copy any old data over and adjust the
1553 * Chains can be resized smaller without reallocating the storage. Resizing
1554 * larger will reallocate the storage. Excess or prior storage is reclaimed
1555 * asynchronously at a later time.
1557 * An nradix value of 0 is special-cased to mean that the storage should
1558 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1561 * Must be passed an exclusively locked parent and chain.
1563 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1564 * to avoid instantiating a device buffer that conflicts with the vnode data
1565 * buffer. However, because H2 can compress or encrypt data, the chain may
1566 * have a dio assigned to it in those situations, and they do not conflict.
1568 * XXX return error if cannot resize.
1571 hammer2_chain_resize(hammer2_chain_t *chain,
1572 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1573 int nradix, int flags)
1583 * Only data and indirect blocks can be resized for now.
1584 * (The volu root, inodes, and freemap elements use a fixed size).
1586 KKASSERT(chain != &hmp->vchain);
1587 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1588 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1589 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1592 * Nothing to do if the element is already the proper size
1594 obytes = chain->bytes;
1595 nbytes = (nradix) ? (1U << nradix) : 0;
1596 if (obytes == nbytes)
1597 return (chain->error);
1600 * Make sure the old data is instantiated so we can copy it. If this
1601 * is a data block, the device data may be superfluous since the data
1602 * might be in a logical block, but compressed or encrypted data is
1605 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1607 error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1612 * Relocate the block, even if making it smaller (because different
1613 * block sizes may be in different regions).
1615 * NOTE: Operation does not copy the data and may only be used
1616 * to resize data blocks in-place, or directory entry blocks
1617 * which are about to be modified in some manner.
1619 error = hammer2_freemap_alloc(chain, nbytes);
1623 chain->bytes = nbytes;
1626 * We don't want the followup chain_modify() to try to copy data
1627 * from the old (wrong-sized) buffer. It won't know how much to
1628 * copy. This case should only occur during writes when the
1629 * originator already has the data to write in-hand.
1632 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1633 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1634 hammer2_io_brelse(&chain->dio);
1637 return (chain->error);
1641 * Set the chain modified so its data can be changed by the caller, or
1642 * install deduplicated data. The caller must call this routine for each
1643 * set of modifications it makes, even if the chain is already flagged
1646 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1647 * is a CLC (cluster level change) field and is not updated by parent
1648 * propagation during a flush.
1650 * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1651 * chain->error except for HAMMER2_ERROR_ENOSPC. If the allocation fails
1652 * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1653 * remains unmodified with its old data ref intact and chain->error
1658 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1659 * even if the chain is still flagged MODIFIED. In this case the chain's
1660 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1662 * If the caller passes a non-zero dedup_off we will use it to assign the
1663 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1664 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1665 * must not modify the data content upon return.
1668 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1669 hammer2_off_t dedup_off, int flags)
1671 hammer2_blockref_t obref;
1682 obref = chain->bref;
1683 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1684 KKASSERT(chain->lock.mtx_lock & MTX_EXCLUSIVE);
1687 * Data is not optional for freemap chains (we must always be sure
1688 * to copy the data on COW storage allocations).
1690 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1691 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1692 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1693 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1697 * Data must be resolved if already assigned, unless explicitly
1698 * flagged otherwise. If we cannot safety load the data the
1699 * modification fails and we return early.
1701 if (chain->data == NULL && chain->bytes != 0 &&
1702 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1703 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1704 hammer2_chain_load_data(chain);
1706 return (chain->error);
1711 * Set MODIFIED to indicate that the chain has been modified. A new
1712 * allocation is required when modifying a chain.
1714 * Set UPDATE to ensure that the blockref is updated in the parent.
1716 * If MODIFIED is already set determine if we can reuse the assigned
1717 * data block or if we need a new data block.
1719 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1721 * Must set modified bit.
1723 atomic_add_long(&hammer2_count_modified_chains, 1);
1724 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1725 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1729 * We may be able to avoid a copy-on-write if the chain's
1730 * check mode is set to NONE and the chain's current
1731 * modify_tid is beyond the last explicit snapshot tid.
1733 * This implements HAMMER2's overwrite-in-place feature.
1735 * NOTE! This data-block cannot be used as a de-duplication
1736 * source when the check mode is set to NONE.
1738 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1739 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1740 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1741 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1742 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1743 HAMMER2_CHECK_NONE &&
1745 chain->bref.modify_tid >
1746 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1748 * Sector overwrite allowed.
1751 } else if ((hmp->hflags & HMNT2_EMERG) &&
1753 chain->bref.modify_tid >
1754 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1756 * If in emergency delete mode then do a modify-in-
1757 * place on any chain type belonging to the PFS as
1758 * long as it doesn't mess up a snapshot. We might
1759 * be forced to do this anyway a little further down
1760 * in the code if the allocation fails.
1762 * Also note that in emergency mode, these modify-in-
1763 * place operations are NOT SAFE. A storage failure,
1764 * power failure, or panic can corrupt the filesystem.
1769 * Sector overwrite not allowed, must copy-on-write.
1773 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1775 * If the modified chain was registered for dedup we need
1776 * a new allocation. This only happens for delayed-flush
1777 * chains (i.e. which run through the front-end buffer
1784 * Already flagged modified, no new allocation is needed.
1791 * Flag parent update required.
1793 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1794 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1801 * The XOP code returns held but unlocked focus chains. This
1802 * prevents the chain from being destroyed but does not prevent
1803 * it from being modified. diolk is used to interlock modifications
1804 * against XOP frontend accesses to the focus.
1806 * This allows us to theoretically avoid deadlocking the frontend
1807 * if one of the backends lock up by not formally locking the
1808 * focused chain in the frontend. In addition, the synchronization
1809 * code relies on this mechanism to avoid deadlocking concurrent
1810 * synchronization threads.
1812 lockmgr(&chain->diolk, LK_EXCLUSIVE);
1815 * The modification or re-modification requires an allocation and
1816 * possible COW. If an error occurs, the previous content and data
1817 * reference is retained and the modification fails.
1819 * If dedup_off is non-zero, the caller is requesting a deduplication
1820 * rather than a modification. The MODIFIED bit is not set and the
1821 * data offset is set to the deduplication offset. The data cannot
1824 * NOTE: The dedup offset is allowed to be in a partially free state
1825 * and we must be sure to reset it to a fully allocated state
1826 * to force two bulkfree passes to free it again.
1828 * NOTE: Only applicable when chain->bytes != 0.
1830 * XXX can a chain already be marked MODIFIED without a data
1831 * assignment? If not, assert here instead of testing the case.
1833 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1835 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1839 * NOTE: We do not have to remove the dedup
1840 * registration because the area is still
1841 * allocated and the underlying DIO will
1845 chain->bref.data_off = dedup_off;
1846 chain->bytes = 1 << (dedup_off &
1847 HAMMER2_OFF_MASK_RADIX);
1849 atomic_clear_int(&chain->flags,
1850 HAMMER2_CHAIN_MODIFIED);
1851 atomic_add_long(&hammer2_count_modified_chains,
1854 hammer2_pfs_memory_wakeup(chain->pmp);
1855 hammer2_freemap_adjust(hmp, &chain->bref,
1856 HAMMER2_FREEMAP_DORECOVER);
1857 atomic_set_int(&chain->flags,
1858 HAMMER2_CHAIN_DEDUPABLE);
1860 error = hammer2_freemap_alloc(chain,
1862 atomic_clear_int(&chain->flags,
1863 HAMMER2_CHAIN_DEDUPABLE);
1866 * If we are unable to allocate a new block
1867 * but we are in emergency mode, issue a
1868 * warning to the console and reuse the same
1871 * We behave as if the allocation were
1874 * THIS IS IMPORTANT: These modifications
1875 * are virtually guaranteed to corrupt any
1876 * snapshots related to this filesystem.
1878 if (error && (hmp->hflags & HMNT2_EMERG)) {
1880 chain->bref.flags |=
1881 HAMMER2_BREF_FLAG_EMERG_MIP;
1883 krateprintf(&krate_h2em,
1884 "hammer2: Emergency Mode WARNING: "
1885 "Operation will likely corrupt "
1886 "related snapshot: "
1887 "%016jx.%02x key=%016jx\n",
1888 chain->bref.data_off,
1891 } else if (error == 0) {
1892 chain->bref.flags &=
1893 ~HAMMER2_BREF_FLAG_EMERG_MIP;
1900 * Stop here if error. We have to undo any flag bits we might
1905 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1906 atomic_add_long(&hammer2_count_modified_chains, -1);
1908 hammer2_pfs_memory_wakeup(chain->pmp);
1911 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1913 lockmgr(&chain->diolk, LK_RELEASE);
1919 * Update mirror_tid and modify_tid. modify_tid is only updated
1920 * if not passed as zero (during flushes, parent propagation passes
1923 * NOTE: chain->pmp could be the device spmp.
1925 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1927 chain->bref.modify_tid = mtid;
1930 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1931 * requires updating as well as to tell the delete code that the
1932 * chain's blockref might not exactly match (in terms of physical size
1933 * or block offset) the one in the parent's blocktable. The base key
1934 * of course will still match.
1936 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1937 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1940 * Short-cut data blocks which the caller does not need an actual
1941 * data reference to (aka OPTDATA), as long as the chain does not
1942 * already have a data pointer to the data. This generally means
1943 * that the modifications are being done via the logical buffer cache.
1944 * The INITIAL flag relates only to the device data buffer and thus
1945 * remains unchange in this situation.
1947 * This code also handles bytes == 0 (most dirents).
1949 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1950 (flags & HAMMER2_MODIFY_OPTDATA) &&
1951 chain->data == NULL) {
1952 KKASSERT(chain->dio == NULL);
1957 * Clearing the INITIAL flag (for indirect blocks) indicates that
1958 * we've processed the uninitialized storage allocation.
1960 * If this flag is already clear we are likely in a copy-on-write
1961 * situation but we have to be sure NOT to bzero the storage if
1962 * no data is present.
1964 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1965 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1972 * Instantiate data buffer and possibly execute COW operation
1974 switch(chain->bref.type) {
1975 case HAMMER2_BREF_TYPE_VOLUME:
1976 case HAMMER2_BREF_TYPE_FREEMAP:
1978 * The data is embedded, no copy-on-write operation is
1981 KKASSERT(chain->dio == NULL);
1983 case HAMMER2_BREF_TYPE_DIRENT:
1985 * The data might be fully embedded.
1987 if (chain->bytes == 0) {
1988 KKASSERT(chain->dio == NULL);
1992 case HAMMER2_BREF_TYPE_INODE:
1993 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1994 case HAMMER2_BREF_TYPE_DATA:
1995 case HAMMER2_BREF_TYPE_INDIRECT:
1996 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1998 * Perform the copy-on-write operation
2000 * zero-fill or copy-on-write depending on whether
2001 * chain->data exists or not and set the dirty state for
2002 * the new buffer. hammer2_io_new() will handle the
2005 * If a dedup_off was supplied this is an existing block
2006 * and no COW, copy, or further modification is required.
2008 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
2010 if (wasinitial && dedup_off == 0) {
2011 error = hammer2_io_new(hmp, chain->bref.type,
2012 chain->bref.data_off,
2013 chain->bytes, &dio);
2015 error = hammer2_io_bread(hmp, chain->bref.type,
2016 chain->bref.data_off,
2017 chain->bytes, &dio);
2019 hammer2_adjreadcounter(&chain->bref, chain->bytes);
2022 * If an I/O error occurs make sure callers cannot accidently
2023 * modify the old buffer's contents and corrupt the filesystem.
2025 * NOTE: hammer2_io_data() call issues bkvasync()
2028 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
2030 chain->error = HAMMER2_ERROR_EIO;
2031 hammer2_io_brelse(&dio);
2032 hammer2_io_brelse(&chain->dio);
2037 bdata = hammer2_io_data(dio, chain->bref.data_off);
2041 * COW (unless a dedup).
2043 KKASSERT(chain->dio != NULL);
2044 if (chain->data != (void *)bdata && dedup_off == 0) {
2045 bcopy(chain->data, bdata, chain->bytes);
2047 } else if (wasinitial == 0) {
2049 * We have a problem. We were asked to COW but
2050 * we don't have any data to COW with!
2052 panic("hammer2_chain_modify: having a COW %p\n",
2057 * Retire the old buffer, replace with the new. Dirty or
2058 * redirty the new buffer.
2060 * WARNING! The system buffer cache may have already flushed
2061 * the buffer, so we must be sure to [re]dirty it
2062 * for further modification.
2064 * If dedup_off was supplied, the caller is not
2065 * expected to make any further modification to the
2068 * WARNING! hammer2_get_gdata() assumes dio never transitions
2069 * through NULL in order to optimize away unnecessary
2075 if ((tio = chain->dio) != NULL)
2076 hammer2_io_bqrelse(&tio);
2077 chain->data = (void *)bdata;
2080 hammer2_io_setdirty(dio);
2084 panic("hammer2_chain_modify: illegal non-embedded type %d",
2091 * setflush on parent indicating that the parent must recurse down
2092 * to us. Do not call on chain itself which might already have it
2096 hammer2_chain_setflush(chain->parent);
2097 lockmgr(&chain->diolk, LK_RELEASE);
2099 return (chain->error);
2103 * Modify the chain associated with an inode.
2106 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
2107 hammer2_tid_t mtid, int flags)
2111 hammer2_inode_modify(ip);
2112 error = hammer2_chain_modify(chain, mtid, 0, flags);
2118 * Volume header data locks
2121 hammer2_voldata_lock(hammer2_dev_t *hmp)
2123 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
2127 hammer2_voldata_unlock(hammer2_dev_t *hmp)
2129 lockmgr(&hmp->vollk, LK_RELEASE);
2133 hammer2_voldata_modify(hammer2_dev_t *hmp)
2135 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
2136 atomic_add_long(&hammer2_count_modified_chains, 1);
2137 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
2138 hammer2_pfs_memory_inc(hmp->vchain.pmp);
2143 * This function returns the chain at the nearest key within the specified
2144 * range. The returned chain will be referenced but not locked.
2146 * This function will recurse through chain->rbtree as necessary and will
2147 * return a *key_nextp suitable for iteration. *key_nextp is only set if
2148 * the iteration value is less than the current value of *key_nextp.
2150 * The caller should use (*key_nextp) to calculate the actual range of
2151 * the returned element, which will be (key_beg to *key_nextp - 1), because
2152 * there might be another element which is superior to the returned element
2155 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
2156 * chains continue to be returned. On EOF (*key_nextp) may overflow since
2157 * it will wind up being (key_end + 1).
2159 * WARNING! Must be called with child's spinlock held. Spinlock remains
2160 * held through the operation.
2162 struct hammer2_chain_find_info {
2163 hammer2_chain_t *best;
2164 hammer2_key_t key_beg;
2165 hammer2_key_t key_end;
2166 hammer2_key_t key_next;
2169 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
2170 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
2174 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
2175 hammer2_key_t key_beg, hammer2_key_t key_end)
2177 struct hammer2_chain_find_info info;
2180 info.key_beg = key_beg;
2181 info.key_end = key_end;
2182 info.key_next = *key_nextp;
2184 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
2185 hammer2_chain_find_cmp, hammer2_chain_find_callback,
2187 *key_nextp = info.key_next;
2189 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
2190 parent, key_beg, key_end, *key_nextp);
2198 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
2200 struct hammer2_chain_find_info *info = data;
2201 hammer2_key_t child_beg;
2202 hammer2_key_t child_end;
2204 child_beg = child->bref.key;
2205 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2207 if (child_end < info->key_beg)
2209 if (child_beg > info->key_end)
2216 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2218 struct hammer2_chain_find_info *info = data;
2219 hammer2_chain_t *best;
2220 hammer2_key_t child_end;
2223 * WARNING! Layerq is scanned forwards, exact matches should keep
2224 * the existing info->best.
2226 if ((best = info->best) == NULL) {
2228 * No previous best. Assign best
2231 } else if (best->bref.key <= info->key_beg &&
2232 child->bref.key <= info->key_beg) {
2237 /*info->best = child;*/
2238 } else if (child->bref.key < best->bref.key) {
2240 * Child has a nearer key and best is not flush with key_beg.
2241 * Set best to child. Truncate key_next to the old best key.
2244 if (info->key_next > best->bref.key || info->key_next == 0)
2245 info->key_next = best->bref.key;
2246 } else if (child->bref.key == best->bref.key) {
2248 * If our current best is flush with the child then this
2249 * is an illegal overlap.
2251 * key_next will automatically be limited to the smaller of
2252 * the two end-points.
2258 * Keep the current best but truncate key_next to the child's
2261 * key_next will also automatically be limited to the smaller
2262 * of the two end-points (probably not necessary for this case
2263 * but we do it anyway).
2265 if (info->key_next > child->bref.key || info->key_next == 0)
2266 info->key_next = child->bref.key;
2270 * Always truncate key_next based on child's end-of-range.
2272 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2273 if (child_end && (info->key_next > child_end || info->key_next == 0))
2274 info->key_next = child_end;
2280 * Retrieve the specified chain from a media blockref, creating the
2281 * in-memory chain structure which reflects it. The returned chain is
2282 * held and locked according to (how) (HAMMER2_RESOLVE_*). The caller must
2283 * handle crc-checks and so forth, and should check chain->error before
2284 * assuming that the data is good.
2286 * To handle insertion races pass the INSERT_RACE flag along with the
2287 * generation number of the core. NULL will be returned if the generation
2288 * number changes before we have a chance to insert the chain. Insert
2289 * races can occur because the parent might be held shared.
2291 * Caller must hold the parent locked shared or exclusive since we may
2292 * need the parent's bref array to find our block.
2294 * WARNING! chain->pmp is always set to NULL for any chain representing
2295 * part of the super-root topology.
2298 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2299 hammer2_blockref_t *bref, int how)
2301 hammer2_dev_t *hmp = parent->hmp;
2302 hammer2_chain_t *chain;
2306 * Allocate a chain structure representing the existing media
2307 * entry. Resulting chain has one ref and is not locked.
2309 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2310 chain = hammer2_chain_alloc(hmp, NULL, bref);
2312 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2313 /* ref'd chain returned */
2316 * Flag that the chain is in the parent's blockmap so delete/flush
2317 * knows what to do with it.
2319 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2322 * chain must be locked to avoid unexpected ripouts
2324 hammer2_chain_lock(chain, how);
2327 * Link the chain into its parent. A spinlock is required to safely
2328 * access the RBTREE, and it is possible to collide with another
2329 * hammer2_chain_get() operation because the caller might only hold
2330 * a shared lock on the parent.
2332 * NOTE: Get races can occur quite often when we distribute
2333 * asynchronous read-aheads across multiple threads.
2335 KKASSERT(parent->refs > 0);
2336 error = hammer2_chain_insert(parent, chain,
2337 HAMMER2_CHAIN_INSERT_SPIN |
2338 HAMMER2_CHAIN_INSERT_RACE,
2341 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2342 /*kprintf("chain %p get race\n", chain);*/
2343 hammer2_chain_unlock(chain);
2344 hammer2_chain_drop(chain);
2347 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2351 * Return our new chain referenced but not locked, or NULL if
2358 * Lookup initialization/completion API
2361 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2363 hammer2_chain_ref(parent);
2364 if (flags & HAMMER2_LOOKUP_SHARED) {
2365 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2366 HAMMER2_RESOLVE_SHARED);
2368 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2374 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2377 hammer2_chain_unlock(parent);
2378 hammer2_chain_drop(parent);
2383 * Take the locked chain and return a locked parent. The chain remains
2384 * locked on return, but may have to be temporarily unlocked to acquire
2385 * the parent. Because of this, (chain) must be stable and cannot be
2386 * deleted while it was temporarily unlocked (typically means that (chain)
2389 * Pass HAMMER2_RESOLVE_* flags in flags.
2391 * This will work even if the chain is errored, and the caller can check
2392 * parent->error on return if desired since the parent will be locked.
2394 * This function handles the lock order reversal.
2397 hammer2_chain_getparent(hammer2_chain_t *chain, int flags)
2399 hammer2_chain_t *parent;
2402 * Be careful of order, chain must be unlocked before parent
2403 * is locked below to avoid a deadlock. Try it trivially first.
2405 parent = chain->parent;
2407 panic("hammer2_chain_getparent: no parent");
2408 hammer2_chain_ref(parent);
2409 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0)
2413 hammer2_chain_unlock(chain);
2414 hammer2_chain_lock(parent, flags);
2415 hammer2_chain_lock(chain, flags);
2418 * Parent relinking races are quite common. We have to get
2419 * it right or we will blow up the block table.
2421 if (chain->parent == parent)
2423 hammer2_chain_unlock(parent);
2424 hammer2_chain_drop(parent);
2426 parent = chain->parent;
2428 panic("hammer2_chain_getparent: no parent");
2429 hammer2_chain_ref(parent);
2435 * Take the locked chain and return a locked parent. The chain is unlocked
2436 * and dropped. *chainp is set to the returned parent as a convenience.
2437 * Pass HAMMER2_RESOLVE_* flags in flags.
2439 * This will work even if the chain is errored, and the caller can check
2440 * parent->error on return if desired since the parent will be locked.
2442 * The chain does NOT need to be stable. We use a tracking structure
2443 * to track the expected parent if the chain is deleted out from under us.
2445 * This function handles the lock order reversal.
2448 hammer2_chain_repparent(hammer2_chain_t **chainp, int flags)
2450 hammer2_chain_t *chain;
2451 hammer2_chain_t *parent;
2452 struct hammer2_reptrack reptrack;
2453 struct hammer2_reptrack **repp;
2456 * Be careful of order, chain must be unlocked before parent
2457 * is locked below to avoid a deadlock. Try it trivially first.
2460 parent = chain->parent;
2461 if (parent == NULL) {
2462 hammer2_spin_unex(&chain->core.spin);
2463 panic("hammer2_chain_repparent: no parent");
2465 hammer2_chain_ref(parent);
2466 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0) {
2467 hammer2_chain_unlock(chain);
2468 hammer2_chain_drop(chain);
2475 * Ok, now it gets a bit nasty. There are multiple situations where
2476 * the parent might be in the middle of a deletion, or where the child
2477 * (chain) might be deleted the instant we let go of its lock.
2478 * We can potentially end up in a no-win situation!
2480 * In particular, the indirect_maintenance() case can cause these
2483 * To deal with this we install a reptrack structure in the parent
2484 * This reptrack structure 'owns' the parent ref and will automatically
2485 * migrate to the parent's parent if the parent is deleted permanently.
2487 hammer2_spin_init(&reptrack.spin, "h2reptrk");
2488 reptrack.chain = parent;
2489 hammer2_chain_ref(parent); /* for the reptrack */
2491 hammer2_spin_ex(&parent->core.spin);
2492 reptrack.next = parent->core.reptrack;
2493 parent->core.reptrack = &reptrack;
2494 hammer2_spin_unex(&parent->core.spin);
2496 hammer2_chain_unlock(chain);
2497 hammer2_chain_drop(chain);
2498 chain = NULL; /* gone */
2501 * At the top of this loop, chain is gone and parent is refd both
2502 * by us explicitly AND via our reptrack. We are attempting to
2506 hammer2_chain_lock(parent, flags);
2508 if (reptrack.chain == parent)
2510 hammer2_chain_unlock(parent);
2511 hammer2_chain_drop(parent);
2513 kprintf("hammer2: debug REPTRACK %p->%p\n",
2514 parent, reptrack.chain);
2515 hammer2_spin_ex(&reptrack.spin);
2516 parent = reptrack.chain;
2517 hammer2_chain_ref(parent);
2518 hammer2_spin_unex(&reptrack.spin);
2522 * Once parent is locked and matches our reptrack, our reptrack
2523 * will be stable and we have our parent. We can unlink our
2526 * WARNING! Remember that the chain lock might be shared. Chains
2527 * locked shared have stable parent linkages.
2529 hammer2_spin_ex(&parent->core.spin);
2530 repp = &parent->core.reptrack;
2531 while (*repp != &reptrack)
2532 repp = &(*repp)->next;
2533 *repp = reptrack.next;
2534 hammer2_spin_unex(&parent->core.spin);
2536 hammer2_chain_drop(parent); /* reptrack ref */
2537 *chainp = parent; /* return parent lock+ref */
2543 * Dispose of any linked reptrack structures in (chain) by shifting them to
2544 * (parent). Both (chain) and (parent) must be exclusively locked.
2546 * This is interlocked against any children of (chain) on the other side.
2547 * No children so remain as-of when this is called so we can test
2548 * core.reptrack without holding the spin-lock.
2550 * Used whenever the caller intends to permanently delete chains related
2551 * to topological recursions (BREF_TYPE_INDIRECT, BREF_TYPE_FREEMAP_NODE),
2552 * where the chains underneath the node being deleted are given a new parent
2553 * above the node being deleted.
2557 hammer2_chain_repchange(hammer2_chain_t *parent, hammer2_chain_t *chain)
2559 struct hammer2_reptrack *reptrack;
2561 KKASSERT(chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree));
2562 while (chain->core.reptrack) {
2563 hammer2_spin_ex(&parent->core.spin);
2564 hammer2_spin_ex(&chain->core.spin);
2565 reptrack = chain->core.reptrack;
2566 if (reptrack == NULL) {
2567 hammer2_spin_unex(&chain->core.spin);
2568 hammer2_spin_unex(&parent->core.spin);
2571 hammer2_spin_ex(&reptrack->spin);
2572 chain->core.reptrack = reptrack->next;
2573 reptrack->chain = parent;
2574 reptrack->next = parent->core.reptrack;
2575 parent->core.reptrack = reptrack;
2576 hammer2_chain_ref(parent); /* reptrack */
2578 hammer2_spin_unex(&chain->core.spin);
2579 hammer2_spin_unex(&parent->core.spin);
2580 kprintf("hammer2: debug repchange %p %p->%p\n",
2581 reptrack, chain, parent);
2582 hammer2_chain_drop(chain); /* reptrack */
2587 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2588 * (*parentp) typically points to an inode but can also point to a related
2589 * indirect block and this function will recurse upwards and find the inode
2590 * or the nearest undeleted indirect block covering the key range.
2592 * This function unconditionally sets *errorp, replacing any previous value.
2594 * (*parentp) must be exclusive or shared locked (depending on flags) and
2595 * referenced and can be an inode or an existing indirect block within the
2598 * If (*parent) is errored out, this function will not attempt to recurse
2599 * the radix tree and will return NULL along with an appropriate *errorp.
2600 * If NULL is returned and *errorp is 0, the requested lookup could not be
2603 * On return (*parentp) will be modified to point at the deepest parent chain
2604 * element encountered during the search, as a helper for an insertion or
2607 * The new (*parentp) will be locked shared or exclusive (depending on flags),
2608 * and referenced, and the old will be unlocked and dereferenced (no change
2609 * if they are both the same). This is particularly important if the caller
2610 * wishes to insert a new chain, (*parentp) will be set properly even if NULL
2611 * is returned, as long as no error occurred.
2613 * The matching chain will be returned locked according to flags.
2617 * NULL is returned if no match was found, but (*parentp) will still
2618 * potentially be adjusted.
2620 * On return (*key_nextp) will point to an iterative value for key_beg.
2621 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2623 * This function will also recurse up the chain if the key is not within the
2624 * current parent's range. (*parentp) can never be set to NULL. An iteration
2625 * can simply allow (*parentp) to float inside the loop.
2627 * NOTE! chain->data is not always resolved. By default it will not be
2628 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2629 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2630 * BREF_TYPE_DATA as the device buffer can alias the logical file
2635 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2636 hammer2_key_t key_beg, hammer2_key_t key_end,
2637 int *errorp, int flags)
2640 hammer2_chain_t *parent;
2641 hammer2_chain_t *chain;
2642 hammer2_blockref_t *base;
2643 hammer2_blockref_t *bref;
2644 hammer2_blockref_t bsave;
2645 hammer2_key_t scan_beg;
2646 hammer2_key_t scan_end;
2648 int how_always = HAMMER2_RESOLVE_ALWAYS;
2649 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2652 int maxloops = 300000;
2653 volatile hammer2_mtx_t save_mtx;
2655 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2656 how_maybe = how_always;
2657 how = HAMMER2_RESOLVE_ALWAYS;
2658 } else if (flags & HAMMER2_LOOKUP_NODATA) {
2659 how = HAMMER2_RESOLVE_NEVER;
2661 how = HAMMER2_RESOLVE_MAYBE;
2663 if (flags & HAMMER2_LOOKUP_SHARED) {
2664 how_maybe |= HAMMER2_RESOLVE_SHARED;
2665 how_always |= HAMMER2_RESOLVE_SHARED;
2666 how |= HAMMER2_RESOLVE_SHARED;
2670 * Recurse (*parentp) upward if necessary until the parent completely
2671 * encloses the key range or we hit the inode.
2673 * Handle races against the flusher deleting indirect nodes on its
2674 * way back up by continuing to recurse upward past the deletion.
2680 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2681 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2682 scan_beg = parent->bref.key;
2683 scan_end = scan_beg +
2684 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2685 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2686 if (key_beg >= scan_beg && key_end <= scan_end)
2689 parent = hammer2_chain_repparent(parentp, how_maybe);
2692 if (--maxloops == 0)
2693 panic("hammer2_chain_lookup: maxloops");
2696 * MATCHIND case that does not require parent->data (do prior to
2697 * parent->error check).
2699 switch(parent->bref.type) {
2700 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2701 case HAMMER2_BREF_TYPE_INDIRECT:
2702 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2703 scan_beg = parent->bref.key;
2704 scan_end = scan_beg +
2705 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2706 if (key_beg == scan_beg && key_end == scan_end) {
2708 hammer2_chain_ref(chain);
2709 hammer2_chain_lock(chain, how_maybe);
2710 *key_nextp = scan_end + 1;
2720 * No lookup is possible if the parent is errored. We delayed
2721 * this check as long as we could to ensure that the parent backup,
2722 * embedded data, and MATCHIND code could still execute.
2724 if (parent->error) {
2725 *errorp = parent->error;
2730 * Locate the blockref array. Currently we do a fully associative
2731 * search through the array.
2733 switch(parent->bref.type) {
2734 case HAMMER2_BREF_TYPE_INODE:
2736 * Special shortcut for embedded data returns the inode
2737 * itself. Callers must detect this condition and access
2738 * the embedded data (the strategy code does this for us).
2740 * This is only applicable to regular files and softlinks.
2742 * We need a second lock on parent. Since we already have
2743 * a lock we must pass LOCKAGAIN to prevent unexpected
2744 * blocking (we don't want to block on a second shared
2745 * ref if an exclusive lock is pending)
2747 if (parent->data->ipdata.meta.op_flags &
2748 HAMMER2_OPFLAG_DIRECTDATA) {
2749 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2751 *key_nextp = key_end + 1;
2754 hammer2_chain_ref(parent);
2755 hammer2_chain_lock(parent, how_always |
2756 HAMMER2_RESOLVE_LOCKAGAIN);
2757 *key_nextp = key_end + 1;
2760 base = &parent->data->ipdata.u.blockset.blockref[0];
2761 count = HAMMER2_SET_COUNT;
2763 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2764 case HAMMER2_BREF_TYPE_INDIRECT:
2766 * Optimize indirect blocks in the INITIAL state to avoid
2769 * Debugging: Enter permanent wait state instead of
2770 * panicing on unexpectedly NULL data for the moment.
2772 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2775 if (parent->data == NULL) {
2776 kprintf("hammer2: unexpected NULL data "
2779 tsleep(parent, 0, "xxx", 0);
2781 base = &parent->data->npdata[0];
2783 count = parent->bytes / sizeof(hammer2_blockref_t);
2785 case HAMMER2_BREF_TYPE_VOLUME:
2786 base = &parent->data->voldata.sroot_blockset.blockref[0];
2787 count = HAMMER2_SET_COUNT;
2789 case HAMMER2_BREF_TYPE_FREEMAP:
2790 base = &parent->data->blkset.blockref[0];
2791 count = HAMMER2_SET_COUNT;
2794 kprintf("hammer2_chain_lookup: unrecognized "
2795 "blockref(B) type: %d",
2798 tsleep(&base, 0, "dead", 0);
2799 panic("hammer2_chain_lookup: unrecognized "
2800 "blockref(B) type: %d",
2802 base = NULL; /* safety */
2803 count = 0; /* safety */
2807 * Merged scan to find next candidate.
2809 * hammer2_base_*() functions require the parent->core.live_* fields
2810 * to be synchronized.
2812 * We need to hold the spinlock to access the block array and RB tree
2813 * and to interlock chain creation.
2815 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2816 hammer2_chain_countbrefs(parent, base, count);
2821 hammer2_spin_ex(&parent->core.spin);
2822 chain = hammer2_combined_find(parent, base, count,
2826 generation = parent->core.generation;
2829 * Exhausted parent chain, iterate.
2832 KKASSERT(chain == NULL);
2833 hammer2_spin_unex(&parent->core.spin);
2834 if (key_beg == key_end) /* short cut single-key case */
2838 * Stop if we reached the end of the iteration.
2840 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2841 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2846 * Calculate next key, stop if we reached the end of the
2847 * iteration, otherwise go up one level and loop.
2849 key_beg = parent->bref.key +
2850 ((hammer2_key_t)1 << parent->bref.keybits);
2851 if (key_beg == 0 || key_beg > key_end)
2853 parent = hammer2_chain_repparent(parentp, how_maybe);
2858 * Selected from blockref or in-memory chain.
2861 if (chain == NULL) {
2862 hammer2_spin_unex(&parent->core.spin);
2863 if (bsave.type == HAMMER2_BREF_TYPE_INDIRECT ||
2864 bsave.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2865 chain = hammer2_chain_get(parent, generation,
2868 chain = hammer2_chain_get(parent, generation,
2874 hammer2_chain_ref(chain);
2875 hammer2_spin_unex(&parent->core.spin);
2878 * chain is referenced but not locked. We must lock the
2879 * chain to obtain definitive state.
2881 if (bsave.type == HAMMER2_BREF_TYPE_INDIRECT ||
2882 bsave.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2883 hammer2_chain_lock(chain, how_maybe);
2885 hammer2_chain_lock(chain, how);
2887 KKASSERT(chain->parent == parent);
2889 if (bcmp(&bsave, &chain->bref, sizeof(bsave)) ||
2890 chain->parent != parent) {
2891 hammer2_chain_unlock(chain);
2892 hammer2_chain_drop(chain);
2893 chain = NULL; /* SAFETY */
2899 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2901 * NOTE: Chain's key range is not relevant as there might be
2902 * one-offs within the range that are not deleted.
2904 * NOTE: Lookups can race delete-duplicate because
2905 * delete-duplicate does not lock the parent's core
2906 * (they just use the spinlock on the core).
2908 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2909 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2910 chain->bref.data_off, chain->bref.type,
2912 hammer2_chain_unlock(chain);
2913 hammer2_chain_drop(chain);
2914 chain = NULL; /* SAFETY */
2915 key_beg = *key_nextp;
2916 if (key_beg == 0 || key_beg > key_end)
2922 * If the chain element is an indirect block it becomes the new
2923 * parent and we loop on it. We must maintain our top-down locks
2924 * to prevent the flusher from interfering (i.e. doing a
2925 * delete-duplicate and leaving us recursing down a deleted chain).
2927 * The parent always has to be locked with at least RESOLVE_MAYBE
2928 * so we can access its data. It might need a fixup if the caller
2929 * passed incompatible flags. Be careful not to cause a deadlock
2930 * as a data-load requires an exclusive lock.
2932 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2933 * range is within the requested key range we return the indirect
2934 * block and do NOT loop. This is usually only used to acquire
2937 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2938 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2939 save_mtx = parent->lock;
2940 hammer2_chain_unlock(parent);
2941 hammer2_chain_drop(parent);
2942 *parentp = parent = chain;
2943 chain = NULL; /* SAFETY */
2948 * All done, return the locked chain.
2950 * If the caller does not want a locked chain, replace the lock with
2951 * a ref. Perhaps this can eventually be optimized to not obtain the
2952 * lock in the first place for situations where the data does not
2953 * need to be resolved.
2955 * NOTE! A chain->error must be tested by the caller upon return.
2956 * *errorp is only set based on issues which occur while
2957 * trying to reach the chain.
2963 * After having issued a lookup we can iterate all matching keys.
2965 * If chain is non-NULL we continue the iteration from just after it's index.
2967 * If chain is NULL we assume the parent was exhausted and continue the
2968 * iteration at the next parent.
2970 * If a fatal error occurs (typically an I/O error), a dummy chain is
2971 * returned with chain->error and error-identifying information set. This
2972 * chain will assert if you try to do anything fancy with it.
2974 * XXX Depending on where the error occurs we should allow continued iteration.
2976 * parent must be locked on entry and remains locked throughout. chain's
2977 * lock status must match flags. Chain is always at least referenced.
2979 * WARNING! The MATCHIND flag does not apply to this function.
2982 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2983 hammer2_key_t *key_nextp,
2984 hammer2_key_t key_beg, hammer2_key_t key_end,
2985 int *errorp, int flags)
2987 hammer2_chain_t *parent;
2991 * Calculate locking flags for upward recursion.
2993 how_maybe = HAMMER2_RESOLVE_MAYBE;
2994 if (flags & HAMMER2_LOOKUP_SHARED)
2995 how_maybe |= HAMMER2_RESOLVE_SHARED;
3001 * Calculate the next index and recalculate the parent if necessary.
3004 key_beg = chain->bref.key +
3005 ((hammer2_key_t)1 << chain->bref.keybits);
3006 hammer2_chain_unlock(chain);
3007 hammer2_chain_drop(chain);
3010 * chain invalid past this point, but we can still do a
3011 * pointer comparison w/parent.
3013 * Any scan where the lookup returned degenerate data embedded
3014 * in the inode has an invalid index and must terminate.
3016 if (chain == parent)
3018 if (key_beg == 0 || key_beg > key_end)
3021 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
3022 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
3024 * We reached the end of the iteration.
3029 * Continue iteration with next parent unless the current
3030 * parent covers the range.
3032 * (This also handles the case of a deleted, empty indirect
3035 key_beg = parent->bref.key +
3036 ((hammer2_key_t)1 << parent->bref.keybits);
3037 if (key_beg == 0 || key_beg > key_end)
3039 parent = hammer2_chain_repparent(parentp, how_maybe);
3045 return (hammer2_chain_lookup(parentp, key_nextp,
3051 * Caller wishes to iterate chains under parent, loading new chains into
3052 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
3053 * then call hammer2_chain_scan() repeatedly until a non-zero return.
3054 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
3055 * with the returned chain for the scan. The returned *chainp will be
3056 * locked and referenced. Any prior contents will be unlocked and dropped.
3058 * Caller should check the return value. A normal scan EOF will return
3059 * exactly HAMMER2_ERROR_EOF. Any other non-zero value indicates an
3060 * error trying to access parent data. Any error in the returned chain
3061 * must be tested separately by the caller.
3063 * (*chainp) is dropped on each scan, but will only be set if the returned
3064 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
3065 * returned via *chainp. The caller will get their bref only.
3067 * The raw scan function is similar to lookup/next but does not seek to a key.
3068 * Blockrefs are iterated via first_bref = (parent, NULL) and
3069 * next_chain = (parent, bref).
3071 * The passed-in parent must be locked and its data resolved. The function
3072 * nominally returns a locked and referenced *chainp != NULL for chains
3073 * the caller might need to recurse on (and will dipose of any *chainp passed
3074 * in). The caller must check the chain->bref.type either way.
3077 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
3078 hammer2_blockref_t *bref, int *firstp,
3082 hammer2_blockref_t *base;
3083 hammer2_blockref_t *bref_ptr;
3085 hammer2_key_t next_key;
3086 hammer2_chain_t *chain = NULL;
3088 int how_always = HAMMER2_RESOLVE_ALWAYS;
3089 int how_maybe = HAMMER2_RESOLVE_MAYBE;
3092 int maxloops = 300000;
3099 * Scan flags borrowed from lookup.
3101 if (flags & HAMMER2_LOOKUP_ALWAYS) {
3102 how_maybe = how_always;
3103 how = HAMMER2_RESOLVE_ALWAYS;
3104 } else if (flags & HAMMER2_LOOKUP_NODATA) {
3105 how = HAMMER2_RESOLVE_NEVER;
3107 how = HAMMER2_RESOLVE_MAYBE;
3109 if (flags & HAMMER2_LOOKUP_SHARED) {
3110 how_maybe |= HAMMER2_RESOLVE_SHARED;
3111 how_always |= HAMMER2_RESOLVE_SHARED;
3112 how |= HAMMER2_RESOLVE_SHARED;
3116 * Calculate key to locate first/next element, unlocking the previous
3117 * element as we go. Be careful, the key calculation can overflow.
3119 * (also reset bref to NULL)
3125 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
3126 if ((chain = *chainp) != NULL) {
3128 hammer2_chain_unlock(chain);
3129 hammer2_chain_drop(chain);
3133 error |= HAMMER2_ERROR_EOF;
3139 if (parent->error) {
3140 error = parent->error;
3143 if (--maxloops == 0)
3144 panic("hammer2_chain_scan: maxloops");
3147 * Locate the blockref array. Currently we do a fully associative
3148 * search through the array.
3150 switch(parent->bref.type) {
3151 case HAMMER2_BREF_TYPE_INODE:
3153 * An inode with embedded data has no sub-chains.
3155 * WARNING! Bulk scan code may pass a static chain marked
3156 * as BREF_TYPE_INODE with a copy of the volume
3157 * root blockset to snapshot the volume.
3159 if (parent->data->ipdata.meta.op_flags &
3160 HAMMER2_OPFLAG_DIRECTDATA) {
3161 error |= HAMMER2_ERROR_EOF;
3164 base = &parent->data->ipdata.u.blockset.blockref[0];
3165 count = HAMMER2_SET_COUNT;
3167 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3168 case HAMMER2_BREF_TYPE_INDIRECT:
3170 * Optimize indirect blocks in the INITIAL state to avoid
3173 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3176 if (parent->data == NULL)
3177 panic("parent->data is NULL");
3178 base = &parent->data->npdata[0];
3180 count = parent->bytes / sizeof(hammer2_blockref_t);
3182 case HAMMER2_BREF_TYPE_VOLUME:
3183 base = &parent->data->voldata.sroot_blockset.blockref[0];
3184 count = HAMMER2_SET_COUNT;
3186 case HAMMER2_BREF_TYPE_FREEMAP:
3187 base = &parent->data->blkset.blockref[0];
3188 count = HAMMER2_SET_COUNT;
3191 panic("hammer2_chain_scan: unrecognized blockref type: %d",
3193 base = NULL; /* safety */
3194 count = 0; /* safety */
3198 * Merged scan to find next candidate.
3200 * hammer2_base_*() functions require the parent->core.live_* fields
3201 * to be synchronized.
3203 * We need to hold the spinlock to access the block array and RB tree
3204 * and to interlock chain creation.
3206 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3207 hammer2_chain_countbrefs(parent, base, count);
3211 hammer2_spin_ex(&parent->core.spin);
3212 chain = hammer2_combined_find(parent, base, count,
3214 key, HAMMER2_KEY_MAX,
3216 generation = parent->core.generation;
3219 * Exhausted parent chain, we're done.
3221 if (bref_ptr == NULL) {
3222 hammer2_spin_unex(&parent->core.spin);
3223 KKASSERT(chain == NULL);
3224 error |= HAMMER2_ERROR_EOF;
3229 * Copy into the supplied stack-based blockref.
3234 * Selected from blockref or in-memory chain.
3236 if (chain == NULL) {
3237 switch(bref->type) {
3238 case HAMMER2_BREF_TYPE_INODE:
3239 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3240 case HAMMER2_BREF_TYPE_INDIRECT:
3241 case HAMMER2_BREF_TYPE_VOLUME:
3242 case HAMMER2_BREF_TYPE_FREEMAP:
3244 * Recursion, always get the chain
3246 hammer2_spin_unex(&parent->core.spin);
3247 chain = hammer2_chain_get(parent, generation,
3254 * No recursion, do not waste time instantiating
3255 * a chain, just iterate using the bref.
3257 hammer2_spin_unex(&parent->core.spin);
3262 * Recursion or not we need the chain in order to supply
3265 hammer2_chain_ref(chain);
3266 hammer2_spin_unex(&parent->core.spin);
3267 hammer2_chain_lock(chain, how);
3270 (bcmp(bref, &chain->bref, sizeof(*bref)) ||
3271 chain->parent != parent)) {
3272 hammer2_chain_unlock(chain);
3273 hammer2_chain_drop(chain);
3279 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
3281 * NOTE: chain's key range is not relevant as there might be
3282 * one-offs within the range that are not deleted.
3284 * NOTE: XXX this could create problems with scans used in
3285 * situations other than mount-time recovery.
3287 * NOTE: Lookups can race delete-duplicate because
3288 * delete-duplicate does not lock the parent's core
3289 * (they just use the spinlock on the core).
3291 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3292 hammer2_chain_unlock(chain);
3293 hammer2_chain_drop(chain);
3298 error |= HAMMER2_ERROR_EOF;
3306 * All done, return the bref or NULL, supply chain if necessary.
3314 * Create and return a new hammer2 system memory structure of the specified
3315 * key, type and size and insert it under (*parentp). This is a full
3316 * insertion, based on the supplied key/keybits, and may involve creating
3317 * indirect blocks and moving other chains around via delete/duplicate.
3319 * This call can be made with parent == NULL as long as a non -1 methods
3320 * is supplied. hmp must also be supplied in this situation (otherwise
3321 * hmp is extracted from the supplied parent). The chain will be detached
3322 * from the topology. A later call with both parent and chain can be made
3325 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3326 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3327 * FULL. This typically means that the caller is creating the chain after
3328 * doing a hammer2_chain_lookup().
3330 * (*parentp) must be exclusive locked and may be replaced on return
3331 * depending on how much work the function had to do.
3333 * (*parentp) must not be errored or this function will assert.
3335 * (*chainp) usually starts out NULL and returns the newly created chain,
3336 * but if the caller desires the caller may allocate a disconnected chain
3337 * and pass it in instead.
3339 * This function should NOT be used to insert INDIRECT blocks. It is
3340 * typically used to create/insert inodes and data blocks.
3342 * Caller must pass-in an exclusively locked parent the new chain is to
3343 * be inserted under, and optionally pass-in a disconnected, exclusively
3344 * locked chain to insert (else we create a new chain). The function will
3345 * adjust (*parentp) as necessary, create or connect the chain, and
3346 * return an exclusively locked chain in *chainp.
3348 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3349 * and will be reassigned.
3351 * NOTE: returns HAMMER_ERROR_* flags
3354 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3355 hammer2_dev_t *hmp, hammer2_pfs_t *pmp, int methods,
3356 hammer2_key_t key, int keybits, int type, size_t bytes,
3357 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3359 hammer2_chain_t *chain;
3360 hammer2_chain_t *parent;
3361 hammer2_blockref_t *base;
3362 hammer2_blockref_t dummy;
3366 int maxloops = 300000;
3369 * Topology may be crossing a PFS boundary.
3373 KKASSERT(hammer2_mtx_owned(&parent->lock));
3374 KKASSERT(parent->error == 0);
3379 if (chain == NULL) {
3381 * First allocate media space and construct the dummy bref,
3382 * then allocate the in-memory chain structure. Set the
3383 * INITIAL flag for fresh chains which do not have embedded
3386 * XXX for now set the check mode of the child based on
3387 * the parent or, if the parent is an inode, the
3388 * specification in the inode.
3390 bzero(&dummy, sizeof(dummy));
3393 dummy.keybits = keybits;
3394 dummy.data_off = hammer2_getradix(bytes);
3397 * Inherit methods from parent by default. Primarily used
3398 * for BREF_TYPE_DATA. Non-data types *must* be set to
3399 * a non-NONE check algorithm.
3402 dummy.methods = parent->bref.methods;
3404 dummy.methods = (uint8_t)methods;
3406 if (type != HAMMER2_BREF_TYPE_DATA &&
3407 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3409 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3412 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3415 * Lock the chain manually, chain_lock will load the chain
3416 * which we do NOT want to do. (note: chain->refs is set
3417 * to 1 by chain_alloc() for us, but lockcnt is not).
3420 hammer2_mtx_ex(&chain->lock);
3424 * Set INITIAL to optimize I/O. The flag will generally be
3425 * processed when we call hammer2_chain_modify().
3427 * Recalculate bytes to reflect the actual media block
3428 * allocation. Handle special case radix 0 == 0 bytes.
3430 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3432 bytes = (hammer2_off_t)1 << bytes;
3433 chain->bytes = bytes;
3436 case HAMMER2_BREF_TYPE_VOLUME:
3437 case HAMMER2_BREF_TYPE_FREEMAP:
3438 panic("hammer2_chain_create: called with volume type");
3440 case HAMMER2_BREF_TYPE_INDIRECT:
3441 panic("hammer2_chain_create: cannot be used to"
3442 "create indirect block");
3444 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3445 panic("hammer2_chain_create: cannot be used to"
3446 "create freemap root or node");
3448 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3449 KKASSERT(bytes == sizeof(chain->data->bmdata));
3451 case HAMMER2_BREF_TYPE_DIRENT:
3452 case HAMMER2_BREF_TYPE_INODE:
3453 case HAMMER2_BREF_TYPE_DATA:
3456 * leave chain->data NULL, set INITIAL
3458 KKASSERT(chain->data == NULL);
3459 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3464 * We are reattaching a previously deleted chain, possibly
3465 * under a new parent and possibly with a new key/keybits.
3466 * The chain does not have to be in a modified state. The
3467 * UPDATE flag will be set later on in this routine.
3469 * Do NOT mess with the current state of the INITIAL flag.
3471 chain->bref.key = key;
3472 chain->bref.keybits = keybits;
3473 if (chain->flags & HAMMER2_CHAIN_DELETED)
3474 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3475 KKASSERT(chain->parent == NULL);
3479 * Set the appropriate bref flag if requested.
3481 * NOTE! Callers can call this function to move chains without
3482 * knowing about special flags, so don't clear bref flags
3485 if (flags & HAMMER2_INSERT_PFSROOT)
3486 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3492 * Calculate how many entries we have in the blockref array and
3493 * determine if an indirect block is required when inserting into
3497 if (--maxloops == 0)
3498 panic("hammer2_chain_create: maxloops");
3500 switch(parent->bref.type) {
3501 case HAMMER2_BREF_TYPE_INODE:
3502 if ((parent->data->ipdata.meta.op_flags &
3503 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3504 kprintf("hammer2: parent set for direct-data! "
3505 "pkey=%016jx ckey=%016jx\n",
3509 KKASSERT((parent->data->ipdata.meta.op_flags &
3510 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3511 KKASSERT(parent->data != NULL);
3512 base = &parent->data->ipdata.u.blockset.blockref[0];
3513 count = HAMMER2_SET_COUNT;
3515 case HAMMER2_BREF_TYPE_INDIRECT:
3516 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3517 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3520 base = &parent->data->npdata[0];
3521 count = parent->bytes / sizeof(hammer2_blockref_t);
3523 case HAMMER2_BREF_TYPE_VOLUME:
3524 KKASSERT(parent->data != NULL);
3525 base = &parent->data->voldata.sroot_blockset.blockref[0];
3526 count = HAMMER2_SET_COUNT;
3528 case HAMMER2_BREF_TYPE_FREEMAP:
3529 KKASSERT(parent->data != NULL);
3530 base = &parent->data->blkset.blockref[0];
3531 count = HAMMER2_SET_COUNT;
3534 panic("hammer2_chain_create: unrecognized blockref type: %d",
3542 * Make sure we've counted the brefs
3544 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3545 hammer2_chain_countbrefs(parent, base, count);
3547 KASSERT(parent->core.live_count >= 0 &&
3548 parent->core.live_count <= count,
3549 ("bad live_count %d/%d (%02x, %d)",
3550 parent->core.live_count, count,
3551 parent->bref.type, parent->bytes));
3554 * If no free blockref could be found we must create an indirect
3555 * block and move a number of blockrefs into it. With the parent
3556 * locked we can safely lock each child in order to delete+duplicate
3557 * it without causing a deadlock.
3559 * This may return the new indirect block or the old parent depending
3560 * on where the key falls. NULL is returned on error.
3562 if (parent->core.live_count == count) {
3563 hammer2_chain_t *nparent;
3565 KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3567 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3568 mtid, type, &error);
3569 if (nparent == NULL) {
3571 hammer2_chain_drop(chain);
3575 if (parent != nparent) {
3576 hammer2_chain_unlock(parent);
3577 hammer2_chain_drop(parent);
3578 parent = *parentp = nparent;
3584 * fall through if parent, or skip to here if no parent.
3587 if (chain->flags & HAMMER2_CHAIN_DELETED)
3588 kprintf("Inserting deleted chain @%016jx\n",
3592 * Link the chain into its parent.
3594 if (chain->parent != NULL)
3595 panic("hammer2: hammer2_chain_create: chain already connected");
3596 KKASSERT(chain->parent == NULL);
3598 KKASSERT(parent->core.live_count < count);
3599 hammer2_chain_insert(parent, chain,
3600 HAMMER2_CHAIN_INSERT_SPIN |
3601 HAMMER2_CHAIN_INSERT_LIVE,
3607 * Mark the newly created chain modified. This will cause
3608 * UPDATE to be set and process the INITIAL flag.
3610 * Device buffers are not instantiated for DATA elements
3611 * as these are handled by logical buffers.
3613 * Indirect and freemap node indirect blocks are handled
3614 * by hammer2_chain_create_indirect() and not by this
3617 * Data for all other bref types is expected to be
3618 * instantiated (INODE, LEAF).
3620 switch(chain->bref.type) {
3621 case HAMMER2_BREF_TYPE_DATA:
3622 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3623 case HAMMER2_BREF_TYPE_DIRENT:
3624 case HAMMER2_BREF_TYPE_INODE:
3625 error = hammer2_chain_modify(chain, mtid, dedup_off,
3626 HAMMER2_MODIFY_OPTDATA);
3630 * Remaining types are not supported by this function.
3631 * In particular, INDIRECT and LEAF_NODE types are
3632 * handled by create_indirect().
3634 panic("hammer2_chain_create: bad type: %d",
3641 * When reconnecting a chain we must set UPDATE and
3642 * setflush so the flush recognizes that it must update
3643 * the bref in the parent.
3645 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3646 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3650 * We must setflush(parent) to ensure that it recurses through to
3651 * chain. setflush(chain) might not work because ONFLUSH is possibly
3652 * already set in the chain (so it won't recurse up to set it in the
3656 hammer2_chain_setflush(parent);
3665 * Move the chain from its old parent to a new parent. The chain must have
3666 * already been deleted or already disconnected (or never associated) with
3667 * a parent. The chain is reassociated with the new parent and the deleted
3668 * flag will be cleared (no longer deleted). The chain's modification state
3671 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3672 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3673 * FULL. This typically means that the caller is creating the chain after
3674 * doing a hammer2_chain_lookup().
3676 * Neither (parent) or (chain) can be errored.
3678 * If (parent) is non-NULL then the chain is inserted under the parent.
3680 * If (parent) is NULL then the newly duplicated chain is not inserted
3681 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3682 * passing into hammer2_chain_create() after this function returns).
3684 * WARNING! This function calls create which means it can insert indirect
3685 * blocks. This can cause other unrelated chains in the parent to
3686 * be moved to a newly inserted indirect block in addition to the
3690 hammer2_chain_rename(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3691 hammer2_tid_t mtid, int flags)
3693 hammer2_blockref_t *bref;
3695 hammer2_chain_t *parent;
3699 * WARNING! We should never resolve DATA to device buffers
3700 * (XXX allow it if the caller did?), and since
3701 * we currently do not have the logical buffer cache
3702 * buffer in-hand to fix its cached physical offset
3703 * we also force the modify code to not COW it. XXX
3705 * NOTE! We allow error'd chains to be renamed. The bref itself
3706 * is good and can be renamed. The content, however, may
3710 KKASSERT(chain->parent == NULL);
3711 /*KKASSERT(chain->error == 0); allow */
3714 * Now create a duplicate of the chain structure, associating
3715 * it with the same core, making it the same size, pointing it
3716 * to the same bref (the same media block).
3718 * NOTE: Handle special radix == 0 case (means 0 bytes).
3720 bref = &chain->bref;
3721 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3723 bytes = (hammer2_off_t)1 << bytes;
3726 * If parent is not NULL the duplicated chain will be entered under
3727 * the parent and the UPDATE bit set to tell flush to update
3730 * We must setflush(parent) to ensure that it recurses through to
3731 * chain. setflush(chain) might not work because ONFLUSH is possibly
3732 * already set in the chain (so it won't recurse up to set it in the
3735 * Having both chains locked is extremely important for atomicy.
3737 if (parentp && (parent = *parentp) != NULL) {
3738 KKASSERT(hammer2_mtx_owned(&parent->lock));
3739 KKASSERT(parent->refs > 0);
3740 KKASSERT(parent->error == 0);
3742 hammer2_chain_create(parentp, &chain, NULL, chain->pmp,
3743 HAMMER2_METH_DEFAULT,
3744 bref->key, bref->keybits, bref->type,
3745 chain->bytes, mtid, 0, flags);
3746 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3747 hammer2_chain_setflush(*parentp);
3752 * This works in tandem with delete_obref() to install a blockref in
3753 * (typically) an indirect block that is associated with the chain being
3754 * moved to *parentp.
3756 * The reason we need this function is that the caller needs to maintain
3757 * the blockref as it was, and not generate a new blockref for what might
3758 * be a modified chain. Otherwise stuff will leak into the flush that
3759 * the flush code's FLUSH_INODE_STOP flag is unable to catch.
3761 * It is EXTREMELY important that we properly set CHAIN_BMAPUPD and
3762 * CHAIN_UPDATE. We must set BMAPUPD if the bref does not match, and
3763 * we must clear CHAIN_UPDATE (that was likely set by the chain_rename) if
3764 * it does. Otherwise we can end up in a situation where H2 is unable to
3765 * clean up the in-memory chain topology.
3767 * The reason for this is that flushes do not generally flush through
3768 * BREF_TYPE_INODE chains and depend on a hammer2_inode_t queued to syncq
3769 * or sideq to properly flush and dispose of the related inode chain's flags.
3770 * Situations where the inode is not actually modified by the frontend,
3771 * but where we have to move the related chains around as we insert or cleanup
3772 * indirect blocks, can leave us with a 'dirty' (non-disposable) in-memory
3773 * inode chain that does not have a hammer2_inode_t associated with it.
3776 hammer2_chain_rename_obref(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3777 hammer2_tid_t mtid, int flags,
3778 hammer2_blockref_t *obref)
3780 hammer2_chain_rename(parentp, chain, mtid, flags);
3782 if (obref->type != HAMMER2_BREF_TYPE_EMPTY) {
3783 hammer2_blockref_t *tbase;
3786 KKASSERT((chain->flags & HAMMER2_CHAIN_BMAPPED) == 0);
3787 hammer2_chain_modify(*parentp, mtid, 0, 0);
3788 tbase = hammer2_chain_base_and_count(*parentp, &tcount);
3789 hammer2_base_insert(*parentp, tbase, tcount, chain, obref);
3790 if (bcmp(obref, &chain->bref, sizeof(chain->bref))) {
3791 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD |
3792 HAMMER2_CHAIN_UPDATE);
3794 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3800 * Helper function for deleting chains.
3802 * The chain is removed from the live view (the RBTREE) as well as the parent's
3803 * blockmap. Both chain and its parent must be locked.
3805 * parent may not be errored. chain can be errored.
3808 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3809 hammer2_tid_t mtid, int flags,
3810 hammer2_blockref_t *obref)
3815 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3816 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3817 KKASSERT(chain->parent == parent);
3820 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3822 * Chain is blockmapped, so there must be a parent.
3823 * Atomically remove the chain from the parent and remove
3824 * the blockmap entry. The parent must be set modified
3825 * to remove the blockmap entry.
3827 hammer2_blockref_t *base;
3830 KKASSERT(parent != NULL);
3831 KKASSERT(parent->error == 0);
3832 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3833 error = hammer2_chain_modify(parent, mtid, 0, 0);
3838 * Calculate blockmap pointer
3840 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3841 hammer2_spin_ex(&chain->core.spin);
3842 hammer2_spin_ex(&parent->core.spin);
3844 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3845 atomic_add_int(&parent->core.live_count, -1);
3846 ++parent->core.generation;
3847 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3848 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3849 --parent->core.chain_count;
3850 chain->parent = NULL;
3852 switch(parent->bref.type) {
3853 case HAMMER2_BREF_TYPE_INODE:
3855 * Access the inode's block array. However, there
3856 * is no block array if the inode is flagged
3860 (parent->data->ipdata.meta.op_flags &
3861 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3863 &parent->data->ipdata.u.blockset.blockref[0];
3867 count = HAMMER2_SET_COUNT;
3869 case HAMMER2_BREF_TYPE_INDIRECT:
3870 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3872 base = &parent->data->npdata[0];
3875 count = parent->bytes / sizeof(hammer2_blockref_t);
3877 case HAMMER2_BREF_TYPE_VOLUME:
3878 base = &parent->data->voldata.
3879 sroot_blockset.blockref[0];
3880 count = HAMMER2_SET_COUNT;
3882 case HAMMER2_BREF_TYPE_FREEMAP:
3883 base = &parent->data->blkset.blockref[0];
3884 count = HAMMER2_SET_COUNT;
3889 panic("_hammer2_chain_delete_helper: "
3890 "unrecognized blockref type: %d",
3895 * delete blockmapped chain from its parent.
3897 * The parent is not affected by any statistics in chain
3898 * which are pending synchronization. That is, there is
3899 * nothing to undo in the parent since they have not yet
3900 * been incorporated into the parent.
3902 * The parent is affected by statistics stored in inodes.
3903 * Those have already been synchronized, so they must be
3904 * undone. XXX split update possible w/delete in middle?
3907 hammer2_base_delete(parent, base, count, chain, obref);
3909 hammer2_spin_unex(&parent->core.spin);
3910 hammer2_spin_unex(&chain->core.spin);
3911 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3913 * Chain is not blockmapped but a parent is present.
3914 * Atomically remove the chain from the parent. There is
3915 * no blockmap entry to remove.
3917 * Because chain was associated with a parent but not
3918 * synchronized, the chain's *_count_up fields contain
3919 * inode adjustment statistics which must be undone.
3921 hammer2_spin_ex(&chain->core.spin);
3922 hammer2_spin_ex(&parent->core.spin);
3923 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3924 atomic_add_int(&parent->core.live_count, -1);
3925 ++parent->core.generation;
3926 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3927 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3928 --parent->core.chain_count;
3929 chain->parent = NULL;
3930 hammer2_spin_unex(&parent->core.spin);
3931 hammer2_spin_unex(&chain->core.spin);
3934 * Chain is not blockmapped and has no parent. This
3935 * is a degenerate case.
3937 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3944 * Create an indirect block that covers one or more of the elements in the
3945 * current parent. Either returns the existing parent with no locking or
3946 * ref changes or returns the new indirect block locked and referenced
3947 * and leaving the original parent lock/ref intact as well.
3949 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3951 * The returned chain depends on where the specified key falls.
3953 * The key/keybits for the indirect mode only needs to follow three rules:
3955 * (1) That all elements underneath it fit within its key space and
3957 * (2) That all elements outside it are outside its key space.
3959 * (3) When creating the new indirect block any elements in the current
3960 * parent that fit within the new indirect block's keyspace must be
3961 * moved into the new indirect block.
3963 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3964 * keyspace the the current parent, but lookup/iteration rules will
3965 * ensure (and must ensure) that rule (2) for all parents leading up
3966 * to the nearest inode or the root volume header is adhered to. This
3967 * is accomplished by always recursing through matching keyspaces in
3968 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3970 * The current implementation calculates the current worst-case keyspace by
3971 * iterating the current parent and then divides it into two halves, choosing
3972 * whichever half has the most elements (not necessarily the half containing
3973 * the requested key).
3975 * We can also opt to use the half with the least number of elements. This
3976 * causes lower-numbered keys (aka logical file offsets) to recurse through
3977 * fewer indirect blocks and higher-numbered keys to recurse through more.
3978 * This also has the risk of not moving enough elements to the new indirect
3979 * block and being forced to create several indirect blocks before the element
3982 * Must be called with an exclusively locked parent.
3984 * NOTE: *errorp set to HAMMER_ERROR_* flags
3986 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3987 hammer2_key_t *keyp, int keybits,
3988 hammer2_blockref_t *base, int count);
3989 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3990 hammer2_key_t *keyp, int keybits,
3991 hammer2_blockref_t *base, int count,
3993 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3994 hammer2_key_t *keyp, int keybits,
3995 hammer2_blockref_t *base, int count,
3999 hammer2_chain_create_indirect(hammer2_chain_t *parent,
4000 hammer2_key_t create_key, int create_bits,
4001 hammer2_tid_t mtid, int for_type, int *errorp)
4004 hammer2_blockref_t *base;
4005 hammer2_blockref_t *bref;
4006 hammer2_blockref_t bsave;
4007 hammer2_blockref_t dummy;
4008 hammer2_chain_t *chain;
4009 hammer2_chain_t *ichain;
4010 hammer2_key_t key = create_key;
4011 hammer2_key_t key_beg;
4012 hammer2_key_t key_end;
4013 hammer2_key_t key_next;
4014 int keybits = create_bits;
4022 int maxloops = 300000;
4025 * Calculate the base blockref pointer or NULL if the chain
4026 * is known to be empty. We need to calculate the array count
4027 * for RB lookups either way.
4030 KKASSERT(hammer2_mtx_owned(&parent->lock));
4033 * Pre-modify the parent now to avoid having to deal with error
4034 * processing if we tried to later (in the middle of our loop).
4036 * We are going to be moving bref's around, the indirect blocks
4037 * cannot be in an initial state. Do not pass MODIFY_OPTDATA.
4039 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
4041 kprintf("hammer2_create_indirect: error %08x %s\n",
4042 *errorp, hammer2_error_str(*errorp));
4045 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
4047 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
4048 base = hammer2_chain_base_and_count(parent, &count);
4051 * How big should our new indirect block be? It has to be at least
4052 * as large as its parent for splits to work properly.
4054 * The freemap uses a specific indirect block size. The number of
4055 * levels are built dynamically and ultimately depend on the size
4056 * volume. Because freemap blocks are taken from the reserved areas
4057 * of the volume our goal is efficiency (fewer levels) and not so
4058 * much to save disk space.
4060 * The first indirect block level for a directory usually uses
4061 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
4062 * the hash mechanism, this typically gives us a nominal
4063 * 32 * 4 entries with one level of indirection.
4065 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
4066 * indirect blocks. The initial 4 entries in the inode gives us
4067 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
4068 * of indirection gives us 137GB, and so forth. H2 can support
4069 * huge file sizes but they are not typical, so we try to stick
4070 * with compactness and do not use a larger indirect block size.
4072 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
4073 * due to the way indirect blocks are created this usually winds
4074 * up being extremely inefficient for small files. Even though
4075 * 16KB requires more levels of indirection for very large files,
4076 * the 16KB records can be ganged together into 64KB DIOs.
4078 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4079 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4080 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
4081 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4082 if (parent->data->ipdata.meta.type ==
4083 HAMMER2_OBJTYPE_DIRECTORY)
4084 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
4086 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
4089 nbytes = HAMMER2_IND_BYTES_NOM;
4091 if (nbytes < count * sizeof(hammer2_blockref_t)) {
4092 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
4093 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
4094 nbytes = count * sizeof(hammer2_blockref_t);
4096 ncount = nbytes / sizeof(hammer2_blockref_t);
4099 * When creating an indirect block for a freemap node or leaf
4100 * the key/keybits must be fitted to static radix levels because
4101 * particular radix levels use particular reserved blocks in the
4104 * This routine calculates the key/radix of the indirect block
4105 * we need to create, and whether it is on the high-side or the
4109 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4110 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4111 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
4114 case HAMMER2_BREF_TYPE_DATA:
4115 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
4116 base, count, ncount);
4118 case HAMMER2_BREF_TYPE_DIRENT:
4119 case HAMMER2_BREF_TYPE_INODE:
4120 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
4121 base, count, ncount);
4124 panic("illegal indirect block for bref type %d", for_type);
4129 * Normalize the key for the radix being represented, keeping the
4130 * high bits and throwing away the low bits.
4132 key &= ~(((hammer2_key_t)1 << keybits) - 1);
4135 * Ok, create our new indirect block
4137 bzero(&dummy, sizeof(dummy));
4138 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4139 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4140 dummy.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
4142 dummy.type = HAMMER2_BREF_TYPE_INDIRECT;
4145 dummy.keybits = keybits;
4146 dummy.data_off = hammer2_getradix(nbytes);
4148 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
4149 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
4151 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy);
4152 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
4153 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
4154 /* ichain has one ref at this point */
4157 * We have to mark it modified to allocate its block, but use
4158 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
4159 * it won't be acted upon by the flush code.
4161 * XXX remove OPTDATA, we need a fully initialized indirect block to
4162 * be able to move the original blockref.
4164 *errorp = hammer2_chain_modify(ichain, mtid, 0, 0);
4166 kprintf("hammer2_alloc_indirect: error %08x %s\n",
4167 *errorp, hammer2_error_str(*errorp));
4168 hammer2_chain_unlock(ichain);
4169 hammer2_chain_drop(ichain);
4172 KKASSERT((ichain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4175 * Iterate the original parent and move the matching brefs into
4176 * the new indirect block.
4178 * XXX handle flushes.
4181 key_end = HAMMER2_KEY_MAX;
4182 key_next = 0; /* avoid gcc warnings */
4183 hammer2_spin_ex(&parent->core.spin);
4189 * Parent may have been modified, relocating its block array.
4190 * Reload the base pointer.
4192 base = hammer2_chain_base_and_count(parent, &count);
4194 if (++loops > 100000) {
4195 hammer2_spin_unex(&parent->core.spin);
4196 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
4197 reason, parent, base, count, key_next);
4201 * NOTE: spinlock stays intact, returned chain (if not NULL)
4202 * is not referenced or locked which means that we
4203 * cannot safely check its flagged / deletion status
4206 chain = hammer2_combined_find(parent, base, count,
4210 generation = parent->core.generation;
4213 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4216 * Skip keys that are not within the key/radix of the new
4217 * indirect block. They stay in the parent.
4219 if (rounddown2(key ^ bref->key, (hammer2_key_t)1 << keybits) != 0) {
4220 goto next_key_spinlocked;
4224 * Load the new indirect block by acquiring the related
4225 * chains (potentially from media as it might not be
4226 * in-memory). Then move it to the new parent (ichain).
4228 * chain is referenced but not locked. We must lock the
4229 * chain to obtain definitive state.
4234 * Use chain already present in the RBTREE
4236 hammer2_chain_ref(chain);
4237 hammer2_spin_unex(&parent->core.spin);
4238 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
4241 * Get chain for blockref element. _get returns NULL
4242 * on insertion race.
4244 hammer2_spin_unex(&parent->core.spin);
4245 chain = hammer2_chain_get(parent, generation, &bsave,
4246 HAMMER2_RESOLVE_NEVER);
4247 if (chain == NULL) {
4249 hammer2_spin_ex(&parent->core.spin);
4255 * This is always live so if the chain has been deleted
4256 * we raced someone and we have to retry.
4258 * NOTE: Lookups can race delete-duplicate because
4259 * delete-duplicate does not lock the parent's core
4260 * (they just use the spinlock on the core).
4262 * (note reversed logic for this one)
4264 if (bcmp(&bsave, &chain->bref, sizeof(bsave)) ||
4265 chain->parent != parent ||
4266 (chain->flags & HAMMER2_CHAIN_DELETED)) {
4267 hammer2_chain_unlock(chain);
4268 hammer2_chain_drop(chain);
4269 if (hammer2_debug & 0x0040) {
4270 kprintf("LOST PARENT RETRY "
4271 "RETRY (%p,%p)->%p %08x\n",
4272 parent, chain->parent, chain, chain->flags);
4274 hammer2_spin_ex(&parent->core.spin);
4279 * Shift the chain to the indirect block.
4281 * WARNING! No reason for us to load chain data, pass NOSTATS
4282 * to prevent delete/insert from trying to access
4283 * inode stats (and thus asserting if there is no
4284 * chain->data loaded).
4286 * WARNING! The (parent, chain) deletion may modify the parent
4287 * and invalidate the base pointer.
4289 * WARNING! Parent must already be marked modified, so we
4290 * can assume that chain_delete always suceeds.
4292 * WARNING! hammer2_chain_repchange() does not have to be
4293 * called (and doesn't work anyway because we are
4294 * only doing a partial shift). A recursion that is
4295 * in-progress can continue at the current parent
4296 * and will be able to properly find its next key.
4298 error = hammer2_chain_delete_obref(parent, chain, mtid, 0,
4300 KKASSERT(error == 0);
4301 hammer2_chain_rename_obref(&ichain, chain, mtid, 0, &bsave);
4302 hammer2_chain_unlock(chain);
4303 hammer2_chain_drop(chain);
4304 KKASSERT(parent->refs > 0);
4306 base = NULL; /* safety */
4307 hammer2_spin_ex(&parent->core.spin);
4308 next_key_spinlocked:
4309 if (--maxloops == 0)
4310 panic("hammer2_chain_create_indirect: maxloops");
4312 if (key_next == 0 || key_next > key_end)
4317 hammer2_spin_unex(&parent->core.spin);
4320 * Insert the new indirect block into the parent now that we've
4321 * cleared out some entries in the parent. We calculated a good
4322 * insertion index in the loop above (ichain->index).
4324 * We don't have to set UPDATE here because we mark ichain
4325 * modified down below (so the normal modified -> flush -> set-moved
4326 * sequence applies).
4328 * The insertion shouldn't race as this is a completely new block
4329 * and the parent is locked.
4331 base = NULL; /* safety, parent modify may change address */
4332 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
4333 KKASSERT(parent->core.live_count < count);
4334 hammer2_chain_insert(parent, ichain,
4335 HAMMER2_CHAIN_INSERT_SPIN |
4336 HAMMER2_CHAIN_INSERT_LIVE,
4340 * Make sure flushes propogate after our manual insertion.
4342 hammer2_chain_setflush(ichain);
4343 hammer2_chain_setflush(parent);
4346 * Figure out what to return.
4348 if (rounddown2(create_key ^ key, (hammer2_key_t)1 << keybits)) {
4350 * Key being created is outside the key range,
4351 * return the original parent.
4353 hammer2_chain_unlock(ichain);
4354 hammer2_chain_drop(ichain);
4357 * Otherwise its in the range, return the new parent.
4358 * (leave both the new and old parent locked).
4367 * Do maintenance on an indirect chain. Both parent and chain are locked.
4369 * Returns non-zero if (chain) is deleted, either due to being empty or
4370 * because its children were safely moved into the parent.
4373 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
4374 hammer2_chain_t *chain)
4376 hammer2_blockref_t *chain_base;
4377 hammer2_blockref_t *base;
4378 hammer2_blockref_t *bref;
4379 hammer2_blockref_t bsave;
4380 hammer2_key_t key_next;
4381 hammer2_key_t key_beg;
4382 hammer2_key_t key_end;
4383 hammer2_chain_t *sub;
4390 * Make sure we have an accurate live_count
4392 if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4393 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4394 base = &chain->data->npdata[0];
4395 count = chain->bytes / sizeof(hammer2_blockref_t);
4396 hammer2_chain_countbrefs(chain, base, count);
4400 * If the indirect block is empty we can delete it.
4401 * (ignore deletion error)
4403 if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4404 hammer2_chain_delete(parent, chain,
4405 chain->bref.modify_tid,
4406 HAMMER2_DELETE_PERMANENT);
4407 hammer2_chain_repchange(parent, chain);
4411 base = hammer2_chain_base_and_count(parent, &count);
4413 if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4414 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4415 hammer2_chain_countbrefs(parent, base, count);
4419 * Determine if we can collapse chain into parent, calculate
4420 * hysteresis for chain emptiness.
4422 if (parent->core.live_count + chain->core.live_count - 1 > count)
4424 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4425 if (chain->core.live_count > chain_count * 3 / 4)
4429 * Ok, theoretically we can collapse chain's contents into
4430 * parent. chain is locked, but any in-memory children of chain
4431 * are not. For this to work, we must be able to dispose of any
4432 * in-memory children of chain.
4434 * For now require that there are no in-memory children of chain.
4436 * WARNING! Both chain and parent must remain locked across this
4441 * Parent must be marked modified. Don't try to collapse it if we
4442 * can't mark it modified. Once modified, destroy chain to make room
4443 * and to get rid of what will be a conflicting key (this is included
4444 * in the calculation above). Finally, move the children of chain
4445 * into chain's parent.
4447 * This order creates an accounting problem for bref.embed.stats
4448 * because we destroy chain before we remove its children. Any
4449 * elements whos blockref is already synchronized will be counted
4450 * twice. To deal with the problem we clean out chain's stats prior
4453 error = hammer2_chain_modify(parent, 0, 0, 0);
4455 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4456 hammer2_error_str(error));
4459 error = hammer2_chain_modify(chain, chain->bref.modify_tid, 0, 0);
4461 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4462 hammer2_error_str(error));
4466 chain->bref.embed.stats.inode_count = 0;
4467 chain->bref.embed.stats.data_count = 0;
4468 error = hammer2_chain_delete(parent, chain,
4469 chain->bref.modify_tid,
4470 HAMMER2_DELETE_PERMANENT);
4471 KKASSERT(error == 0);
4474 * The combined_find call requires core.spin to be held. One would
4475 * think there wouldn't be any conflicts since we hold chain
4476 * exclusively locked, but the caching mechanism for 0-ref children
4477 * does not require a chain lock.
4479 hammer2_spin_ex(&chain->core.spin);
4483 key_end = HAMMER2_KEY_MAX;
4485 chain_base = &chain->data->npdata[0];
4486 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4487 sub = hammer2_combined_find(chain, chain_base, chain_count,
4491 generation = chain->core.generation;
4494 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4498 hammer2_chain_ref(sub);
4499 hammer2_spin_unex(&chain->core.spin);
4500 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4502 hammer2_spin_unex(&chain->core.spin);
4503 sub = hammer2_chain_get(chain, generation, &bsave,
4504 HAMMER2_RESOLVE_NEVER);
4506 hammer2_spin_ex(&chain->core.spin);
4510 if (bcmp(&bsave, &sub->bref, sizeof(bsave)) ||
4511 sub->parent != chain ||
4512 (sub->flags & HAMMER2_CHAIN_DELETED)) {
4513 hammer2_chain_unlock(sub);
4514 hammer2_chain_drop(sub);
4515 hammer2_spin_ex(&chain->core.spin);
4516 sub = NULL; /* safety */
4519 error = hammer2_chain_delete_obref(chain, sub,
4520 sub->bref.modify_tid, 0,
4522 KKASSERT(error == 0);
4523 hammer2_chain_rename_obref(&parent, sub,
4524 sub->bref.modify_tid,
4525 HAMMER2_INSERT_SAMEPARENT, &bsave);
4526 hammer2_chain_unlock(sub);
4527 hammer2_chain_drop(sub);
4528 hammer2_spin_ex(&chain->core.spin);
4534 hammer2_spin_unex(&chain->core.spin);
4536 hammer2_chain_repchange(parent, chain);
4542 * Freemap indirect blocks
4544 * Calculate the keybits and highside/lowside of the freemap node the
4545 * caller is creating.
4547 * This routine will specify the next higher-level freemap key/radix
4548 * representing the lowest-ordered set. By doing so, eventually all
4549 * low-ordered sets will be moved one level down.
4551 * We have to be careful here because the freemap reserves a limited
4552 * number of blocks for a limited number of levels. So we can't just
4553 * push indiscriminately.
4556 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4557 int keybits, hammer2_blockref_t *base, int count)
4559 hammer2_chain_t *chain;
4560 hammer2_blockref_t *bref;
4562 hammer2_key_t key_beg;
4563 hammer2_key_t key_end;
4564 hammer2_key_t key_next;
4567 int maxloops = 300000;
4575 * Calculate the range of keys in the array being careful to skip
4576 * slots which are overridden with a deletion.
4579 key_end = HAMMER2_KEY_MAX;
4580 hammer2_spin_ex(&parent->core.spin);
4583 if (--maxloops == 0) {
4584 panic("indkey_freemap shit %p %p:%d\n",
4585 parent, base, count);
4587 chain = hammer2_combined_find(parent, base, count,
4599 * Skip deleted chains.
4601 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4602 if (key_next == 0 || key_next > key_end)
4609 * Use the full live (not deleted) element for the scan
4610 * iteration. HAMMER2 does not allow partial replacements.
4612 * XXX should be built into hammer2_combined_find().
4614 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4616 if (keybits > bref->keybits) {
4618 keybits = bref->keybits;
4619 } else if (keybits == bref->keybits && bref->key < key) {
4626 hammer2_spin_unex(&parent->core.spin);
4629 * Return the keybits for a higher-level FREEMAP_NODE covering
4633 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4634 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4636 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4637 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4639 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4640 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4642 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4643 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4645 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4646 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4648 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4649 panic("hammer2_chain_indkey_freemap: level too high");
4652 panic("hammer2_chain_indkey_freemap: bad radix");
4661 * File indirect blocks
4663 * Calculate the key/keybits for the indirect block to create by scanning
4664 * existing keys. The key being created is also passed in *keyp and can be
4665 * inside or outside the indirect block. Regardless, the indirect block
4666 * must hold at least two keys in order to guarantee sufficient space.
4668 * We use a modified version of the freemap's fixed radix tree, but taylored
4669 * for file data. Basically we configure an indirect block encompassing the
4673 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4674 int keybits, hammer2_blockref_t *base, int count,
4677 hammer2_chain_t *chain;
4678 hammer2_blockref_t *bref;
4680 hammer2_key_t key_beg;
4681 hammer2_key_t key_end;
4682 hammer2_key_t key_next;
4686 int maxloops = 300000;
4694 * Calculate the range of keys in the array being careful to skip
4695 * slots which are overridden with a deletion.
4697 * Locate the smallest key.
4700 key_end = HAMMER2_KEY_MAX;
4701 hammer2_spin_ex(&parent->core.spin);
4704 if (--maxloops == 0) {
4705 panic("indkey_freemap shit %p %p:%d\n",
4706 parent, base, count);
4708 chain = hammer2_combined_find(parent, base, count,
4720 * Skip deleted chains.
4722 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4723 if (key_next == 0 || key_next > key_end)
4730 * Use the full live (not deleted) element for the scan
4731 * iteration. HAMMER2 does not allow partial replacements.
4733 * XXX should be built into hammer2_combined_find().
4735 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4737 if (keybits > bref->keybits) {
4739 keybits = bref->keybits;
4740 } else if (keybits == bref->keybits && bref->key < key) {
4747 hammer2_spin_unex(&parent->core.spin);
4750 * Calculate the static keybits for a higher-level indirect block
4751 * that contains the key.
4756 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4757 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4759 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4760 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4762 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4763 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4766 panic("bad ncount %d\n", ncount);
4772 * The largest radix that can be returned for an indirect block is
4773 * 63 bits. (The largest practical indirect block radix is actually
4774 * 62 bits because the top-level inode or volume root contains four
4775 * entries, but allow 63 to be returned).
4780 return keybits + nradix;
4786 * Directory indirect blocks.
4788 * Covers both the inode index (directory of inodes), and directory contents
4789 * (filenames hardlinked to inodes).
4791 * Because directory keys are hashed we generally try to cut the space in
4792 * half. We accomodate the inode index (which tends to have linearly
4793 * increasing inode numbers) by ensuring that the keyspace is at least large
4794 * enough to fill up the indirect block being created.
4797 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4798 int keybits, hammer2_blockref_t *base, int count,
4801 hammer2_blockref_t *bref;
4802 hammer2_chain_t *chain;
4803 hammer2_key_t key_beg;
4804 hammer2_key_t key_end;
4805 hammer2_key_t key_next;
4810 int maxloops = 300000;
4813 * NOTE: We can't take a shortcut here anymore for inodes because
4814 * the root directory can contain a mix of inodes and directory
4815 * entries (we used to just return 63 if parent->bref.type was
4816 * HAMMER2_BREF_TYPE_INODE.
4823 * Calculate the range of keys in the array being careful to skip
4824 * slots which are overridden with a deletion.
4827 key_end = HAMMER2_KEY_MAX;
4828 hammer2_spin_ex(&parent->core.spin);
4831 if (--maxloops == 0) {
4832 panic("indkey_freemap shit %p %p:%d\n",
4833 parent, base, count);
4835 chain = hammer2_combined_find(parent, base, count,
4849 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4850 if (key_next == 0 || key_next > key_end)
4857 * Use the full live (not deleted) element for the scan
4858 * iteration. HAMMER2 does not allow partial replacements.
4860 * XXX should be built into hammer2_combined_find().
4862 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4865 * Expand our calculated key range (key, keybits) to fit
4866 * the scanned key. nkeybits represents the full range
4867 * that we will later cut in half (two halves @ nkeybits - 1).
4870 if (nkeybits < bref->keybits) {
4871 if (bref->keybits > 64) {
4872 kprintf("bad bref chain %p bref %p\n",
4876 nkeybits = bref->keybits;
4878 while (nkeybits < 64 &&
4879 rounddown2(key ^ bref->key, (hammer2_key_t)1 << nkeybits) != 0) {
4884 * If the new key range is larger we have to determine
4885 * which side of the new key range the existing keys fall
4886 * under by checking the high bit, then collapsing the
4887 * locount into the hicount or vise-versa.
4889 if (keybits != nkeybits) {
4890 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4901 * The newly scanned key will be in the lower half or the
4902 * upper half of the (new) key range.
4904 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4913 hammer2_spin_unex(&parent->core.spin);
4914 bref = NULL; /* now invalid (safety) */
4917 * Adjust keybits to represent half of the full range calculated
4918 * above (radix 63 max) for our new indirect block.
4923 * Expand keybits to hold at least ncount elements. ncount will be
4924 * a power of 2. This is to try to completely fill leaf nodes (at
4925 * least for keys which are not hashes).
4927 * We aren't counting 'in' or 'out', we are counting 'high side'
4928 * and 'low side' based on the bit at (1LL << keybits). We want
4929 * everything to be inside in these cases so shift it all to
4930 * the low or high side depending on the new high bit.
4932 while (((hammer2_key_t)1 << keybits) < ncount) {
4934 if (key & ((hammer2_key_t)1 << keybits)) {
4943 if (hicount > locount)
4944 key |= (hammer2_key_t)1 << keybits;
4946 key &= ~(hammer2_key_t)1 << keybits;
4956 * Directory indirect blocks.
4958 * Covers both the inode index (directory of inodes), and directory contents
4959 * (filenames hardlinked to inodes).
4961 * Because directory keys are hashed we generally try to cut the space in
4962 * half. We accomodate the inode index (which tends to have linearly
4963 * increasing inode numbers) by ensuring that the keyspace is at least large
4964 * enough to fill up the indirect block being created.
4967 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4968 int keybits, hammer2_blockref_t *base, int count,
4971 hammer2_blockref_t *bref;
4972 hammer2_chain_t *chain;
4973 hammer2_key_t key_beg;
4974 hammer2_key_t key_end;
4975 hammer2_key_t key_next;
4980 int maxloops = 300000;
4983 * Shortcut if the parent is the inode. In this situation the
4984 * parent has 4+1 directory entries and we are creating an indirect
4985 * block capable of holding many more.
4987 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4996 * Calculate the range of keys in the array being careful to skip
4997 * slots which are overridden with a deletion.
5000 key_end = HAMMER2_KEY_MAX;
5001 hammer2_spin_ex(&parent->core.spin);
5004 if (--maxloops == 0) {
5005 panic("indkey_freemap shit %p %p:%d\n",
5006 parent, base, count);
5008 chain = hammer2_combined_find(parent, base, count,
5022 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
5023 if (key_next == 0 || key_next > key_end)
5030 * Use the full live (not deleted) element for the scan
5031 * iteration. HAMMER2 does not allow partial replacements.
5033 * XXX should be built into hammer2_combined_find().
5035 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
5038 * Expand our calculated key range (key, keybits) to fit
5039 * the scanned key. nkeybits represents the full range
5040 * that we will later cut in half (two halves @ nkeybits - 1).
5043 if (nkeybits < bref->keybits) {
5044 if (bref->keybits > 64) {
5045 kprintf("bad bref chain %p bref %p\n",
5049 nkeybits = bref->keybits;
5051 while (nkeybits < 64 &&
5052 (~(((hammer2_key_t)1 << nkeybits) - 1) &
5053 (key ^ bref->key)) != 0) {
5058 * If the new key range is larger we have to determine
5059 * which side of the new key range the existing keys fall
5060 * under by checking the high bit, then collapsing the
5061 * locount into the hicount or vise-versa.
5063 if (keybits != nkeybits) {
5064 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
5075 * The newly scanned key will be in the lower half or the
5076 * upper half of the (new) key range.
5078 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
5087 hammer2_spin_unex(&parent->core.spin);
5088 bref = NULL; /* now invalid (safety) */
5091 * Adjust keybits to represent half of the full range calculated
5092 * above (radix 63 max) for our new indirect block.
5097 * Expand keybits to hold at least ncount elements. ncount will be
5098 * a power of 2. This is to try to completely fill leaf nodes (at
5099 * least for keys which are not hashes).
5101 * We aren't counting 'in' or 'out', we are counting 'high side'
5102 * and 'low side' based on the bit at (1LL << keybits). We want
5103 * everything to be inside in these cases so shift it all to
5104 * the low or high side depending on the new high bit.
5106 while (((hammer2_key_t)1 << keybits) < ncount) {
5108 if (key & ((hammer2_key_t)1 << keybits)) {
5117 if (hicount > locount)
5118 key |= (hammer2_key_t)1 << keybits;
5120 key &= ~(hammer2_key_t)1 << keybits;
5130 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
5133 * Both parent and chain must be locked exclusively.
5135 * This function will modify the parent if the blockref requires removal
5136 * from the parent's block table.
5138 * This function is NOT recursive. Any entity already pushed into the
5139 * chain (such as an inode) may still need visibility into its contents,
5140 * as well as the ability to read and modify the contents. For example,
5141 * for an unlinked file which is still open.
5143 * Also note that the flusher is responsible for cleaning up empty
5147 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
5148 hammer2_tid_t mtid, int flags)
5152 KKASSERT(hammer2_mtx_owned(&chain->lock));
5155 * Nothing to do if already marked.
5157 * We need the spinlock on the core whos RBTREE contains chain
5158 * to protect against races.
5160 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5161 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5162 chain->parent == parent);
5163 error = _hammer2_chain_delete_helper(parent, chain,
5168 * Permanent deletions mark the chain as destroyed.
5170 * NOTE: We do not setflush the chain unless the deletion is
5171 * permanent, since the deletion of a chain does not actually
5172 * require it to be flushed.
5175 if (flags & HAMMER2_DELETE_PERMANENT) {
5176 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5177 hammer2_chain_setflush(chain);
5185 hammer2_chain_delete_obref(hammer2_chain_t *parent, hammer2_chain_t *chain,
5186 hammer2_tid_t mtid, int flags,
5187 hammer2_blockref_t *obref)
5191 KKASSERT(hammer2_mtx_owned(&chain->lock));
5194 * Nothing to do if already marked.
5196 * We need the spinlock on the core whos RBTREE contains chain
5197 * to protect against races.
5199 obref->type = HAMMER2_BREF_TYPE_EMPTY;
5200 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5201 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5202 chain->parent == parent);
5203 error = _hammer2_chain_delete_helper(parent, chain,
5204 mtid, flags, obref);
5208 * Permanent deletions mark the chain as destroyed.
5210 * NOTE: We do not setflush the chain unless the deletion is
5211 * permanent, since the deletion of a chain does not actually
5212 * require it to be flushed.
5215 if (flags & HAMMER2_DELETE_PERMANENT) {
5216 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5217 hammer2_chain_setflush(chain);
5225 * Returns the index of the nearest element in the blockref array >= elm.
5226 * Returns (count) if no element could be found.
5228 * Sets *key_nextp to the next key for loop purposes but does not modify
5229 * it if the next key would be higher than the current value of *key_nextp.
5230 * Note that *key_nexp can overflow to 0, which should be tested by the
5233 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5234 * held through the operation.
5237 hammer2_base_find(hammer2_chain_t *parent,
5238 hammer2_blockref_t *base, int count,
5239 hammer2_key_t *key_nextp,
5240 hammer2_key_t key_beg, hammer2_key_t key_end)
5242 hammer2_blockref_t *scan;
5243 hammer2_key_t scan_end;
5248 * Require the live chain's already have their core's counted
5249 * so we can optimize operations.
5251 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
5256 if (count == 0 || base == NULL)
5260 * Sequential optimization using parent->cache_index. This is
5261 * the most likely scenario.
5263 * We can avoid trailing empty entries on live chains, otherwise
5264 * we might have to check the whole block array.
5266 i = parent->cache_index; /* SMP RACE OK */
5268 limit = parent->core.live_zero;
5273 KKASSERT(i < count);
5279 while (i > 0 && (scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5280 scan->key > key_beg)) {
5284 parent->cache_index = i;
5287 * Search forwards, stop when we find a scan element which
5288 * encloses the key or until we know that there are no further
5292 if (scan->type != HAMMER2_BREF_TYPE_EMPTY) {
5293 scan_end = scan->key +
5294 ((hammer2_key_t)1 << scan->keybits) - 1;
5295 if (scan->key > key_beg || scan_end >= key_beg)
5304 parent->cache_index = i;
5308 scan_end = scan->key +
5309 ((hammer2_key_t)1 << scan->keybits);
5310 if (scan_end && (*key_nextp > scan_end ||
5312 *key_nextp = scan_end;
5320 * Do a combined search and return the next match either from the blockref
5321 * array or from the in-memory chain. Sets *bresp to the returned bref in
5322 * both cases, or sets it to NULL if the search exhausted. Only returns
5323 * a non-NULL chain if the search matched from the in-memory chain.
5325 * When no in-memory chain has been found and a non-NULL bref is returned
5329 * The returned chain is not locked or referenced. Use the returned bref
5330 * to determine if the search exhausted or not. Iterate if the base find
5331 * is chosen but matches a deleted chain.
5333 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5334 * held through the operation.
5337 hammer2_combined_find(hammer2_chain_t *parent,
5338 hammer2_blockref_t *base, int count,
5339 hammer2_key_t *key_nextp,
5340 hammer2_key_t key_beg, hammer2_key_t key_end,
5341 hammer2_blockref_t **bresp)
5343 hammer2_blockref_t *bref;
5344 hammer2_chain_t *chain;
5348 * Lookup in block array and in rbtree.
5350 *key_nextp = key_end + 1;
5351 i = hammer2_base_find(parent, base, count, key_nextp,
5353 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
5358 if (i == count && chain == NULL) {
5364 * Only chain matched.
5367 bref = &chain->bref;
5372 * Only blockref matched.
5374 if (chain == NULL) {
5380 * Both in-memory and blockref matched, select the nearer element.
5382 * If both are flush with the left-hand side or both are the
5383 * same distance away, select the chain. In this situation the
5384 * chain must have been loaded from the matching blockmap.
5386 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
5387 chain->bref.key == base[i].key) {
5388 KKASSERT(chain->bref.key == base[i].key);
5389 bref = &chain->bref;
5394 * Select the nearer key
5396 if (chain->bref.key < base[i].key) {
5397 bref = &chain->bref;
5404 * If the bref is out of bounds we've exhausted our search.
5407 if (bref->key > key_end) {
5417 * Locate the specified block array element and delete it. The element
5420 * The spin lock on the related chain must be held.
5422 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5423 * need to be adjusted when we commit the media change.
5426 hammer2_base_delete(hammer2_chain_t *parent,
5427 hammer2_blockref_t *base, int count,
5428 hammer2_chain_t *chain,
5429 hammer2_blockref_t *obref)
5431 hammer2_blockref_t *elm = &chain->bref;
5432 hammer2_blockref_t *scan;
5433 hammer2_key_t key_next;
5437 * Delete element. Expect the element to exist.
5439 * XXX see caller, flush code not yet sophisticated enough to prevent
5440 * re-flushed in some cases.
5442 key_next = 0; /* max range */
5443 i = hammer2_base_find(parent, base, count, &key_next,
5444 elm->key, elm->key);
5446 if (i == count || scan->type == HAMMER2_BREF_TYPE_EMPTY ||
5447 scan->key != elm->key ||
5448 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
5449 scan->keybits != elm->keybits)) {
5450 hammer2_spin_unex(&parent->core.spin);
5451 panic("delete base %p element not found at %d/%d elm %p\n",
5452 base, i, count, elm);
5457 * Update stats and zero the entry.
5459 * NOTE: Handle radix == 0 (0 bytes) case.
5461 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5462 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5463 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5465 switch(scan->type) {
5466 case HAMMER2_BREF_TYPE_INODE:
5467 --parent->bref.embed.stats.inode_count;
5469 case HAMMER2_BREF_TYPE_DATA:
5470 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5471 atomic_set_int(&chain->flags,
5472 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5474 if (parent->bref.leaf_count)
5475 --parent->bref.leaf_count;
5478 case HAMMER2_BREF_TYPE_INDIRECT:
5479 if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5480 parent->bref.embed.stats.data_count -=
5481 scan->embed.stats.data_count;
5482 parent->bref.embed.stats.inode_count -=
5483 scan->embed.stats.inode_count;
5485 if (scan->type == HAMMER2_BREF_TYPE_INODE)
5487 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5488 atomic_set_int(&chain->flags,
5489 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5491 if (parent->bref.leaf_count <= scan->leaf_count)
5492 parent->bref.leaf_count = 0;
5494 parent->bref.leaf_count -= scan->leaf_count;
5497 case HAMMER2_BREF_TYPE_DIRENT:
5498 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5499 atomic_set_int(&chain->flags,
5500 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5502 if (parent->bref.leaf_count)
5503 --parent->bref.leaf_count;
5511 bzero(scan, sizeof(*scan));
5514 * We can only optimize parent->core.live_zero for live chains.
5516 if (parent->core.live_zero == i + 1) {
5517 while (--i >= 0 && base[i].type == HAMMER2_BREF_TYPE_EMPTY)
5519 parent->core.live_zero = i + 1;
5523 * Clear appropriate blockmap flags in chain.
5525 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
5526 HAMMER2_CHAIN_BMAPUPD);
5530 * Insert the specified element. The block array must not already have the
5531 * element and must have space available for the insertion.
5533 * The spin lock on the related chain must be held.
5535 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5536 * need to be adjusted when we commit the media change.
5539 hammer2_base_insert(hammer2_chain_t *parent,
5540 hammer2_blockref_t *base, int count,
5541 hammer2_chain_t *chain, hammer2_blockref_t *elm)
5543 hammer2_key_t key_next;
5552 * Insert new element. Expect the element to not already exist
5553 * unless we are replacing it.
5555 * XXX see caller, flush code not yet sophisticated enough to prevent
5556 * re-flushed in some cases.
5558 key_next = 0; /* max range */
5559 i = hammer2_base_find(parent, base, count, &key_next,
5560 elm->key, elm->key);
5563 * Shortcut fill optimization, typical ordered insertion(s) may not
5566 KKASSERT(i >= 0 && i <= count);
5569 * Set appropriate blockmap flags in chain (if not NULL)
5572 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
5575 * Update stats and zero the entry
5577 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5578 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5579 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5582 case HAMMER2_BREF_TYPE_INODE:
5583 ++parent->bref.embed.stats.inode_count;
5585 case HAMMER2_BREF_TYPE_DATA:
5586 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5587 ++parent->bref.leaf_count;
5589 case HAMMER2_BREF_TYPE_INDIRECT:
5590 if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5591 parent->bref.embed.stats.data_count +=
5592 elm->embed.stats.data_count;
5593 parent->bref.embed.stats.inode_count +=
5594 elm->embed.stats.inode_count;
5596 if (elm->type == HAMMER2_BREF_TYPE_INODE)
5598 if (parent->bref.leaf_count + elm->leaf_count <
5599 HAMMER2_BLOCKREF_LEAF_MAX) {
5600 parent->bref.leaf_count += elm->leaf_count;
5602 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5605 case HAMMER2_BREF_TYPE_DIRENT:
5606 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5607 ++parent->bref.leaf_count;
5615 * We can only optimize parent->core.live_zero for live chains.
5617 if (i == count && parent->core.live_zero < count) {
5618 i = parent->core.live_zero++;
5623 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5624 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5625 hammer2_spin_unex(&parent->core.spin);
5626 panic("insert base %p overlapping elements at %d elm %p\n",
5631 * Try to find an empty slot before or after.
5635 while (j > 0 || k < count) {
5637 if (j >= 0 && base[j].type == HAMMER2_BREF_TYPE_EMPTY) {
5641 bcopy(&base[j+1], &base[j],
5642 (i - j - 1) * sizeof(*base));
5648 if (k < count && base[k].type == HAMMER2_BREF_TYPE_EMPTY) {
5649 bcopy(&base[i], &base[i+1],
5650 (k - i) * sizeof(hammer2_blockref_t));
5654 * We can only update parent->core.live_zero for live
5657 if (parent->core.live_zero <= k)
5658 parent->core.live_zero = k + 1;
5663 panic("hammer2_base_insert: no room!");
5670 for (l = 0; l < count; ++l) {
5671 if (base[l].type != HAMMER2_BREF_TYPE_EMPTY) {
5672 key_next = base[l].key +
5673 ((hammer2_key_t)1 << base[l].keybits) - 1;
5677 while (++l < count) {
5678 if (base[l].type != HAMMER2_BREF_TYPE_EMPTY) {
5679 if (base[l].key <= key_next)
5680 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5681 key_next = base[l].key +
5682 ((hammer2_key_t)1 << base[l].keybits) - 1;
5692 * Sort the blockref array for the chain. Used by the flush code to
5693 * sort the blockref[] array.
5695 * The chain must be exclusively locked AND spin-locked.
5697 typedef hammer2_blockref_t *hammer2_blockref_p;
5701 hammer2_base_sort_callback(const void *v1, const void *v2)
5703 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5704 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5707 * Make sure empty elements are placed at the end of the array
5709 if (bref1->type == HAMMER2_BREF_TYPE_EMPTY) {
5710 if (bref2->type == HAMMER2_BREF_TYPE_EMPTY)
5713 } else if (bref2->type == HAMMER2_BREF_TYPE_EMPTY) {
5720 if (bref1->key < bref2->key)
5722 if (bref1->key > bref2->key)
5728 hammer2_base_sort(hammer2_chain_t *chain)
5730 hammer2_blockref_t *base;
5733 switch(chain->bref.type) {
5734 case HAMMER2_BREF_TYPE_INODE:
5736 * Special shortcut for embedded data returns the inode
5737 * itself. Callers must detect this condition and access
5738 * the embedded data (the strategy code does this for us).
5740 * This is only applicable to regular files and softlinks.
5742 if (chain->data->ipdata.meta.op_flags &
5743 HAMMER2_OPFLAG_DIRECTDATA) {
5746 base = &chain->data->ipdata.u.blockset.blockref[0];
5747 count = HAMMER2_SET_COUNT;
5749 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5750 case HAMMER2_BREF_TYPE_INDIRECT:
5752 * Optimize indirect blocks in the INITIAL state to avoid
5755 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5756 base = &chain->data->npdata[0];
5757 count = chain->bytes / sizeof(hammer2_blockref_t);
5759 case HAMMER2_BREF_TYPE_VOLUME:
5760 base = &chain->data->voldata.sroot_blockset.blockref[0];
5761 count = HAMMER2_SET_COUNT;
5763 case HAMMER2_BREF_TYPE_FREEMAP:
5764 base = &chain->data->blkset.blockref[0];
5765 count = HAMMER2_SET_COUNT;
5768 kprintf("hammer2_chain_lookup: unrecognized "
5769 "blockref(A) type: %d",
5772 tsleep(&base, 0, "dead", 0);
5773 panic("hammer2_base_sort: unrecognized "
5774 "blockref(A) type: %d",
5776 base = NULL; /* safety */
5777 count = 0; /* safety */
5779 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5785 * Chain memory management
5788 hammer2_chain_wait(hammer2_chain_t *chain)
5790 tsleep(chain, 0, "chnflw", 1);
5793 const hammer2_media_data_t *
5794 hammer2_chain_rdata(hammer2_chain_t *chain)
5796 KKASSERT(chain->data != NULL);
5797 return (chain->data);
5800 hammer2_media_data_t *
5801 hammer2_chain_wdata(hammer2_chain_t *chain)
5803 KKASSERT(chain->data != NULL);
5804 return (chain->data);
5808 * Set the check data for a chain. This can be a heavy-weight operation
5809 * and typically only runs on-flush. For file data check data is calculated
5810 * when the logical buffers are flushed.
5813 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5815 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5817 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5818 case HAMMER2_CHECK_NONE:
5820 case HAMMER2_CHECK_DISABLED:
5822 case HAMMER2_CHECK_ISCSI32:
5823 chain->bref.check.iscsi32.value =
5824 hammer2_icrc32(bdata, chain->bytes);
5826 case HAMMER2_CHECK_XXHASH64:
5827 chain->bref.check.xxhash64.value =
5828 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5830 case HAMMER2_CHECK_SHA192:
5832 SHA256_CTX hash_ctx;
5834 uint8_t digest[SHA256_DIGEST_LENGTH];
5835 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5838 SHA256_Init(&hash_ctx);
5839 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5840 SHA256_Final(u.digest, &hash_ctx);
5841 u.digest64[2] ^= u.digest64[3];
5843 chain->bref.check.sha192.data,
5844 sizeof(chain->bref.check.sha192.data));
5847 case HAMMER2_CHECK_FREEMAP:
5848 chain->bref.check.freemap.icrc32 =
5849 hammer2_icrc32(bdata, chain->bytes);
5852 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5853 chain->bref.methods);
5859 * Characterize a failed check code and try to trace back to the inode.
5862 hammer2_characterize_failed_chain(hammer2_chain_t *chain, uint64_t check,
5865 hammer2_chain_t *lchain;
5866 hammer2_chain_t *ochain;
5869 did = krateprintf(&krate_h2chk,
5870 "chain %016jx.%02x (%s) meth=%02x CHECK FAIL "
5871 "(flags=%08x, bref/data ",
5872 chain->bref.data_off,
5874 hammer2_bref_type_str(&chain->bref),
5875 chain->bref.methods,
5881 kprintf("%08x/%08x)\n",
5882 chain->bref.check.iscsi32.value,
5885 kprintf("%016jx/%016jx)\n",
5886 chain->bref.check.xxhash64.value,
5891 * Run up the chains to try to find the governing inode so we
5894 * XXX This error reporting is not really MPSAFE
5898 while (chain && chain->bref.type != HAMMER2_BREF_TYPE_INODE) {
5900 chain = chain->parent;
5903 if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
5904 ((chain->bref.flags & HAMMER2_BREF_FLAG_PFSROOT) == 0 ||
5905 (lchain->bref.key & HAMMER2_DIRHASH_VISIBLE))) {
5906 kprintf(" Resides at/in inode %ld\n",
5908 } else if (chain && chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5909 kprintf(" Resides in inode index - CRITICAL!!!\n");
5911 kprintf(" Resides in root index - CRITICAL!!!\n");
5914 const char *pfsname = "UNKNOWN";
5918 for (i = 0; i < HAMMER2_MAXCLUSTER; ++i) {
5919 if (ochain->pmp->pfs_hmps[i] == ochain->hmp &&
5920 ochain->pmp->pfs_names[i]) {
5921 pfsname = ochain->pmp->pfs_names[i];
5926 kprintf(" In pfs %s on device %s\n",
5927 pfsname, ochain->hmp->devrepname);
5932 * Returns non-zero on success, 0 on failure.
5935 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5941 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5944 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5945 case HAMMER2_CHECK_NONE:
5948 case HAMMER2_CHECK_DISABLED:
5951 case HAMMER2_CHECK_ISCSI32:
5952 check32 = hammer2_icrc32(bdata, chain->bytes);
5953 r = (chain->bref.check.iscsi32.value == check32);
5955 hammer2_characterize_failed_chain(chain, check32, 32);
5957 hammer2_process_icrc32 += chain->bytes;
5959 case HAMMER2_CHECK_XXHASH64:
5960 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5961 r = (chain->bref.check.xxhash64.value == check64);
5963 hammer2_characterize_failed_chain(chain, check64, 64);
5965 hammer2_process_xxhash64 += chain->bytes;
5967 case HAMMER2_CHECK_SHA192:
5969 SHA256_CTX hash_ctx;
5971 uint8_t digest[SHA256_DIGEST_LENGTH];
5972 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5975 SHA256_Init(&hash_ctx);
5976 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5977 SHA256_Final(u.digest, &hash_ctx);
5978 u.digest64[2] ^= u.digest64[3];
5980 chain->bref.check.sha192.data,
5981 sizeof(chain->bref.check.sha192.data)) == 0) {
5985 krateprintf(&krate_h2chk,
5986 "chain %016jx.%02x meth=%02x "
5988 chain->bref.data_off,
5990 chain->bref.methods);
5994 case HAMMER2_CHECK_FREEMAP:
5995 r = (chain->bref.check.freemap.icrc32 ==
5996 hammer2_icrc32(bdata, chain->bytes));
6000 did = krateprintf(&krate_h2chk,
6001 "chain %016jx.%02x meth=%02x "
6003 chain->bref.data_off,
6005 chain->bref.methods);
6007 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
6008 chain->bref.check.freemap.icrc32,
6009 hammer2_icrc32(bdata, chain->bytes),
6012 kprintf("dio %p buf %016jx,%d "
6015 chain->dio->bp->b_loffset,
6016 chain->dio->bp->b_bufsize,
6018 chain->dio->bp->b_data);
6024 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
6025 chain->bref.methods);
6033 * Acquire the chain and parent representing the specified inode for the
6034 * device at the specified cluster index.
6036 * The flags passed in are LOOKUP flags, not RESOLVE flags.
6038 * If we are unable to locate the inode, HAMMER2_ERROR_EIO is returned and
6039 * *chainp will be NULL. *parentp may still be set error or not, or NULL
6040 * if the parent itself could not be resolved.
6042 * The caller may pass-in a locked *parentp and/or *chainp, or neither.
6043 * They will be unlocked and released by this function. The *parentp and
6044 * *chainp representing the located inode are returned locked.
6047 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
6048 int clindex, int flags,
6049 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
6051 hammer2_chain_t *parent;
6052 hammer2_chain_t *rchain;
6053 hammer2_key_t key_dummy;
6054 hammer2_inode_t *ip;
6058 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
6059 HAMMER2_RESOLVE_SHARED : 0;
6062 * Caller expects us to replace these.
6065 hammer2_chain_unlock(*chainp);
6066 hammer2_chain_drop(*chainp);
6070 hammer2_chain_unlock(*parentp);
6071 hammer2_chain_drop(*parentp);
6076 * Be very careful, this is a backend function and we CANNOT
6077 * lock any frontend inode structure we find. But we have to
6078 * look the inode up this way first in case it exists but is
6079 * detached from the radix tree.
6081 ip = hammer2_inode_lookup(pmp, inum);
6083 *chainp = hammer2_inode_chain_and_parent(ip, clindex,
6086 hammer2_inode_drop(ip);
6089 hammer2_chain_unlock(*chainp);
6090 hammer2_chain_drop(*chainp);
6093 hammer2_chain_unlock(*parentp);
6094 hammer2_chain_drop(*parentp);
6100 * Inodes hang off of the iroot (bit 63 is clear, differentiating
6101 * inodes from root directory entries in the key lookup).
6103 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
6106 rchain = hammer2_chain_lookup(&parent, &key_dummy,
6110 error = HAMMER2_ERROR_EIO;
6119 * Used by the bulkscan code to snapshot the synchronized storage for
6120 * a volume, allowing it to be scanned concurrently against normal
6124 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
6126 hammer2_chain_t *copy;
6128 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
6129 copy->data = kmalloc(sizeof(copy->data->voldata),
6132 hammer2_voldata_lock(hmp);
6133 copy->data->voldata = hmp->volsync;
6134 hammer2_voldata_unlock(hmp);
6140 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
6142 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
6143 KKASSERT(copy->data);
6144 kfree(copy->data, copy->hmp->mchain);
6146 atomic_add_long(&hammer2_chain_allocs, -1);
6147 hammer2_chain_drop(copy);
6151 * Returns non-zero if the chain (INODE or DIRENT) matches the
6155 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
6158 const hammer2_inode_data_t *ripdata;
6159 const hammer2_dirent_head_t *den;
6161 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
6162 ripdata = &chain->data->ipdata;
6163 if (ripdata->meta.name_len == name_len &&
6164 bcmp(ripdata->filename, name, name_len) == 0) {
6168 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
6169 chain->bref.embed.dirent.namlen == name_len) {
6170 den = &chain->bref.embed.dirent;
6171 if (name_len > sizeof(chain->bref.check.buf) &&
6172 bcmp(chain->data->buf, name, name_len) == 0) {
6175 if (name_len <= sizeof(chain->bref.check.buf) &&
6176 bcmp(chain->bref.check.buf, name, name_len) == 0) {