2 * Copyright (c) 2011-2018 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 hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain);
72 static hammer2_chain_t *hammer2_combined_find(
73 hammer2_chain_t *parent,
74 hammer2_blockref_t *base, int count,
75 hammer2_key_t *key_nextp,
76 hammer2_key_t key_beg, hammer2_key_t key_end,
77 hammer2_blockref_t **bresp);
79 static struct krate krate_h2me = { .freq = 1 };
82 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
83 * overlap in the RB trees. Deleted chains are moved from rbtree to either
86 * Chains in delete-duplicate sequences can always iterate through core_entry
87 * to locate the live version of the chain.
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
92 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
100 * Compare chains. Overlaps are not supposed to happen and catch
101 * any software issues early we count overlaps as a match.
103 c1_beg = chain1->bref.key;
104 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
105 c2_beg = chain2->bref.key;
106 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
108 if (c1_end < c2_beg) /* fully to the left */
110 if (c1_beg > c2_end) /* fully to the right */
112 return(0); /* overlap (must not cross edge boundary) */
116 * Assert that a chain has no media data associated with it.
119 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
121 KKASSERT(chain->dio == NULL);
122 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
123 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
125 panic("hammer2_assert_no_data: chain %p still has data", chain);
130 * Make a chain visible to the flusher. The flusher needs to be able to
131 * do flushes of subdirectory chains or single files so it does a top-down
132 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
133 * or UPDATE chains and flushes back up the chain to the volume root.
135 * This routine sets ONFLUSH upward until it hits the volume root. For
136 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
137 * Extra ONFLUSH flagging doesn't hurt the filesystem.
140 hammer2_chain_setflush(hammer2_chain_t *chain)
142 hammer2_chain_t *parent;
144 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 hammer2_spin_sh(&chain->core.spin);
146 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
147 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
148 if ((parent = chain->parent) == NULL)
150 hammer2_spin_sh(&parent->core.spin);
151 hammer2_spin_unsh(&chain->core.spin);
154 hammer2_spin_unsh(&chain->core.spin);
159 * Allocate a new disconnected chain element representing the specified
160 * bref. chain->refs is set to 1 and the passed bref is copied to
161 * chain->bref. chain->bytes is derived from the bref.
163 * chain->pmp inherits pmp unless the chain is an inode (other than the
166 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
169 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
170 hammer2_blockref_t *bref)
172 hammer2_chain_t *chain;
176 * Special case - radix of 0 indicates a chain that does not
177 * need a data reference (context is completely embedded in the
180 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
181 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
185 atomic_add_long(&hammer2_chain_allocs, 1);
188 * Construct the appropriate system structure.
191 case HAMMER2_BREF_TYPE_DIRENT:
192 case HAMMER2_BREF_TYPE_INODE:
193 case HAMMER2_BREF_TYPE_INDIRECT:
194 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
195 case HAMMER2_BREF_TYPE_DATA:
196 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
198 * Chain's are really only associated with the hmp but we
199 * maintain a pmp association for per-mount memory tracking
200 * purposes. The pmp can be NULL.
202 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
204 case HAMMER2_BREF_TYPE_VOLUME:
205 case HAMMER2_BREF_TYPE_FREEMAP:
207 * Only hammer2_chain_bulksnap() calls this function with these
210 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
214 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
219 * Initialize the new chain structure. pmp must be set to NULL for
220 * chains belonging to the super-root topology of a device mount.
222 if (pmp == hmp->spmp)
229 chain->bytes = bytes;
231 chain->flags = HAMMER2_CHAIN_ALLOCATED;
232 lockinit(&chain->diolk, "chdio", 0, 0);
235 * Set the PFS boundary flag if this chain represents a PFS root.
237 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
238 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
239 hammer2_chain_core_init(chain);
245 * Initialize a chain's core structure. This structure used to be allocated
246 * but is now embedded.
248 * The core is not locked. No additional refs on the chain are made.
249 * (trans) must not be NULL if (core) is not NULL.
252 hammer2_chain_core_init(hammer2_chain_t *chain)
255 * Fresh core under nchain (no multi-homing of ochain's
258 RB_INIT(&chain->core.rbtree); /* live chains */
259 hammer2_mtx_init(&chain->lock, "h2chain");
263 * Add a reference to a chain element, preventing its destruction.
265 * (can be called with spinlock held)
268 hammer2_chain_ref(hammer2_chain_t *chain)
270 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
272 * Just flag that the chain was used and should be recycled
273 * on the LRU if it encounters it later.
275 if (chain->flags & HAMMER2_CHAIN_ONLRU)
276 atomic_set_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
280 * REMOVED - reduces contention, lru_list is more heuristical
283 * 0->non-zero transition must ensure that chain is removed
286 * NOTE: Already holding lru_spin here so we cannot call
287 * hammer2_chain_ref() to get it off lru_list, do
290 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
291 hammer2_pfs_t *pmp = chain->pmp;
292 hammer2_spin_ex(&pmp->lru_spin);
293 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
294 atomic_add_int(&pmp->lru_count, -1);
295 atomic_clear_int(&chain->flags,
296 HAMMER2_CHAIN_ONLRU);
297 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
299 hammer2_spin_unex(&pmp->lru_spin);
306 * Ref a locked chain and force the data to be held across an unlock.
307 * Chain must be currently locked. The user of the chain who desires
308 * to release the hold must call hammer2_chain_lock_unhold() to relock
309 * and unhold the chain, then unlock normally, or may simply call
310 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
313 hammer2_chain_ref_hold(hammer2_chain_t *chain)
315 atomic_add_int(&chain->lockcnt, 1);
316 hammer2_chain_ref(chain);
320 * Insert the chain in the core rbtree.
322 * Normal insertions are placed in the live rbtree. Insertion of a deleted
323 * chain is a special case used by the flush code that is placed on the
324 * unstaged deleted list to avoid confusing the live view.
326 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
327 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
328 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
332 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
333 int flags, int generation)
335 hammer2_chain_t *xchain;
338 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
339 hammer2_spin_ex(&parent->core.spin);
342 * Interlocked by spinlock, check for race
344 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
345 parent->core.generation != generation) {
346 error = HAMMER2_ERROR_EAGAIN;
353 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
354 KASSERT(xchain == NULL,
355 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
356 chain, xchain, chain->bref.key));
357 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
358 chain->parent = parent;
359 ++parent->core.chain_count;
360 ++parent->core.generation; /* XXX incs for _get() too, XXX */
363 * We have to keep track of the effective live-view blockref count
364 * so the create code knows when to push an indirect block.
366 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
367 atomic_add_int(&parent->core.live_count, 1);
369 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
370 hammer2_spin_unex(&parent->core.spin);
375 * Drop the caller's reference to the chain. When the ref count drops to
376 * zero this function will try to disassociate the chain from its parent and
377 * deallocate it, then recursely drop the parent using the implied ref
378 * from the chain's chain->parent.
380 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
381 * races an acquisition by another cpu. Therefore we can loop if we are
382 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
383 * race against another drop.
385 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
387 static void hammer2_chain_lru_flush(hammer2_pfs_t *pmp);
390 hammer2_chain_drop(hammer2_chain_t *chain)
394 if (hammer2_debug & 0x200000)
397 KKASSERT(chain->refs > 0);
405 if (hammer2_mtx_ex_try(&chain->lock) == 0)
406 chain = hammer2_chain_lastdrop(chain, 0);
407 /* retry the same chain, or chain from lastdrop */
409 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
411 /* retry the same chain */
418 * Unhold a held and probably not-locked chain, ensure that the data is
419 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
420 * lock and then simply unlocking the chain.
423 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
429 lockcnt = chain->lockcnt;
432 if (atomic_cmpset_int(&chain->lockcnt,
433 lockcnt, lockcnt - 1)) {
436 } else if (hammer2_mtx_ex_try(&chain->lock) == 0) {
437 hammer2_chain_unlock(chain);
441 * This situation can easily occur on SMP due to
442 * the gap inbetween the 1->0 transition and the
443 * final unlock. We cannot safely block on the
444 * mutex because lockcnt might go above 1.
446 * XXX Sleep for one tick if it takes too long.
449 if (iter > 1000 + hz) {
450 kprintf("hammer2: h2race1 %p\n", chain);
453 tsleep(&iter, 0, "h2race1", 1);
458 hammer2_chain_drop(chain);
462 * Handles the (potential) last drop of chain->refs from 1->0. Called with
463 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
464 * possible against refs and lockcnt. We must dispose of the mutex on chain.
466 * This function returns an unlocked chain for recursive drop or NULL. It
467 * can return the same chain if it determines it has raced another ref.
471 * When two chains need to be recursively dropped we use the chain we
472 * would otherwise free to placehold the additional chain. It's a bit
473 * convoluted but we can't just recurse without potentially blowing out
476 * The chain cannot be freed if it has any children.
477 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
478 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
479 * Any dedup registration can remain intact.
481 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
485 hammer2_chain_lastdrop(hammer2_chain_t *chain, int depth)
489 hammer2_chain_t *parent;
490 hammer2_chain_t *rdrop;
497 * On last drop if there is no parent and data_off is good (at
498 * least does not represent the volume root), the modified chain
499 * is probably going to be destroyed. We have to make sure that
500 * the data area is not registered for dedup.
502 * XXX removed. In fact, we do not have to make sure that the
503 * data area is not registered for dedup. The data area
504 * can, in fact, still be used for dedup because it is
505 * still allocated in the freemap and the underlying I/O
506 * will still be flushed.
508 if (chain->parent == NULL &&
509 (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
510 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
512 hammer2_io_dedup_delete(hmp, chain->bref.type,
513 chain->bref.data_off, chain->bytes);
517 * We need chain's spinlock to interlock the sub-tree test.
518 * We already have chain's mutex, protecting chain->parent.
520 * Remember that chain->refs can be in flux.
522 hammer2_spin_ex(&chain->core.spin);
524 if (chain->parent != NULL) {
526 * If the chain has a parent the UPDATE bit prevents scrapping
527 * as the chain is needed to properly flush the parent. Try
528 * to complete the 1->0 transition and return NULL. Retry
529 * (return chain) if we are unable to complete the 1->0
530 * transition, else return NULL (nothing more to do).
532 * If the chain has a parent the MODIFIED bit prevents
535 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
537 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
538 HAMMER2_CHAIN_MODIFIED)) {
539 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
540 hammer2_spin_unex(&chain->core.spin);
542 dio = hammer2_chain_drop_data(chain, 0);
544 hammer2_io_bqrelse(&dio);
546 hammer2_chain_assert_no_data(chain);
547 hammer2_mtx_unlock(&chain->lock);
550 hammer2_spin_unex(&chain->core.spin);
551 hammer2_mtx_unlock(&chain->lock);
555 /* spinlock still held */
556 } else if (chain->bref.type == HAMMER2_BREF_TYPE_VOLUME ||
557 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP) {
559 * Retain the static vchain and fchain. Clear bits that
560 * are not relevant. Do not clear the MODIFIED bit,
561 * and certainly do not put it on the delayed-flush queue.
563 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
566 * The chain has no parent and can be flagged for destruction.
567 * Since it has no parent, UPDATE can also be cleared.
569 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
570 if (chain->flags & HAMMER2_CHAIN_UPDATE)
571 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
574 * If the chain has children we must still flush the chain.
575 * Any dedup is already handled by the underlying DIO, so
576 * we do not have to specifically flush it here.
578 * In the case where it has children, the DESTROY flag test
579 * in the flush code will prevent unnecessary flushes of
580 * MODIFIED chains that are not flagged DEDUP so don't worry
583 if (chain->core.chain_count) {
585 * Put on flushq (should ensure refs > 1), retry
588 hammer2_spin_unex(&chain->core.spin);
589 hammer2_delayed_flush(chain);
590 hammer2_mtx_unlock(&chain->lock);
592 return(chain); /* retry drop */
596 * Otherwise we can scrap the MODIFIED bit if it is set,
597 * and continue along the freeing path.
599 * Be sure to clean-out any dedup bits. Without a parent
600 * this chain will no longer be visible to the flush code.
601 * Easy check data_off to avoid the volume root.
603 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
604 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
605 atomic_add_long(&hammer2_count_modified_chains, -1);
607 hammer2_pfs_memory_wakeup(chain->pmp);
609 /* spinlock still held */
612 /* spinlock still held */
618 * If any children exist we must leave the chain intact with refs == 0.
619 * They exist because chains are retained below us which have refs or
620 * may require flushing.
622 * Retry (return chain) if we fail to transition the refs to 0, else
623 * return NULL indication nothing more to do.
625 * Chains with children are NOT put on the LRU list.
627 if (chain->core.chain_count) {
628 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
629 hammer2_spin_unex(&chain->core.spin);
630 hammer2_chain_assert_no_data(chain);
631 hammer2_mtx_unlock(&chain->lock);
634 hammer2_spin_unex(&chain->core.spin);
635 hammer2_mtx_unlock(&chain->lock);
639 /* spinlock still held */
640 /* no chains left under us */
643 * chain->core has no children left so no accessors can get to our
644 * chain from there. Now we have to lock the parent core to interlock
645 * remaining possible accessors that might bump chain's refs before
646 * we can safely drop chain's refs with intent to free the chain.
649 pmp = chain->pmp; /* can be NULL */
652 parent = chain->parent;
655 * WARNING! chain's spin lock is still held here, and other spinlocks
656 * will be acquired and released in the code below. We
657 * cannot be making fancy procedure calls!
661 * We can cache the chain if it is associated with a pmp
662 * and not flagged as being destroyed or requesting a full
663 * release. In this situation the chain is not removed
664 * from its parent, i.e. it can still be looked up.
666 * We intentionally do not cache DATA chains because these
667 * were likely used to load data into the logical buffer cache
668 * and will not be accessed again for some time.
671 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
673 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
675 hammer2_spin_ex(&parent->core.spin);
676 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
678 * 1->0 transition failed, retry. Do not drop
679 * the chain's data yet!
682 hammer2_spin_unex(&parent->core.spin);
683 hammer2_spin_unex(&chain->core.spin);
684 hammer2_mtx_unlock(&chain->lock);
693 dio = hammer2_chain_drop_data(chain, 1);
695 hammer2_chain_assert_no_data(chain);
698 * Make sure we are on the LRU list, clean up excessive
699 * LRU entries. We can only really drop one but there might
700 * be other entries that we can remove from the lru_list
703 * NOTE: HAMMER2_CHAIN_ONLRU may only be safely set when
704 * chain->core.spin AND pmp->lru_spin are held, but
705 * can be safely cleared only holding pmp->lru_spin.
707 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
708 hammer2_spin_ex(&pmp->lru_spin);
709 if ((chain->flags & HAMMER2_CHAIN_ONLRU) == 0) {
710 atomic_set_int(&chain->flags,
711 HAMMER2_CHAIN_ONLRU);
712 TAILQ_INSERT_TAIL(&pmp->lru_list,
714 atomic_add_int(&pmp->lru_count, 1);
716 if (pmp->lru_count < HAMMER2_LRU_LIMIT)
717 depth = 1; /* disable lru_list flush */
718 hammer2_spin_unex(&pmp->lru_spin);
720 /* disable lru flush */
725 hammer2_spin_unex(&parent->core.spin);
726 parent = NULL; /* safety */
728 hammer2_spin_unex(&chain->core.spin);
729 hammer2_mtx_unlock(&chain->lock);
732 hammer2_io_bqrelse(&dio);
736 * lru_list hysteresis (see above for depth overrides).
737 * Note that depth also prevents excessive lastdrop recursion.
740 hammer2_chain_lru_flush(pmp);
747 * Make sure we are not on the LRU list.
749 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
750 hammer2_spin_ex(&pmp->lru_spin);
751 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
752 atomic_add_int(&pmp->lru_count, -1);
753 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
754 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
756 hammer2_spin_unex(&pmp->lru_spin);
760 * Spinlock the parent and try to drop the last ref on chain.
761 * On success determine if we should dispose of the chain
762 * (remove the chain from its parent, etc).
764 * (normal core locks are top-down recursive but we define
765 * core spinlocks as bottom-up recursive, so this is safe).
768 hammer2_spin_ex(&parent->core.spin);
769 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
771 /* XXX remove, don't try to drop data on fail */
772 hammer2_spin_unex(&parent->core.spin);
773 dio = hammer2_chain_drop_data(chain, 0);
774 hammer2_spin_unex(&chain->core.spin);
776 hammer2_io_bqrelse(&dio);
779 * 1->0 transition failed, retry.
781 hammer2_spin_unex(&parent->core.spin);
782 hammer2_spin_unex(&chain->core.spin);
783 hammer2_mtx_unlock(&chain->lock);
789 * 1->0 transition successful, parent spin held to prevent
790 * new lookups, chain spinlock held to protect parent field.
791 * Remove chain from the parent.
793 * If the chain is being removed from the parent's btree but
794 * is not bmapped, we have to adjust live_count downward. If
795 * it is bmapped then the blockref is retained in the parent
796 * as is its associated live_count. This case can occur when
797 * a chain added to the topology is unable to flush and is
798 * then later deleted.
800 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
801 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) &&
802 (chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
803 atomic_add_int(&parent->core.live_count, -1);
805 RB_REMOVE(hammer2_chain_tree,
806 &parent->core.rbtree, chain);
807 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
808 --parent->core.chain_count;
809 chain->parent = NULL;
813 * If our chain was the last chain in the parent's core the
814 * core is now empty and its parent might have to be
815 * re-dropped if it has 0 refs.
817 if (parent->core.chain_count == 0) {
819 atomic_add_int(&rdrop->refs, 1);
821 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
825 hammer2_spin_unex(&parent->core.spin);
826 parent = NULL; /* safety */
832 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
834 * 1->0 transition failed, retry.
836 hammer2_spin_unex(&parent->core.spin);
837 hammer2_spin_unex(&chain->core.spin);
838 hammer2_mtx_unlock(&chain->lock);
845 * Successful 1->0 transition, no parent, no children... no way for
846 * anyone to ref this chain any more. We can clean-up and free it.
848 * We still have the core spinlock, and core's chain_count is 0.
849 * Any parent spinlock is gone.
851 hammer2_spin_unex(&chain->core.spin);
852 hammer2_chain_assert_no_data(chain);
853 hammer2_mtx_unlock(&chain->lock);
854 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
855 chain->core.chain_count == 0);
858 * All locks are gone, no pointers remain to the chain, finish
861 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
862 HAMMER2_CHAIN_MODIFIED)) == 0);
864 dio = hammer2_chain_drop_data(chain, 1);
866 hammer2_io_bqrelse(&dio);
870 * Once chain resources are gone we can use the now dead chain
871 * structure to placehold what might otherwise require a recursive
872 * drop, because we have potentially two things to drop and can only
873 * return one directly.
875 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
876 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
878 kfree(chain, hmp->mchain);
882 * Possible chaining loop when parent re-drop needed.
888 * Heuristical flush of the LRU, try to reduce the number of entries
889 * on the LRU to (HAMMER2_LRU_LIMIT * 2 / 3). This procedure is called
890 * only when lru_count exceeds HAMMER2_LRU_LIMIT.
894 hammer2_chain_lru_flush(hammer2_pfs_t *pmp)
896 hammer2_chain_t *chain;
900 hammer2_spin_ex(&pmp->lru_spin);
901 while (pmp->lru_count > HAMMER2_LRU_LIMIT * 2 / 3) {
903 * Pick a chain off the lru_list, just recycle it quickly
904 * if LRUHINT is set (the chain was ref'd but left on
905 * the lru_list, so cycle to the end).
907 chain = TAILQ_FIRST(&pmp->lru_list);
908 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
910 if (chain->flags & HAMMER2_CHAIN_LRUHINT) {
911 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_LRUHINT);
912 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
918 * Ok, we are off the LRU. We must adjust refs before we
919 * can safely clear the ONLRU flag.
921 atomic_add_int(&pmp->lru_count, -1);
922 if (atomic_cmpset_int(&chain->refs, 0, 1)) {
923 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
924 atomic_set_int(&chain->flags, HAMMER2_CHAIN_RELEASE);
927 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
930 hammer2_spin_unex(&pmp->lru_spin);
935 * If we picked a chain off the lru list we may be able to lastdrop
936 * it. Use a depth of 1 to prevent excessive lastdrop recursion.
946 if (hammer2_mtx_ex_try(&chain->lock) == 0)
947 chain = hammer2_chain_lastdrop(chain, 1);
948 /* retry the same chain, or chain from lastdrop */
950 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
952 /* retry the same chain */
960 * On last lock release.
962 static hammer2_io_t *
963 hammer2_chain_drop_data(hammer2_chain_t *chain)
967 if ((dio = chain->dio) != NULL) {
971 switch(chain->bref.type) {
972 case HAMMER2_BREF_TYPE_VOLUME:
973 case HAMMER2_BREF_TYPE_FREEMAP:
976 if (chain->data != NULL) {
977 hammer2_spin_unex(&chain->core.spin);
978 panic("chain data not null: "
979 "chain %p bref %016jx.%02x "
980 "refs %d parent %p dio %p data %p",
981 chain, chain->bref.data_off,
982 chain->bref.type, chain->refs,
984 chain->dio, chain->data);
986 KKASSERT(chain->data == NULL);
994 * Lock a referenced chain element, acquiring its data with I/O if necessary,
995 * and specify how you would like the data to be resolved.
997 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
999 * The lock is allowed to recurse, multiple locking ops will aggregate
1000 * the requested resolve types. Once data is assigned it will not be
1001 * removed until the last unlock.
1003 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
1004 * (typically used to avoid device/logical buffer
1005 * aliasing for data)
1007 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
1008 * the INITIAL-create state (indirect blocks only).
1010 * Do not resolve data elements for DATA chains.
1011 * (typically used to avoid device/logical buffer
1012 * aliasing for data)
1014 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
1016 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
1017 * it will be locked exclusive.
1019 * HAMMER2_RESOLVE_NONBLOCK- (flag) The chain is locked non-blocking. If
1020 * the lock fails, EAGAIN is returned.
1022 * NOTE: Embedded elements (volume header, inodes) are always resolved
1025 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
1026 * element will instantiate and zero its buffer, and flush it on
1029 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
1030 * so as not to instantiate a device buffer, which could alias against
1031 * a logical file buffer. However, if ALWAYS is specified the
1032 * device buffer will be instantiated anyway.
1034 * NOTE: The return value is always 0 unless NONBLOCK is specified, in which
1035 * case it can be either 0 or EAGAIN.
1037 * WARNING! This function blocks on I/O if data needs to be fetched. This
1038 * blocking can run concurrent with other compatible lock holders
1039 * who do not need data returning. The lock is not upgraded to
1040 * exclusive during a data fetch, a separate bit is used to
1041 * interlock I/O. However, an exclusive lock holder can still count
1042 * on being interlocked against an I/O fetch managed by a shared
1046 hammer2_chain_lock(hammer2_chain_t *chain, int how)
1048 KKASSERT(chain->refs > 0);
1050 if (how & HAMMER2_RESOLVE_NONBLOCK) {
1052 * For non-blocking operation attempt to get the lock
1053 * before bumping lockcnt, just so we don't have to deal
1054 * with dropping lockcnt (and dealing with the underlying
1057 * NOTE: LOCKAGAIN must always succeed without blocking.
1059 if (how & HAMMER2_RESOLVE_SHARED) {
1060 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1061 hammer2_mtx_sh_again(&chain->lock);
1063 if (hammer2_mtx_sh_try(&chain->lock) != 0)
1067 if (hammer2_mtx_ex_try(&chain->lock) != 0)
1070 atomic_add_int(&chain->lockcnt, 1);
1071 ++curthread->td_tracker;
1074 * Lock the element. Recursive locks are allowed. lockcnt
1075 * ensures that data is left intact.
1077 atomic_add_int(&chain->lockcnt, 1);
1080 * Get the appropriate lock. If LOCKAGAIN is flagged with
1081 * SHARED the caller expects a shared lock to already be
1082 * present and we are giving it another ref. This case must
1083 * importantly not block if there is a pending exclusive lock
1086 if (how & HAMMER2_RESOLVE_SHARED) {
1087 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
1088 hammer2_mtx_sh_again(&chain->lock);
1090 hammer2_mtx_sh(&chain->lock);
1093 hammer2_mtx_ex(&chain->lock);
1095 ++curthread->td_tracker;
1099 * If we already have a valid data pointer make sure the data is
1100 * synchronized to the current cpu, and then no further action is
1105 hammer2_io_bkvasync(chain->dio);
1110 * Do we have to resolve the data? This is generally only
1111 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
1112 * Other BREF types expects the data to be there.
1114 switch(how & HAMMER2_RESOLVE_MASK) {
1115 case HAMMER2_RESOLVE_NEVER:
1117 case HAMMER2_RESOLVE_MAYBE:
1118 if (chain->flags & HAMMER2_CHAIN_INITIAL)
1120 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1123 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
1125 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
1129 case HAMMER2_RESOLVE_ALWAYS:
1135 * Caller requires data
1137 hammer2_chain_load_data(chain);
1143 * Lock the chain, retain the hold, and drop the data persistence count.
1144 * The data should remain valid because we never transitioned lockcnt
1148 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
1150 hammer2_chain_lock(chain, how);
1151 atomic_add_int(&chain->lockcnt, -1);
1156 * Downgrade an exclusive chain lock to a shared chain lock.
1158 * NOTE: There is no upgrade equivalent due to the ease of
1159 * deadlocks in that direction.
1162 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1164 hammer2_mtx_downgrade(&chain->lock);
1169 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1170 * may be of any type.
1172 * Once chain->data is set it cannot be disposed of until all locks are
1175 * Make sure the data is synchronized to the current cpu.
1178 hammer2_chain_load_data(hammer2_chain_t *chain)
1180 hammer2_blockref_t *bref;
1187 * Degenerate case, data already present, or chain has no media
1188 * reference to load.
1192 hammer2_io_bkvasync(chain->dio);
1195 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0)
1199 KKASSERT(hmp != NULL);
1202 * Gain the IOINPROG bit, interlocked block.
1208 oflags = chain->flags;
1210 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1211 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1212 tsleep_interlock(&chain->flags, 0);
1213 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1214 tsleep(&chain->flags, PINTERLOCKED,
1219 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1220 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1228 * We own CHAIN_IOINPROG
1230 * Degenerate case if we raced another load.
1234 hammer2_io_bkvasync(chain->dio);
1239 * We must resolve to a device buffer, either by issuing I/O or
1240 * by creating a zero-fill element. We do not mark the buffer
1241 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1242 * API must still be used to do that).
1244 * The device buffer is variable-sized in powers of 2 down
1245 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1246 * chunk always contains buffers of the same size. (XXX)
1248 * The minimum physical IO size may be larger than the variable
1251 bref = &chain->bref;
1254 * The getblk() optimization can only be used on newly created
1255 * elements if the physical block size matches the request.
1257 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1258 error = hammer2_io_new(hmp, bref->type,
1259 bref->data_off, chain->bytes,
1262 error = hammer2_io_bread(hmp, bref->type,
1263 bref->data_off, chain->bytes,
1265 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1268 chain->error = HAMMER2_ERROR_EIO;
1269 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1270 (intmax_t)bref->data_off, error);
1271 hammer2_io_bqrelse(&chain->dio);
1277 * This isn't perfect and can be ignored on OSs which do not have
1278 * an indication as to whether a buffer is coming from cache or
1279 * if I/O was actually issued for the read. TESTEDGOOD will work
1280 * pretty well without the B_IOISSUED logic because chains are
1281 * cached, but in that situation (without B_IOISSUED) it will not
1282 * detect whether a re-read via I/O is corrupted verses the original
1285 * We can't re-run the CRC on every fresh lock. That would be
1286 * insanely expensive.
1288 * If the underlying kernel buffer covers the entire chain we can
1289 * use the B_IOISSUED indication to determine if we have to re-run
1290 * the CRC on chain data for chains that managed to stay cached
1291 * across the kernel disposal of the original buffer.
1293 if ((dio = chain->dio) != NULL && dio->bp) {
1294 struct buf *bp = dio->bp;
1296 if (dio->psize == chain->bytes &&
1297 (bp->b_flags & B_IOISSUED)) {
1298 atomic_clear_int(&chain->flags,
1299 HAMMER2_CHAIN_TESTEDGOOD);
1300 bp->b_flags &= ~B_IOISSUED;
1305 * NOTE: A locked chain's data cannot be modified without first
1306 * calling hammer2_chain_modify().
1310 * Clear INITIAL. In this case we used io_new() and the buffer has
1311 * been zero'd and marked dirty.
1313 * NOTE: hammer2_io_data() call issues bkvasync()
1315 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1317 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1318 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1319 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1320 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1322 * check data not currently synchronized due to
1323 * modification. XXX assumes data stays in the buffer
1324 * cache, which might not be true (need biodep on flush
1325 * to calculate crc? or simple crc?).
1327 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1328 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1329 chain->error = HAMMER2_ERROR_CHECK;
1331 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1336 * Setup the data pointer, either pointing it to an embedded data
1337 * structure and copying the data from the buffer, or pointing it
1340 * The buffer is not retained when copying to an embedded data
1341 * structure in order to avoid potential deadlocks or recursions
1342 * on the same physical buffer.
1344 * WARNING! Other threads can start using the data the instant we
1345 * set chain->data non-NULL.
1347 switch (bref->type) {
1348 case HAMMER2_BREF_TYPE_VOLUME:
1349 case HAMMER2_BREF_TYPE_FREEMAP:
1351 * Copy data from bp to embedded buffer
1353 panic("hammer2_chain_load_data: unresolved volume header");
1355 case HAMMER2_BREF_TYPE_DIRENT:
1356 KKASSERT(chain->bytes != 0);
1358 case HAMMER2_BREF_TYPE_INODE:
1359 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1360 case HAMMER2_BREF_TYPE_INDIRECT:
1361 case HAMMER2_BREF_TYPE_DATA:
1362 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1365 * Point data at the device buffer and leave dio intact.
1367 chain->data = (void *)bdata;
1372 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1379 oflags = chain->flags;
1380 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1381 HAMMER2_CHAIN_IOSIGNAL);
1382 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1383 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1384 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1385 wakeup(&chain->flags);
1392 * Unlock and deref a chain element.
1394 * Remember that the presence of children under chain prevent the chain's
1395 * destruction but do not add additional references, so the dio will still
1399 hammer2_chain_unlock(hammer2_chain_t *chain)
1405 --curthread->td_tracker;
1408 * If multiple locks are present (or being attempted) on this
1409 * particular chain we can just unlock, drop refs, and return.
1411 * Otherwise fall-through on the 1->0 transition.
1414 lockcnt = chain->lockcnt;
1415 KKASSERT(lockcnt > 0);
1418 if (atomic_cmpset_int(&chain->lockcnt,
1419 lockcnt, lockcnt - 1)) {
1420 hammer2_mtx_unlock(&chain->lock);
1423 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1424 /* while holding the mutex exclusively */
1425 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1429 * This situation can easily occur on SMP due to
1430 * the gap inbetween the 1->0 transition and the
1431 * final unlock. We cannot safely block on the
1432 * mutex because lockcnt might go above 1.
1434 * XXX Sleep for one tick if it takes too long.
1436 if (++iter > 1000) {
1437 if (iter > 1000 + hz) {
1438 kprintf("hammer2: h2race2 %p\n", chain);
1441 tsleep(&iter, 0, "h2race2", 1);
1449 * Last unlock / mutex upgraded to exclusive. Drop the data
1452 dio = hammer2_chain_drop_data(chain);
1454 hammer2_io_bqrelse(&dio);
1455 hammer2_mtx_unlock(&chain->lock);
1459 * Unlock and hold chain data intact
1462 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1464 atomic_add_int(&chain->lockcnt, 1);
1465 hammer2_chain_unlock(chain);
1469 * Helper to obtain the blockref[] array base and count for a chain.
1471 * XXX Not widely used yet, various use cases need to be validated and
1472 * converted to use this function.
1475 hammer2_blockref_t *
1476 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1478 hammer2_blockref_t *base;
1481 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1484 switch(parent->bref.type) {
1485 case HAMMER2_BREF_TYPE_INODE:
1486 count = HAMMER2_SET_COUNT;
1488 case HAMMER2_BREF_TYPE_INDIRECT:
1489 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1490 count = parent->bytes / sizeof(hammer2_blockref_t);
1492 case HAMMER2_BREF_TYPE_VOLUME:
1493 count = HAMMER2_SET_COUNT;
1495 case HAMMER2_BREF_TYPE_FREEMAP:
1496 count = HAMMER2_SET_COUNT;
1499 panic("hammer2_chain_create_indirect: "
1500 "unrecognized blockref type: %d",
1506 switch(parent->bref.type) {
1507 case HAMMER2_BREF_TYPE_INODE:
1508 base = &parent->data->ipdata.u.blockset.blockref[0];
1509 count = HAMMER2_SET_COUNT;
1511 case HAMMER2_BREF_TYPE_INDIRECT:
1512 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1513 base = &parent->data->npdata[0];
1514 count = parent->bytes / sizeof(hammer2_blockref_t);
1516 case HAMMER2_BREF_TYPE_VOLUME:
1517 base = &parent->data->voldata.
1518 sroot_blockset.blockref[0];
1519 count = HAMMER2_SET_COUNT;
1521 case HAMMER2_BREF_TYPE_FREEMAP:
1522 base = &parent->data->blkset.blockref[0];
1523 count = HAMMER2_SET_COUNT;
1526 panic("hammer2_chain_create_indirect: "
1527 "unrecognized blockref type: %d",
1539 * This counts the number of live blockrefs in a block array and
1540 * also calculates the point at which all remaining blockrefs are empty.
1541 * This routine can only be called on a live chain.
1543 * Caller holds the chain locked, but possibly with a shared lock. We
1544 * must use an exclusive spinlock to prevent corruption.
1546 * NOTE: Flag is not set until after the count is complete, allowing
1547 * callers to test the flag without holding the spinlock.
1549 * NOTE: If base is NULL the related chain is still in the INITIAL
1550 * state and there are no blockrefs to count.
1552 * NOTE: live_count may already have some counts accumulated due to
1553 * creation and deletion and could even be initially negative.
1556 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1557 hammer2_blockref_t *base, int count)
1559 hammer2_spin_ex(&chain->core.spin);
1560 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1562 while (--count >= 0) {
1563 if (base[count].type)
1566 chain->core.live_zero = count + 1;
1567 while (count >= 0) {
1568 if (base[count].type)
1569 atomic_add_int(&chain->core.live_count,
1574 chain->core.live_zero = 0;
1576 /* else do not modify live_count */
1577 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1579 hammer2_spin_unex(&chain->core.spin);
1583 * Resize the chain's physical storage allocation in-place. This function does
1584 * not usually adjust the data pointer and must be followed by (typically) a
1585 * hammer2_chain_modify() call to copy any old data over and adjust the
1588 * Chains can be resized smaller without reallocating the storage. Resizing
1589 * larger will reallocate the storage. Excess or prior storage is reclaimed
1590 * asynchronously at a later time.
1592 * An nradix value of 0 is special-cased to mean that the storage should
1593 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1596 * Must be passed an exclusively locked parent and chain.
1598 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1599 * to avoid instantiating a device buffer that conflicts with the vnode data
1600 * buffer. However, because H2 can compress or encrypt data, the chain may
1601 * have a dio assigned to it in those situations, and they do not conflict.
1603 * XXX return error if cannot resize.
1606 hammer2_chain_resize(hammer2_chain_t *chain,
1607 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1608 int nradix, int flags)
1618 * Only data and indirect blocks can be resized for now.
1619 * (The volu root, inodes, and freemap elements use a fixed size).
1621 KKASSERT(chain != &hmp->vchain);
1622 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1623 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1624 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1627 * Nothing to do if the element is already the proper size
1629 obytes = chain->bytes;
1630 nbytes = (nradix) ? (1U << nradix) : 0;
1631 if (obytes == nbytes)
1632 return (chain->error);
1635 * Make sure the old data is instantiated so we can copy it. If this
1636 * is a data block, the device data may be superfluous since the data
1637 * might be in a logical block, but compressed or encrypted data is
1640 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1642 error = hammer2_chain_modify(chain, mtid, dedup_off, 0);
1647 * Relocate the block, even if making it smaller (because different
1648 * block sizes may be in different regions).
1650 * NOTE: Operation does not copy the data and may only be used
1651 * to resize data blocks in-place, or directory entry blocks
1652 * which are about to be modified in some manner.
1654 error = hammer2_freemap_alloc(chain, nbytes);
1658 chain->bytes = nbytes;
1661 * We don't want the followup chain_modify() to try to copy data
1662 * from the old (wrong-sized) buffer. It won't know how much to
1663 * copy. This case should only occur during writes when the
1664 * originator already has the data to write in-hand.
1667 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1668 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1669 hammer2_io_brelse(&chain->dio);
1672 return (chain->error);
1676 * Set the chain modified so its data can be changed by the caller, or
1677 * install deduplicated data. The caller must call this routine for each
1678 * set of modifications it makes, even if the chain is already flagged
1681 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1682 * is a CLC (cluster level change) field and is not updated by parent
1683 * propagation during a flush.
1685 * Returns an appropriate HAMMER2_ERROR_* code, which will generally reflect
1686 * chain->error except for HAMMER2_ERROR_ENOSPC. If the allocation fails
1687 * due to no space available, HAMMER2_ERROR_ENOSPC is returned and the chain
1688 * remains unmodified with its old data ref intact and chain->error
1693 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1694 * even if the chain is still flagged MODIFIED. In this case the chain's
1695 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1697 * If the caller passes a non-zero dedup_off we will use it to assign the
1698 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1699 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1700 * must not modify the data content upon return.
1703 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1704 hammer2_off_t dedup_off, int flags)
1706 hammer2_blockref_t obref;
1717 obref = chain->bref;
1718 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1721 * Data is not optional for freemap chains (we must always be sure
1722 * to copy the data on COW storage allocations).
1724 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1725 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1726 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1727 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1731 * Data must be resolved if already assigned, unless explicitly
1732 * flagged otherwise. If we cannot safety load the data the
1733 * modification fails and we return early.
1735 if (chain->data == NULL && chain->bytes != 0 &&
1736 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1737 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1738 hammer2_chain_load_data(chain);
1740 return (chain->error);
1745 * Set MODIFIED to indicate that the chain has been modified. A new
1746 * allocation is required when modifying a chain.
1748 * Set UPDATE to ensure that the blockref is updated in the parent.
1750 * If MODIFIED is already set determine if we can reuse the assigned
1751 * data block or if we need a new data block.
1753 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1755 * Must set modified bit.
1757 atomic_add_long(&hammer2_count_modified_chains, 1);
1758 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1759 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1763 * We may be able to avoid a copy-on-write if the chain's
1764 * check mode is set to NONE and the chain's current
1765 * modify_tid is beyond the last explicit snapshot tid.
1767 * This implements HAMMER2's overwrite-in-place feature.
1769 * NOTE! This data-block cannot be used as a de-duplication
1770 * source when the check mode is set to NONE.
1772 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1773 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1774 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1775 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1776 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1777 HAMMER2_CHECK_NONE &&
1779 chain->bref.modify_tid >
1780 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1782 * Sector overwrite allowed.
1787 * Sector overwrite not allowed, must copy-on-write.
1791 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1793 * If the modified chain was registered for dedup we need
1794 * a new allocation. This only happens for delayed-flush
1795 * chains (i.e. which run through the front-end buffer
1802 * Already flagged modified, no new allocation is needed.
1809 * Flag parent update required.
1811 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1812 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1819 * The XOP code returns held but unlocked focus chains. This
1820 * prevents the chain from being destroyed but does not prevent
1821 * it from being modified. diolk is used to interlock modifications
1822 * against XOP frontend accesses to the focus.
1824 * This allows us to theoretically avoid deadlocking the frontend
1825 * if one of the backends lock up by not formally locking the
1826 * focused chain in the frontend. In addition, the synchronization
1827 * code relies on this mechanism to avoid deadlocking concurrent
1828 * synchronization threads.
1830 lockmgr(&chain->diolk, LK_EXCLUSIVE);
1833 * The modification or re-modification requires an allocation and
1834 * possible COW. If an error occurs, the previous content and data
1835 * reference is retained and the modification fails.
1837 * If dedup_off is non-zero, the caller is requesting a deduplication
1838 * rather than a modification. The MODIFIED bit is not set and the
1839 * data offset is set to the deduplication offset. The data cannot
1842 * NOTE: The dedup offset is allowed to be in a partially free state
1843 * and we must be sure to reset it to a fully allocated state
1844 * to force two bulkfree passes to free it again.
1846 * NOTE: Only applicable when chain->bytes != 0.
1848 * XXX can a chain already be marked MODIFIED without a data
1849 * assignment? If not, assert here instead of testing the case.
1851 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1853 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1857 * NOTE: We do not have to remove the dedup
1858 * registration because the area is still
1859 * allocated and the underlying DIO will
1863 chain->bref.data_off = dedup_off;
1864 chain->bytes = 1 << (dedup_off &
1865 HAMMER2_OFF_MASK_RADIX);
1867 atomic_clear_int(&chain->flags,
1868 HAMMER2_CHAIN_MODIFIED);
1869 atomic_add_long(&hammer2_count_modified_chains,
1872 hammer2_pfs_memory_wakeup(chain->pmp);
1873 hammer2_freemap_adjust(hmp, &chain->bref,
1874 HAMMER2_FREEMAP_DORECOVER);
1875 atomic_set_int(&chain->flags,
1876 HAMMER2_CHAIN_DEDUPABLE);
1878 error = hammer2_freemap_alloc(chain,
1880 atomic_clear_int(&chain->flags,
1881 HAMMER2_CHAIN_DEDUPABLE);
1887 * Stop here if error. We have to undo any flag bits we might
1892 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1893 atomic_add_long(&hammer2_count_modified_chains, -1);
1895 hammer2_pfs_memory_wakeup(chain->pmp);
1898 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1900 lockmgr(&chain->diolk, LK_RELEASE);
1906 * Update mirror_tid and modify_tid. modify_tid is only updated
1907 * if not passed as zero (during flushes, parent propagation passes
1910 * NOTE: chain->pmp could be the device spmp.
1912 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1914 chain->bref.modify_tid = mtid;
1917 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1918 * requires updating as well as to tell the delete code that the
1919 * chain's blockref might not exactly match (in terms of physical size
1920 * or block offset) the one in the parent's blocktable. The base key
1921 * of course will still match.
1923 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1924 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1927 * Short-cut data blocks which the caller does not need an actual
1928 * data reference to (aka OPTDATA), as long as the chain does not
1929 * already have a data pointer to the data. This generally means
1930 * that the modifications are being done via the logical buffer cache.
1931 * The INITIAL flag relates only to the device data buffer and thus
1932 * remains unchange in this situation.
1934 * This code also handles bytes == 0 (most dirents).
1936 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1937 (flags & HAMMER2_MODIFY_OPTDATA) &&
1938 chain->data == NULL) {
1939 KKASSERT(chain->dio == NULL);
1944 * Clearing the INITIAL flag (for indirect blocks) indicates that
1945 * we've processed the uninitialized storage allocation.
1947 * If this flag is already clear we are likely in a copy-on-write
1948 * situation but we have to be sure NOT to bzero the storage if
1949 * no data is present.
1951 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1952 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1959 * Instantiate data buffer and possibly execute COW operation
1961 switch(chain->bref.type) {
1962 case HAMMER2_BREF_TYPE_VOLUME:
1963 case HAMMER2_BREF_TYPE_FREEMAP:
1965 * The data is embedded, no copy-on-write operation is
1968 KKASSERT(chain->dio == NULL);
1970 case HAMMER2_BREF_TYPE_DIRENT:
1972 * The data might be fully embedded.
1974 if (chain->bytes == 0) {
1975 KKASSERT(chain->dio == NULL);
1979 case HAMMER2_BREF_TYPE_INODE:
1980 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1981 case HAMMER2_BREF_TYPE_DATA:
1982 case HAMMER2_BREF_TYPE_INDIRECT:
1983 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1985 * Perform the copy-on-write operation
1987 * zero-fill or copy-on-write depending on whether
1988 * chain->data exists or not and set the dirty state for
1989 * the new buffer. hammer2_io_new() will handle the
1992 * If a dedup_off was supplied this is an existing block
1993 * and no COW, copy, or further modification is required.
1995 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1997 if (wasinitial && dedup_off == 0) {
1998 error = hammer2_io_new(hmp, chain->bref.type,
1999 chain->bref.data_off,
2000 chain->bytes, &dio);
2002 error = hammer2_io_bread(hmp, chain->bref.type,
2003 chain->bref.data_off,
2004 chain->bytes, &dio);
2006 hammer2_adjreadcounter(&chain->bref, chain->bytes);
2009 * If an I/O error occurs make sure callers cannot accidently
2010 * modify the old buffer's contents and corrupt the filesystem.
2012 * NOTE: hammer2_io_data() call issues bkvasync()
2015 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
2017 chain->error = HAMMER2_ERROR_EIO;
2018 hammer2_io_brelse(&dio);
2019 hammer2_io_brelse(&chain->dio);
2024 bdata = hammer2_io_data(dio, chain->bref.data_off);
2028 * COW (unless a dedup).
2030 KKASSERT(chain->dio != NULL);
2031 if (chain->data != (void *)bdata && dedup_off == 0) {
2032 bcopy(chain->data, bdata, chain->bytes);
2034 } else if (wasinitial == 0) {
2036 * We have a problem. We were asked to COW but
2037 * we don't have any data to COW with!
2039 panic("hammer2_chain_modify: having a COW %p\n",
2044 * Retire the old buffer, replace with the new. Dirty or
2045 * redirty the new buffer.
2047 * WARNING! The system buffer cache may have already flushed
2048 * the buffer, so we must be sure to [re]dirty it
2049 * for further modification.
2051 * If dedup_off was supplied, the caller is not
2052 * expected to make any further modification to the
2055 * WARNING! hammer2_get_gdata() assumes dio never transitions
2056 * through NULL in order to optimize away unnecessary
2062 if ((tio = chain->dio) != NULL)
2063 hammer2_io_bqrelse(&tio);
2064 chain->data = (void *)bdata;
2067 hammer2_io_setdirty(dio);
2071 panic("hammer2_chain_modify: illegal non-embedded type %d",
2078 * setflush on parent indicating that the parent must recurse down
2079 * to us. Do not call on chain itself which might already have it
2083 hammer2_chain_setflush(chain->parent);
2084 lockmgr(&chain->diolk, LK_RELEASE);
2086 return (chain->error);
2090 * Modify the chain associated with an inode.
2093 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
2094 hammer2_tid_t mtid, int flags)
2098 hammer2_inode_modify(ip);
2099 error = hammer2_chain_modify(chain, mtid, 0, flags);
2105 * Volume header data locks
2108 hammer2_voldata_lock(hammer2_dev_t *hmp)
2110 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
2114 hammer2_voldata_unlock(hammer2_dev_t *hmp)
2116 lockmgr(&hmp->vollk, LK_RELEASE);
2120 hammer2_voldata_modify(hammer2_dev_t *hmp)
2122 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
2123 atomic_add_long(&hammer2_count_modified_chains, 1);
2124 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
2125 hammer2_pfs_memory_inc(hmp->vchain.pmp);
2130 * This function returns the chain at the nearest key within the specified
2131 * range. The returned chain will be referenced but not locked.
2133 * This function will recurse through chain->rbtree as necessary and will
2134 * return a *key_nextp suitable for iteration. *key_nextp is only set if
2135 * the iteration value is less than the current value of *key_nextp.
2137 * The caller should use (*key_nextp) to calculate the actual range of
2138 * the returned element, which will be (key_beg to *key_nextp - 1), because
2139 * there might be another element which is superior to the returned element
2142 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
2143 * chains continue to be returned. On EOF (*key_nextp) may overflow since
2144 * it will wind up being (key_end + 1).
2146 * WARNING! Must be called with child's spinlock held. Spinlock remains
2147 * held through the operation.
2149 struct hammer2_chain_find_info {
2150 hammer2_chain_t *best;
2151 hammer2_key_t key_beg;
2152 hammer2_key_t key_end;
2153 hammer2_key_t key_next;
2156 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
2157 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
2161 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
2162 hammer2_key_t key_beg, hammer2_key_t key_end)
2164 struct hammer2_chain_find_info info;
2167 info.key_beg = key_beg;
2168 info.key_end = key_end;
2169 info.key_next = *key_nextp;
2171 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
2172 hammer2_chain_find_cmp, hammer2_chain_find_callback,
2174 *key_nextp = info.key_next;
2176 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
2177 parent, key_beg, key_end, *key_nextp);
2185 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
2187 struct hammer2_chain_find_info *info = data;
2188 hammer2_key_t child_beg;
2189 hammer2_key_t child_end;
2191 child_beg = child->bref.key;
2192 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
2194 if (child_end < info->key_beg)
2196 if (child_beg > info->key_end)
2203 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
2205 struct hammer2_chain_find_info *info = data;
2206 hammer2_chain_t *best;
2207 hammer2_key_t child_end;
2210 * WARNING! Layerq is scanned forwards, exact matches should keep
2211 * the existing info->best.
2213 if ((best = info->best) == NULL) {
2215 * No previous best. Assign best
2218 } else if (best->bref.key <= info->key_beg &&
2219 child->bref.key <= info->key_beg) {
2224 /*info->best = child;*/
2225 } else if (child->bref.key < best->bref.key) {
2227 * Child has a nearer key and best is not flush with key_beg.
2228 * Set best to child. Truncate key_next to the old best key.
2231 if (info->key_next > best->bref.key || info->key_next == 0)
2232 info->key_next = best->bref.key;
2233 } else if (child->bref.key == best->bref.key) {
2235 * If our current best is flush with the child then this
2236 * is an illegal overlap.
2238 * key_next will automatically be limited to the smaller of
2239 * the two end-points.
2245 * Keep the current best but truncate key_next to the child's
2248 * key_next will also automatically be limited to the smaller
2249 * of the two end-points (probably not necessary for this case
2250 * but we do it anyway).
2252 if (info->key_next > child->bref.key || info->key_next == 0)
2253 info->key_next = child->bref.key;
2257 * Always truncate key_next based on child's end-of-range.
2259 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2260 if (child_end && (info->key_next > child_end || info->key_next == 0))
2261 info->key_next = child_end;
2267 * Retrieve the specified chain from a media blockref, creating the
2268 * in-memory chain structure which reflects it. The returned chain is
2269 * held and locked according to (how) (HAMMER2_RESOLVE_*). The caller must
2270 * handle crc-checks and so forth, and should check chain->error before
2271 * assuming that the data is good.
2273 * To handle insertion races pass the INSERT_RACE flag along with the
2274 * generation number of the core. NULL will be returned if the generation
2275 * number changes before we have a chance to insert the chain. Insert
2276 * races can occur because the parent might be held shared.
2278 * Caller must hold the parent locked shared or exclusive since we may
2279 * need the parent's bref array to find our block.
2281 * WARNING! chain->pmp is always set to NULL for any chain representing
2282 * part of the super-root topology.
2285 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2286 hammer2_blockref_t *bref, int how)
2288 hammer2_dev_t *hmp = parent->hmp;
2289 hammer2_chain_t *chain;
2293 * Allocate a chain structure representing the existing media
2294 * entry. Resulting chain has one ref and is not locked.
2296 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2297 chain = hammer2_chain_alloc(hmp, NULL, bref);
2299 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2300 /* ref'd chain returned */
2303 * Flag that the chain is in the parent's blockmap so delete/flush
2304 * knows what to do with it.
2306 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2309 * chain must be locked to avoid unexpected ripouts
2311 hammer2_chain_lock(chain, how);
2314 * Link the chain into its parent. A spinlock is required to safely
2315 * access the RBTREE, and it is possible to collide with another
2316 * hammer2_chain_get() operation because the caller might only hold
2317 * a shared lock on the parent.
2319 * NOTE: Get races can occur quite often when we distribute
2320 * asynchronous read-aheads across multiple threads.
2322 KKASSERT(parent->refs > 0);
2323 error = hammer2_chain_insert(parent, chain,
2324 HAMMER2_CHAIN_INSERT_SPIN |
2325 HAMMER2_CHAIN_INSERT_RACE,
2328 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2329 /*kprintf("chain %p get race\n", chain);*/
2330 hammer2_chain_unlock(chain);
2331 hammer2_chain_drop(chain);
2334 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2338 * Return our new chain referenced but not locked, or NULL if
2345 * Lookup initialization/completion API
2348 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2350 hammer2_chain_ref(parent);
2351 if (flags & HAMMER2_LOOKUP_SHARED) {
2352 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2353 HAMMER2_RESOLVE_SHARED);
2355 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2361 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2364 hammer2_chain_unlock(parent);
2365 hammer2_chain_drop(parent);
2370 * Take the locked chain and return a locked parent. The chain remains
2371 * locked on return, but may have to be temporarily unlocked to acquire
2372 * the parent. Because of this, (chain) must be stable and cannot be
2373 * deleted while it was temporarily unlocked (typically means that (chain)
2376 * Pass HAMMER2_RESOLVE_* flags in flags.
2378 * This will work even if the chain is errored, and the caller can check
2379 * parent->error on return if desired since the parent will be locked.
2381 * This function handles the lock order reversal.
2384 hammer2_chain_getparent(hammer2_chain_t *chain, int flags)
2386 hammer2_chain_t *parent;
2389 * Be careful of order, chain must be unlocked before parent
2390 * is locked below to avoid a deadlock. Try it trivially first.
2392 parent = chain->parent;
2394 panic("hammer2_chain_getparent: no parent");
2395 hammer2_chain_ref(parent);
2396 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0)
2400 hammer2_chain_unlock(chain);
2401 hammer2_chain_lock(parent, flags);
2402 hammer2_chain_lock(chain, flags);
2405 * Parent relinking races are quite common. We have to get
2406 * it right or we will blow up the block table.
2408 if (chain->parent == parent)
2410 hammer2_chain_unlock(parent);
2411 hammer2_chain_drop(parent);
2413 parent = chain->parent;
2415 panic("hammer2_chain_getparent: no parent");
2416 hammer2_chain_ref(parent);
2422 * Take the locked chain and return a locked parent. The chain is unlocked
2423 * and dropped. *chainp is set to the returned parent as a convenience.
2424 * Pass HAMMER2_RESOLVE_* flags in flags.
2426 * This will work even if the chain is errored, and the caller can check
2427 * parent->error on return if desired since the parent will be locked.
2429 * The chain does NOT need to be stable. We use a tracking structure
2430 * to track the expected parent if the chain is deleted out from under us.
2432 * This function handles the lock order reversal.
2435 hammer2_chain_repparent(hammer2_chain_t **chainp, int flags)
2437 hammer2_chain_t *chain;
2438 hammer2_chain_t *parent;
2439 struct hammer2_reptrack reptrack;
2440 struct hammer2_reptrack **repp;
2443 * Be careful of order, chain must be unlocked before parent
2444 * is locked below to avoid a deadlock. Try it trivially first.
2447 parent = chain->parent;
2448 if (parent == NULL) {
2449 hammer2_spin_unex(&chain->core.spin);
2450 panic("hammer2_chain_repparent: no parent");
2452 hammer2_chain_ref(parent);
2453 if (hammer2_chain_lock(parent, flags|HAMMER2_RESOLVE_NONBLOCK) == 0) {
2454 hammer2_chain_unlock(chain);
2455 hammer2_chain_drop(chain);
2462 * Ok, now it gets a bit nasty. There are multiple situations where
2463 * the parent might be in the middle of a deletion, or where the child
2464 * (chain) might be deleted the instant we let go of its lock.
2465 * We can potentially end up in a no-win situation!
2467 * In particular, the indirect_maintenance() case can cause these
2470 * To deal with this we install a reptrack structure in the parent
2471 * This reptrack structure 'owns' the parent ref and will automatically
2472 * migrate to the parent's parent if the parent is deleted permanently.
2474 hammer2_spin_init(&reptrack.spin, "h2reptrk");
2475 reptrack.chain = parent;
2476 hammer2_chain_ref(parent); /* for the reptrack */
2478 hammer2_spin_ex(&parent->core.spin);
2479 reptrack.next = parent->core.reptrack;
2480 parent->core.reptrack = &reptrack;
2481 hammer2_spin_unex(&parent->core.spin);
2483 hammer2_chain_unlock(chain);
2484 hammer2_chain_drop(chain);
2485 chain = NULL; /* gone */
2488 * At the top of this loop, chain is gone and parent is refd both
2489 * by us explicitly AND via our reptrack. We are attempting to
2493 hammer2_chain_lock(parent, flags);
2495 if (reptrack.chain == parent)
2497 hammer2_chain_unlock(parent);
2498 hammer2_chain_drop(parent);
2500 kprintf("hammer2: debug REPTRACK %p->%p\n",
2501 parent, reptrack.chain);
2502 hammer2_spin_ex(&reptrack.spin);
2503 parent = reptrack.chain;
2504 hammer2_chain_ref(parent);
2505 hammer2_spin_unex(&reptrack.spin);
2509 * Once parent is locked and matches our reptrack, our reptrack
2510 * will be stable and we have our parent. We can unlink our
2513 * WARNING! Remember that the chain lock might be shared. Chains
2514 * locked shared have stable parent linkages.
2516 hammer2_spin_ex(&parent->core.spin);
2517 repp = &parent->core.reptrack;
2518 while (*repp != &reptrack)
2519 repp = &(*repp)->next;
2520 *repp = reptrack.next;
2521 hammer2_spin_unex(&parent->core.spin);
2523 hammer2_chain_drop(parent); /* reptrack ref */
2524 *chainp = parent; /* return parent lock+ref */
2530 * Dispose of any linked reptrack structures in (chain) by shifting them to
2531 * (parent). Both (chain) and (parent) must be exclusively locked.
2533 * This is interlocked against any children of (chain) on the other side.
2534 * No children so remain as-of when this is called so we can test
2535 * core.reptrack without holding the spin-lock.
2537 * Used whenever the caller intends to permanently delete chains related
2538 * to topological recursions (BREF_TYPE_INDIRECT, BREF_TYPE_FREEMAP_NODE),
2539 * where the chains underneath the node being deleted are given a new parent
2540 * above the node being deleted.
2544 hammer2_chain_repchange(hammer2_chain_t *parent, hammer2_chain_t *chain)
2546 struct hammer2_reptrack *reptrack;
2548 KKASSERT(chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree));
2549 while (chain->core.reptrack) {
2550 hammer2_spin_ex(&parent->core.spin);
2551 hammer2_spin_ex(&chain->core.spin);
2552 reptrack = chain->core.reptrack;
2553 if (reptrack == NULL) {
2554 hammer2_spin_unex(&chain->core.spin);
2555 hammer2_spin_unex(&parent->core.spin);
2558 hammer2_spin_ex(&reptrack->spin);
2559 chain->core.reptrack = reptrack->next;
2560 reptrack->chain = parent;
2561 reptrack->next = parent->core.reptrack;
2562 parent->core.reptrack = reptrack;
2563 hammer2_chain_ref(parent); /* reptrack */
2565 hammer2_spin_unex(&chain->core.spin);
2566 hammer2_spin_unex(&parent->core.spin);
2567 kprintf("hammer2: debug repchange %p %p->%p\n",
2568 reptrack, chain, parent);
2569 hammer2_chain_drop(chain); /* reptrack */
2574 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2575 * (*parentp) typically points to an inode but can also point to a related
2576 * indirect block and this function will recurse upwards and find the inode
2577 * or the nearest undeleted indirect block covering the key range.
2579 * This function unconditionally sets *errorp, replacing any previous value.
2581 * (*parentp) must be exclusive or shared locked (depending on flags) and
2582 * referenced and can be an inode or an existing indirect block within the
2585 * If (*parent) is errored out, this function will not attempt to recurse
2586 * the radix tree and will return NULL along with an appropriate *errorp.
2587 * If NULL is returned and *errorp is 0, the requested lookup could not be
2590 * On return (*parentp) will be modified to point at the deepest parent chain
2591 * element encountered during the search, as a helper for an insertion or
2594 * The new (*parentp) will be locked shared or exclusive (depending on flags),
2595 * and referenced, and the old will be unlocked and dereferenced (no change
2596 * if they are both the same). This is particularly important if the caller
2597 * wishes to insert a new chain, (*parentp) will be set properly even if NULL
2598 * is returned, as long as no error occurred.
2600 * The matching chain will be returned locked according to flags.
2604 * NULL is returned if no match was found, but (*parentp) will still
2605 * potentially be adjusted.
2607 * On return (*key_nextp) will point to an iterative value for key_beg.
2608 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2610 * This function will also recurse up the chain if the key is not within the
2611 * current parent's range. (*parentp) can never be set to NULL. An iteration
2612 * can simply allow (*parentp) to float inside the loop.
2614 * NOTE! chain->data is not always resolved. By default it will not be
2615 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2616 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2617 * BREF_TYPE_DATA as the device buffer can alias the logical file
2622 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2623 hammer2_key_t key_beg, hammer2_key_t key_end,
2624 int *errorp, int flags)
2627 hammer2_chain_t *parent;
2628 hammer2_chain_t *chain;
2629 hammer2_blockref_t *base;
2630 hammer2_blockref_t *bref;
2631 hammer2_blockref_t bcopy;
2632 hammer2_key_t scan_beg;
2633 hammer2_key_t scan_end;
2635 int how_always = HAMMER2_RESOLVE_ALWAYS;
2636 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2639 int maxloops = 300000;
2640 volatile hammer2_mtx_t save_mtx;
2642 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2643 how_maybe = how_always;
2644 how = HAMMER2_RESOLVE_ALWAYS;
2645 } else if (flags & HAMMER2_LOOKUP_NODATA) {
2646 how = HAMMER2_RESOLVE_NEVER;
2648 how = HAMMER2_RESOLVE_MAYBE;
2650 if (flags & HAMMER2_LOOKUP_SHARED) {
2651 how_maybe |= HAMMER2_RESOLVE_SHARED;
2652 how_always |= HAMMER2_RESOLVE_SHARED;
2653 how |= HAMMER2_RESOLVE_SHARED;
2657 * Recurse (*parentp) upward if necessary until the parent completely
2658 * encloses the key range or we hit the inode.
2660 * Handle races against the flusher deleting indirect nodes on its
2661 * way back up by continuing to recurse upward past the deletion.
2667 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2668 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2669 scan_beg = parent->bref.key;
2670 scan_end = scan_beg +
2671 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2672 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2673 if (key_beg >= scan_beg && key_end <= scan_end)
2676 parent = hammer2_chain_repparent(parentp, how_maybe);
2679 if (--maxloops == 0)
2680 panic("hammer2_chain_lookup: maxloops");
2682 * Locate the blockref array. Currently we do a fully associative
2683 * search through the array.
2685 switch(parent->bref.type) {
2686 case HAMMER2_BREF_TYPE_INODE:
2688 * Special shortcut for embedded data returns the inode
2689 * itself. Callers must detect this condition and access
2690 * the embedded data (the strategy code does this for us).
2692 * This is only applicable to regular files and softlinks.
2694 * We need a second lock on parent. Since we already have
2695 * a lock we must pass LOCKAGAIN to prevent unexpected
2696 * blocking (we don't want to block on a second shared
2697 * ref if an exclusive lock is pending)
2699 if (parent->data->ipdata.meta.op_flags &
2700 HAMMER2_OPFLAG_DIRECTDATA) {
2701 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2703 *key_nextp = key_end + 1;
2706 hammer2_chain_ref(parent);
2707 hammer2_chain_lock(parent, how_always |
2708 HAMMER2_RESOLVE_LOCKAGAIN);
2709 *key_nextp = key_end + 1;
2712 base = &parent->data->ipdata.u.blockset.blockref[0];
2713 count = HAMMER2_SET_COUNT;
2715 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2716 case HAMMER2_BREF_TYPE_INDIRECT:
2718 * Handle MATCHIND on the parent
2720 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2721 scan_beg = parent->bref.key;
2722 scan_end = scan_beg +
2723 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2724 if (key_beg == scan_beg && key_end == scan_end) {
2726 hammer2_chain_ref(chain);
2727 hammer2_chain_lock(chain, how_maybe);
2728 *key_nextp = scan_end + 1;
2734 * Optimize indirect blocks in the INITIAL state to avoid
2737 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2740 if (parent->data == NULL) {
2741 kprintf("parent->data is NULL %p\n", parent);
2743 tsleep(parent, 0, "xxx", 0);
2745 base = &parent->data->npdata[0];
2747 count = parent->bytes / sizeof(hammer2_blockref_t);
2749 case HAMMER2_BREF_TYPE_VOLUME:
2750 base = &parent->data->voldata.sroot_blockset.blockref[0];
2751 count = HAMMER2_SET_COUNT;
2753 case HAMMER2_BREF_TYPE_FREEMAP:
2754 base = &parent->data->blkset.blockref[0];
2755 count = HAMMER2_SET_COUNT;
2758 kprintf("hammer2_chain_lookup: unrecognized "
2759 "blockref(B) type: %d",
2762 tsleep(&base, 0, "dead", 0);
2763 panic("hammer2_chain_lookup: unrecognized "
2764 "blockref(B) type: %d",
2766 base = NULL; /* safety */
2767 count = 0; /* safety */
2771 * No lookup is possible if the parent is errored. We delayed
2772 * this check as long as we could to ensure that the parent backup,
2773 * embedded data, and MATCHIND code could still execute.
2775 if (parent->error) {
2776 *errorp = parent->error;
2781 * Merged scan to find next candidate.
2783 * hammer2_base_*() functions require the parent->core.live_* fields
2784 * to be synchronized.
2786 * We need to hold the spinlock to access the block array and RB tree
2787 * and to interlock chain creation.
2789 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2790 hammer2_chain_countbrefs(parent, base, count);
2795 hammer2_spin_ex(&parent->core.spin);
2796 chain = hammer2_combined_find(parent, base, count,
2800 generation = parent->core.generation;
2803 * Exhausted parent chain, iterate.
2806 KKASSERT(chain == NULL);
2807 hammer2_spin_unex(&parent->core.spin);
2808 if (key_beg == key_end) /* short cut single-key case */
2812 * Stop if we reached the end of the iteration.
2814 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2815 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2820 * Calculate next key, stop if we reached the end of the
2821 * iteration, otherwise go up one level and loop.
2823 key_beg = parent->bref.key +
2824 ((hammer2_key_t)1 << parent->bref.keybits);
2825 if (key_beg == 0 || key_beg > key_end)
2827 parent = hammer2_chain_repparent(parentp, how_maybe);
2832 * Selected from blockref or in-memory chain.
2835 if (chain == NULL) {
2836 hammer2_spin_unex(&parent->core.spin);
2837 if (bcopy.type == HAMMER2_BREF_TYPE_INDIRECT ||
2838 bcopy.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2839 chain = hammer2_chain_get(parent, generation,
2842 chain = hammer2_chain_get(parent, generation,
2848 hammer2_chain_ref(chain);
2849 hammer2_spin_unex(&parent->core.spin);
2852 * chain is referenced but not locked. We must lock the
2853 * chain to obtain definitive state.
2855 if (bcopy.type == HAMMER2_BREF_TYPE_INDIRECT ||
2856 bcopy.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2857 hammer2_chain_lock(chain, how_maybe);
2859 hammer2_chain_lock(chain, how);
2861 KKASSERT(chain->parent == parent);
2863 if (bcmp(&bcopy, &chain->bref, sizeof(bcopy)) ||
2864 chain->parent != parent) {
2865 hammer2_chain_unlock(chain);
2866 hammer2_chain_drop(chain);
2867 chain = NULL; /* SAFETY */
2873 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2875 * NOTE: Chain's key range is not relevant as there might be
2876 * one-offs within the range that are not deleted.
2878 * NOTE: Lookups can race delete-duplicate because
2879 * delete-duplicate does not lock the parent's core
2880 * (they just use the spinlock on the core).
2882 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2883 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2884 chain->bref.data_off, chain->bref.type,
2886 hammer2_chain_unlock(chain);
2887 hammer2_chain_drop(chain);
2888 chain = NULL; /* SAFETY */
2889 key_beg = *key_nextp;
2890 if (key_beg == 0 || key_beg > key_end)
2896 * If the chain element is an indirect block it becomes the new
2897 * parent and we loop on it. We must maintain our top-down locks
2898 * to prevent the flusher from interfering (i.e. doing a
2899 * delete-duplicate and leaving us recursing down a deleted chain).
2901 * The parent always has to be locked with at least RESOLVE_MAYBE
2902 * so we can access its data. It might need a fixup if the caller
2903 * passed incompatible flags. Be careful not to cause a deadlock
2904 * as a data-load requires an exclusive lock.
2906 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2907 * range is within the requested key range we return the indirect
2908 * block and do NOT loop. This is usually only used to acquire
2911 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2912 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2913 save_mtx = parent->lock;
2914 hammer2_chain_unlock(parent);
2915 hammer2_chain_drop(parent);
2916 *parentp = parent = chain;
2917 chain = NULL; /* SAFETY */
2922 * All done, return the locked chain.
2924 * If the caller does not want a locked chain, replace the lock with
2925 * a ref. Perhaps this can eventually be optimized to not obtain the
2926 * lock in the first place for situations where the data does not
2927 * need to be resolved.
2929 * NOTE! A chain->error must be tested by the caller upon return.
2930 * *errorp is only set based on issues which occur while
2931 * trying to reach the chain.
2937 * After having issued a lookup we can iterate all matching keys.
2939 * If chain is non-NULL we continue the iteration from just after it's index.
2941 * If chain is NULL we assume the parent was exhausted and continue the
2942 * iteration at the next parent.
2944 * If a fatal error occurs (typically an I/O error), a dummy chain is
2945 * returned with chain->error and error-identifying information set. This
2946 * chain will assert if you try to do anything fancy with it.
2948 * XXX Depending on where the error occurs we should allow continued iteration.
2950 * parent must be locked on entry and remains locked throughout. chain's
2951 * lock status must match flags. Chain is always at least referenced.
2953 * WARNING! The MATCHIND flag does not apply to this function.
2956 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2957 hammer2_key_t *key_nextp,
2958 hammer2_key_t key_beg, hammer2_key_t key_end,
2959 int *errorp, int flags)
2961 hammer2_chain_t *parent;
2965 * Calculate locking flags for upward recursion.
2967 how_maybe = HAMMER2_RESOLVE_MAYBE;
2968 if (flags & HAMMER2_LOOKUP_SHARED)
2969 how_maybe |= HAMMER2_RESOLVE_SHARED;
2975 * Calculate the next index and recalculate the parent if necessary.
2978 key_beg = chain->bref.key +
2979 ((hammer2_key_t)1 << chain->bref.keybits);
2980 hammer2_chain_unlock(chain);
2981 hammer2_chain_drop(chain);
2984 * chain invalid past this point, but we can still do a
2985 * pointer comparison w/parent.
2987 * Any scan where the lookup returned degenerate data embedded
2988 * in the inode has an invalid index and must terminate.
2990 if (chain == parent)
2992 if (key_beg == 0 || key_beg > key_end)
2995 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2996 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2998 * We reached the end of the iteration.
3003 * Continue iteration with next parent unless the current
3004 * parent covers the range.
3006 * (This also handles the case of a deleted, empty indirect
3009 key_beg = parent->bref.key +
3010 ((hammer2_key_t)1 << parent->bref.keybits);
3011 if (key_beg == 0 || key_beg > key_end)
3013 parent = hammer2_chain_repparent(parentp, how_maybe);
3019 return (hammer2_chain_lookup(parentp, key_nextp,
3025 * Caller wishes to iterate chains under parent, loading new chains into
3026 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
3027 * then call hammer2_chain_scan() repeatedly until a non-zero return.
3028 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
3029 * with the returned chain for the scan. The returned *chainp will be
3030 * locked and referenced. Any prior contents will be unlocked and dropped.
3032 * Caller should check the return value. A normal scan EOF will return
3033 * exactly HAMMER2_ERROR_EOF. Any other non-zero value indicates an
3034 * error trying to access parent data. Any error in the returned chain
3035 * must be tested separately by the caller.
3037 * (*chainp) is dropped on each scan, but will only be set if the returned
3038 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
3039 * returned via *chainp. The caller will get their bref only.
3041 * The raw scan function is similar to lookup/next but does not seek to a key.
3042 * Blockrefs are iterated via first_bref = (parent, NULL) and
3043 * next_chain = (parent, bref).
3045 * The passed-in parent must be locked and its data resolved. The function
3046 * nominally returns a locked and referenced *chainp != NULL for chains
3047 * the caller might need to recurse on (and will dipose of any *chainp passed
3048 * in). The caller must check the chain->bref.type either way.
3051 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
3052 hammer2_blockref_t *bref, int *firstp,
3056 hammer2_blockref_t *base;
3057 hammer2_blockref_t *bref_ptr;
3059 hammer2_key_t next_key;
3060 hammer2_chain_t *chain = NULL;
3062 int how_always = HAMMER2_RESOLVE_ALWAYS;
3063 int how_maybe = HAMMER2_RESOLVE_MAYBE;
3066 int maxloops = 300000;
3073 * Scan flags borrowed from lookup.
3075 if (flags & HAMMER2_LOOKUP_ALWAYS) {
3076 how_maybe = how_always;
3077 how = HAMMER2_RESOLVE_ALWAYS;
3078 } else if (flags & HAMMER2_LOOKUP_NODATA) {
3079 how = HAMMER2_RESOLVE_NEVER;
3081 how = HAMMER2_RESOLVE_MAYBE;
3083 if (flags & HAMMER2_LOOKUP_SHARED) {
3084 how_maybe |= HAMMER2_RESOLVE_SHARED;
3085 how_always |= HAMMER2_RESOLVE_SHARED;
3086 how |= HAMMER2_RESOLVE_SHARED;
3090 * Calculate key to locate first/next element, unlocking the previous
3091 * element as we go. Be careful, the key calculation can overflow.
3093 * (also reset bref to NULL)
3099 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
3100 if ((chain = *chainp) != NULL) {
3102 hammer2_chain_unlock(chain);
3103 hammer2_chain_drop(chain);
3107 error |= HAMMER2_ERROR_EOF;
3113 if (parent->error) {
3114 error = parent->error;
3117 if (--maxloops == 0)
3118 panic("hammer2_chain_scan: maxloops");
3121 * Locate the blockref array. Currently we do a fully associative
3122 * search through the array.
3124 switch(parent->bref.type) {
3125 case HAMMER2_BREF_TYPE_INODE:
3127 * An inode with embedded data has no sub-chains.
3129 * WARNING! Bulk scan code may pass a static chain marked
3130 * as BREF_TYPE_INODE with a copy of the volume
3131 * root blockset to snapshot the volume.
3133 if (parent->data->ipdata.meta.op_flags &
3134 HAMMER2_OPFLAG_DIRECTDATA) {
3135 error |= HAMMER2_ERROR_EOF;
3138 base = &parent->data->ipdata.u.blockset.blockref[0];
3139 count = HAMMER2_SET_COUNT;
3141 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3142 case HAMMER2_BREF_TYPE_INDIRECT:
3144 * Optimize indirect blocks in the INITIAL state to avoid
3147 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3150 if (parent->data == NULL)
3151 panic("parent->data is NULL");
3152 base = &parent->data->npdata[0];
3154 count = parent->bytes / sizeof(hammer2_blockref_t);
3156 case HAMMER2_BREF_TYPE_VOLUME:
3157 base = &parent->data->voldata.sroot_blockset.blockref[0];
3158 count = HAMMER2_SET_COUNT;
3160 case HAMMER2_BREF_TYPE_FREEMAP:
3161 base = &parent->data->blkset.blockref[0];
3162 count = HAMMER2_SET_COUNT;
3165 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3167 base = NULL; /* safety */
3168 count = 0; /* safety */
3172 * Merged scan to find next candidate.
3174 * hammer2_base_*() functions require the parent->core.live_* fields
3175 * to be synchronized.
3177 * We need to hold the spinlock to access the block array and RB tree
3178 * and to interlock chain creation.
3180 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3181 hammer2_chain_countbrefs(parent, base, count);
3185 hammer2_spin_ex(&parent->core.spin);
3186 chain = hammer2_combined_find(parent, base, count,
3188 key, HAMMER2_KEY_MAX,
3190 generation = parent->core.generation;
3193 * Exhausted parent chain, we're done.
3195 if (bref_ptr == NULL) {
3196 hammer2_spin_unex(&parent->core.spin);
3197 KKASSERT(chain == NULL);
3198 error |= HAMMER2_ERROR_EOF;
3203 * Copy into the supplied stack-based blockref.
3208 * Selected from blockref or in-memory chain.
3210 if (chain == NULL) {
3211 switch(bref->type) {
3212 case HAMMER2_BREF_TYPE_INODE:
3213 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3214 case HAMMER2_BREF_TYPE_INDIRECT:
3215 case HAMMER2_BREF_TYPE_VOLUME:
3216 case HAMMER2_BREF_TYPE_FREEMAP:
3218 * Recursion, always get the chain
3220 hammer2_spin_unex(&parent->core.spin);
3221 chain = hammer2_chain_get(parent, generation,
3228 * No recursion, do not waste time instantiating
3229 * a chain, just iterate using the bref.
3231 hammer2_spin_unex(&parent->core.spin);
3236 * Recursion or not we need the chain in order to supply
3239 hammer2_chain_ref(chain);
3240 hammer2_spin_unex(&parent->core.spin);
3241 hammer2_chain_lock(chain, how);
3244 (bcmp(bref, &chain->bref, sizeof(*bref)) ||
3245 chain->parent != parent)) {
3246 hammer2_chain_unlock(chain);
3247 hammer2_chain_drop(chain);
3253 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
3255 * NOTE: chain's key range is not relevant as there might be
3256 * one-offs within the range that are not deleted.
3258 * NOTE: XXX this could create problems with scans used in
3259 * situations other than mount-time recovery.
3261 * NOTE: Lookups can race delete-duplicate because
3262 * delete-duplicate does not lock the parent's core
3263 * (they just use the spinlock on the core).
3265 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3266 hammer2_chain_unlock(chain);
3267 hammer2_chain_drop(chain);
3272 error |= HAMMER2_ERROR_EOF;
3280 * All done, return the bref or NULL, supply chain if necessary.
3288 * Create and return a new hammer2 system memory structure of the specified
3289 * key, type and size and insert it under (*parentp). This is a full
3290 * insertion, based on the supplied key/keybits, and may involve creating
3291 * indirect blocks and moving other chains around via delete/duplicate.
3293 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
3294 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3295 * FULL. This typically means that the caller is creating the chain after
3296 * doing a hammer2_chain_lookup().
3298 * (*parentp) must be exclusive locked and may be replaced on return
3299 * depending on how much work the function had to do.
3301 * (*parentp) must not be errored or this function will assert.
3303 * (*chainp) usually starts out NULL and returns the newly created chain,
3304 * but if the caller desires the caller may allocate a disconnected chain
3305 * and pass it in instead.
3307 * This function should NOT be used to insert INDIRECT blocks. It is
3308 * typically used to create/insert inodes and data blocks.
3310 * Caller must pass-in an exclusively locked parent the new chain is to
3311 * be inserted under, and optionally pass-in a disconnected, exclusively
3312 * locked chain to insert (else we create a new chain). The function will
3313 * adjust (*parentp) as necessary, create or connect the chain, and
3314 * return an exclusively locked chain in *chainp.
3316 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
3317 * and will be reassigned.
3319 * NOTE: returns HAMMER_ERROR_* flags
3322 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
3323 hammer2_pfs_t *pmp, int methods,
3324 hammer2_key_t key, int keybits, int type, size_t bytes,
3325 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
3328 hammer2_chain_t *chain;
3329 hammer2_chain_t *parent;
3330 hammer2_blockref_t *base;
3331 hammer2_blockref_t dummy;
3335 int maxloops = 300000;
3338 * Topology may be crossing a PFS boundary.
3341 KKASSERT(hammer2_mtx_owned(&parent->lock));
3342 KKASSERT(parent->error == 0);
3346 if (chain == NULL) {
3348 * First allocate media space and construct the dummy bref,
3349 * then allocate the in-memory chain structure. Set the
3350 * INITIAL flag for fresh chains which do not have embedded
3353 * XXX for now set the check mode of the child based on
3354 * the parent or, if the parent is an inode, the
3355 * specification in the inode.
3357 bzero(&dummy, sizeof(dummy));
3360 dummy.keybits = keybits;
3361 dummy.data_off = hammer2_getradix(bytes);
3364 * Inherit methods from parent by default. Primarily used
3365 * for BREF_TYPE_DATA. Non-data types *must* be set to
3366 * a non-NONE check algorithm.
3369 dummy.methods = parent->bref.methods;
3371 dummy.methods = (uint8_t)methods;
3373 if (type != HAMMER2_BREF_TYPE_DATA &&
3374 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3376 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3379 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3382 * Lock the chain manually, chain_lock will load the chain
3383 * which we do NOT want to do. (note: chain->refs is set
3384 * to 1 by chain_alloc() for us, but lockcnt is not).
3387 hammer2_mtx_ex(&chain->lock);
3389 ++curthread->td_tracker;
3392 * Set INITIAL to optimize I/O. The flag will generally be
3393 * processed when we call hammer2_chain_modify().
3395 * Recalculate bytes to reflect the actual media block
3396 * allocation. Handle special case radix 0 == 0 bytes.
3398 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3400 bytes = (hammer2_off_t)1 << bytes;
3401 chain->bytes = bytes;
3404 case HAMMER2_BREF_TYPE_VOLUME:
3405 case HAMMER2_BREF_TYPE_FREEMAP:
3406 panic("hammer2_chain_create: called with volume type");
3408 case HAMMER2_BREF_TYPE_INDIRECT:
3409 panic("hammer2_chain_create: cannot be used to"
3410 "create indirect block");
3412 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3413 panic("hammer2_chain_create: cannot be used to"
3414 "create freemap root or node");
3416 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3417 KKASSERT(bytes == sizeof(chain->data->bmdata));
3419 case HAMMER2_BREF_TYPE_DIRENT:
3420 case HAMMER2_BREF_TYPE_INODE:
3421 case HAMMER2_BREF_TYPE_DATA:
3424 * leave chain->data NULL, set INITIAL
3426 KKASSERT(chain->data == NULL);
3427 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3432 * We are reattaching a previously deleted chain, possibly
3433 * under a new parent and possibly with a new key/keybits.
3434 * The chain does not have to be in a modified state. The
3435 * UPDATE flag will be set later on in this routine.
3437 * Do NOT mess with the current state of the INITIAL flag.
3439 chain->bref.key = key;
3440 chain->bref.keybits = keybits;
3441 if (chain->flags & HAMMER2_CHAIN_DELETED)
3442 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3443 KKASSERT(chain->parent == NULL);
3447 * Set the appropriate bref flag if requested.
3449 * NOTE! Callers can call this function to move chains without
3450 * knowing about special flags, so don't clear bref flags
3453 if (flags & HAMMER2_INSERT_PFSROOT)
3454 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3457 * Calculate how many entries we have in the blockref array and
3458 * determine if an indirect block is required.
3461 if (--maxloops == 0)
3462 panic("hammer2_chain_create: maxloops");
3464 switch(parent->bref.type) {
3465 case HAMMER2_BREF_TYPE_INODE:
3466 if ((parent->data->ipdata.meta.op_flags &
3467 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3468 kprintf("hammer2: parent set for direct-data! "
3469 "pkey=%016jx ckey=%016jx\n",
3473 KKASSERT((parent->data->ipdata.meta.op_flags &
3474 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3475 KKASSERT(parent->data != NULL);
3476 base = &parent->data->ipdata.u.blockset.blockref[0];
3477 count = HAMMER2_SET_COUNT;
3479 case HAMMER2_BREF_TYPE_INDIRECT:
3480 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3481 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3484 base = &parent->data->npdata[0];
3485 count = parent->bytes / sizeof(hammer2_blockref_t);
3487 case HAMMER2_BREF_TYPE_VOLUME:
3488 KKASSERT(parent->data != NULL);
3489 base = &parent->data->voldata.sroot_blockset.blockref[0];
3490 count = HAMMER2_SET_COUNT;
3492 case HAMMER2_BREF_TYPE_FREEMAP:
3493 KKASSERT(parent->data != NULL);
3494 base = &parent->data->blkset.blockref[0];
3495 count = HAMMER2_SET_COUNT;
3498 panic("hammer2_chain_create: unrecognized blockref type: %d",
3506 * Make sure we've counted the brefs
3508 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3509 hammer2_chain_countbrefs(parent, base, count);
3511 KASSERT(parent->core.live_count >= 0 &&
3512 parent->core.live_count <= count,
3513 ("bad live_count %d/%d (%02x, %d)",
3514 parent->core.live_count, count,
3515 parent->bref.type, parent->bytes));
3518 * If no free blockref could be found we must create an indirect
3519 * block and move a number of blockrefs into it. With the parent
3520 * locked we can safely lock each child in order to delete+duplicate
3521 * it without causing a deadlock.
3523 * This may return the new indirect block or the old parent depending
3524 * on where the key falls. NULL is returned on error.
3526 if (parent->core.live_count == count) {
3527 hammer2_chain_t *nparent;
3529 KKASSERT((flags & HAMMER2_INSERT_SAMEPARENT) == 0);
3531 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3532 mtid, type, &error);
3533 if (nparent == NULL) {
3535 hammer2_chain_drop(chain);
3539 if (parent != nparent) {
3540 hammer2_chain_unlock(parent);
3541 hammer2_chain_drop(parent);
3542 parent = *parentp = nparent;
3547 if (chain->flags & HAMMER2_CHAIN_DELETED)
3548 kprintf("Inserting deleted chain @%016jx\n",
3552 * Link the chain into its parent.
3554 if (chain->parent != NULL)
3555 panic("hammer2: hammer2_chain_create: chain already connected");
3556 KKASSERT(chain->parent == NULL);
3557 KKASSERT(parent->core.live_count < count);
3558 hammer2_chain_insert(parent, chain,
3559 HAMMER2_CHAIN_INSERT_SPIN |
3560 HAMMER2_CHAIN_INSERT_LIVE,
3565 * Mark the newly created chain modified. This will cause
3566 * UPDATE to be set and process the INITIAL flag.
3568 * Device buffers are not instantiated for DATA elements
3569 * as these are handled by logical buffers.
3571 * Indirect and freemap node indirect blocks are handled
3572 * by hammer2_chain_create_indirect() and not by this
3575 * Data for all other bref types is expected to be
3576 * instantiated (INODE, LEAF).
3578 switch(chain->bref.type) {
3579 case HAMMER2_BREF_TYPE_DATA:
3580 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3581 case HAMMER2_BREF_TYPE_DIRENT:
3582 case HAMMER2_BREF_TYPE_INODE:
3583 error = hammer2_chain_modify(chain, mtid, dedup_off,
3584 HAMMER2_MODIFY_OPTDATA);
3588 * Remaining types are not supported by this function.
3589 * In particular, INDIRECT and LEAF_NODE types are
3590 * handled by create_indirect().
3592 panic("hammer2_chain_create: bad type: %d",
3599 * When reconnecting a chain we must set UPDATE and
3600 * setflush so the flush recognizes that it must update
3601 * the bref in the parent.
3603 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3604 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3608 * We must setflush(parent) to ensure that it recurses through to
3609 * chain. setflush(chain) might not work because ONFLUSH is possibly
3610 * already set in the chain (so it won't recurse up to set it in the
3613 hammer2_chain_setflush(parent);
3622 * Move the chain from its old parent to a new parent. The chain must have
3623 * already been deleted or already disconnected (or never associated) with
3624 * a parent. The chain is reassociated with the new parent and the deleted
3625 * flag will be cleared (no longer deleted). The chain's modification state
3628 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3629 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3630 * FULL. This typically means that the caller is creating the chain after
3631 * doing a hammer2_chain_lookup().
3633 * Neither (parent) or (chain) can be errored.
3635 * If (parent) is non-NULL then the chain is inserted under the parent.
3637 * If (parent) is NULL then the newly duplicated chain is not inserted
3638 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3639 * passing into hammer2_chain_create() after this function returns).
3641 * WARNING! This function calls create which means it can insert indirect
3642 * blocks. This can cause other unrelated chains in the parent to
3643 * be moved to a newly inserted indirect block in addition to the
3647 hammer2_chain_rename(hammer2_chain_t **parentp, hammer2_chain_t *chain,
3648 hammer2_tid_t mtid, int flags)
3650 hammer2_blockref_t *bref;
3652 hammer2_chain_t *parent;
3656 * WARNING! We should never resolve DATA to device buffers
3657 * (XXX allow it if the caller did?), and since
3658 * we currently do not have the logical buffer cache
3659 * buffer in-hand to fix its cached physical offset
3660 * we also force the modify code to not COW it. XXX
3663 KKASSERT(chain->parent == NULL);
3664 KKASSERT(chain->error == 0);
3667 * Now create a duplicate of the chain structure, associating
3668 * it with the same core, making it the same size, pointing it
3669 * to the same bref (the same media block).
3671 * NOTE: Handle special radix == 0 case (means 0 bytes).
3673 bref = &chain->bref;
3674 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3676 bytes = (hammer2_off_t)1 << bytes;
3679 * If parent is not NULL the duplicated chain will be entered under
3680 * the parent and the UPDATE bit set to tell flush to update
3683 * We must setflush(parent) to ensure that it recurses through to
3684 * chain. setflush(chain) might not work because ONFLUSH is possibly
3685 * already set in the chain (so it won't recurse up to set it in the
3688 * Having both chains locked is extremely important for atomicy.
3690 if (parentp && (parent = *parentp) != NULL) {
3691 KKASSERT(hammer2_mtx_owned(&parent->lock));
3692 KKASSERT(parent->refs > 0);
3693 KKASSERT(parent->error == 0);
3695 hammer2_chain_create(parentp, &chain,
3696 chain->pmp, HAMMER2_METH_DEFAULT,
3697 bref->key, bref->keybits, bref->type,
3698 chain->bytes, mtid, 0, flags);
3699 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3700 hammer2_chain_setflush(*parentp);
3705 * Helper function for deleting chains.
3707 * The chain is removed from the live view (the RBTREE) as well as the parent's
3708 * blockmap. Both chain and its parent must be locked.
3710 * parent may not be errored. chain can be errored.
3713 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3714 hammer2_tid_t mtid, int flags)
3719 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3720 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3721 KKASSERT(chain->parent == parent);
3724 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3726 * Chain is blockmapped, so there must be a parent.
3727 * Atomically remove the chain from the parent and remove
3728 * the blockmap entry. The parent must be set modified
3729 * to remove the blockmap entry.
3731 hammer2_blockref_t *base;
3734 KKASSERT(parent != NULL);
3735 KKASSERT(parent->error == 0);
3736 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3737 error = hammer2_chain_modify(parent, mtid, 0, 0);
3742 * Calculate blockmap pointer
3744 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3745 hammer2_spin_ex(&chain->core.spin);
3746 hammer2_spin_ex(&parent->core.spin);
3748 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3749 atomic_add_int(&parent->core.live_count, -1);
3750 ++parent->core.generation;
3751 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3752 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3753 --parent->core.chain_count;
3754 chain->parent = NULL;
3756 switch(parent->bref.type) {
3757 case HAMMER2_BREF_TYPE_INODE:
3759 * Access the inode's block array. However, there
3760 * is no block array if the inode is flagged
3764 (parent->data->ipdata.meta.op_flags &
3765 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3767 &parent->data->ipdata.u.blockset.blockref[0];
3771 count = HAMMER2_SET_COUNT;
3773 case HAMMER2_BREF_TYPE_INDIRECT:
3774 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3776 base = &parent->data->npdata[0];
3779 count = parent->bytes / sizeof(hammer2_blockref_t);
3781 case HAMMER2_BREF_TYPE_VOLUME:
3782 base = &parent->data->voldata.
3783 sroot_blockset.blockref[0];
3784 count = HAMMER2_SET_COUNT;
3786 case HAMMER2_BREF_TYPE_FREEMAP:
3787 base = &parent->data->blkset.blockref[0];
3788 count = HAMMER2_SET_COUNT;
3793 panic("hammer2_flush_pass2: "
3794 "unrecognized blockref type: %d",
3799 * delete blockmapped chain from its parent.
3801 * The parent is not affected by any statistics in chain
3802 * which are pending synchronization. That is, there is
3803 * nothing to undo in the parent since they have not yet
3804 * been incorporated into the parent.
3806 * The parent is affected by statistics stored in inodes.
3807 * Those have already been synchronized, so they must be
3808 * undone. XXX split update possible w/delete in middle?
3811 hammer2_base_delete(parent, base, count, chain);
3813 hammer2_spin_unex(&parent->core.spin);
3814 hammer2_spin_unex(&chain->core.spin);
3815 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3817 * Chain is not blockmapped but a parent is present.
3818 * Atomically remove the chain from the parent. There is
3819 * no blockmap entry to remove.
3821 * Because chain was associated with a parent but not
3822 * synchronized, the chain's *_count_up fields contain
3823 * inode adjustment statistics which must be undone.
3825 hammer2_spin_ex(&chain->core.spin);
3826 hammer2_spin_ex(&parent->core.spin);
3827 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3828 atomic_add_int(&parent->core.live_count, -1);
3829 ++parent->core.generation;
3830 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3831 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3832 --parent->core.chain_count;
3833 chain->parent = NULL;
3834 hammer2_spin_unex(&parent->core.spin);
3835 hammer2_spin_unex(&chain->core.spin);
3838 * Chain is not blockmapped and has no parent. This
3839 * is a degenerate case.
3841 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3848 * Create an indirect block that covers one or more of the elements in the
3849 * current parent. Either returns the existing parent with no locking or
3850 * ref changes or returns the new indirect block locked and referenced
3851 * and leaving the original parent lock/ref intact as well.
3853 * If an error occurs, NULL is returned and *errorp is set to the H2 error.
3855 * The returned chain depends on where the specified key falls.
3857 * The key/keybits for the indirect mode only needs to follow three rules:
3859 * (1) That all elements underneath it fit within its key space and
3861 * (2) That all elements outside it are outside its key space.
3863 * (3) When creating the new indirect block any elements in the current
3864 * parent that fit within the new indirect block's keyspace must be
3865 * moved into the new indirect block.
3867 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3868 * keyspace the the current parent, but lookup/iteration rules will
3869 * ensure (and must ensure) that rule (2) for all parents leading up
3870 * to the nearest inode or the root volume header is adhered to. This
3871 * is accomplished by always recursing through matching keyspaces in
3872 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3874 * The current implementation calculates the current worst-case keyspace by
3875 * iterating the current parent and then divides it into two halves, choosing
3876 * whichever half has the most elements (not necessarily the half containing
3877 * the requested key).
3879 * We can also opt to use the half with the least number of elements. This
3880 * causes lower-numbered keys (aka logical file offsets) to recurse through
3881 * fewer indirect blocks and higher-numbered keys to recurse through more.
3882 * This also has the risk of not moving enough elements to the new indirect
3883 * block and being forced to create several indirect blocks before the element
3886 * Must be called with an exclusively locked parent.
3888 * NOTE: *errorp set to HAMMER_ERROR_* flags
3890 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3891 hammer2_key_t *keyp, int keybits,
3892 hammer2_blockref_t *base, int count);
3893 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3894 hammer2_key_t *keyp, int keybits,
3895 hammer2_blockref_t *base, int count,
3897 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3898 hammer2_key_t *keyp, int keybits,
3899 hammer2_blockref_t *base, int count,
3903 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3904 hammer2_key_t create_key, int create_bits,
3905 hammer2_tid_t mtid, int for_type, int *errorp)
3908 hammer2_blockref_t *base;
3909 hammer2_blockref_t *bref;
3910 hammer2_blockref_t bcopy;
3911 hammer2_chain_t *chain;
3912 hammer2_chain_t *ichain;
3913 hammer2_chain_t dummy;
3914 hammer2_key_t key = create_key;
3915 hammer2_key_t key_beg;
3916 hammer2_key_t key_end;
3917 hammer2_key_t key_next;
3918 int keybits = create_bits;
3926 int maxloops = 300000;
3929 * Calculate the base blockref pointer or NULL if the chain
3930 * is known to be empty. We need to calculate the array count
3931 * for RB lookups either way.
3934 KKASSERT(hammer2_mtx_owned(&parent->lock));
3937 * Pre-modify the parent now to avoid having to deal with error
3938 * processing if we tried to later (in the middle of our loop).
3940 *errorp = hammer2_chain_modify(parent, mtid, 0, 0);
3942 kprintf("hammer2_create_indirect: error %08x %s\n",
3943 *errorp, hammer2_error_str(*errorp));
3947 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3948 base = hammer2_chain_base_and_count(parent, &count);
3951 * dummy used in later chain allocation (no longer used for lookups).
3953 bzero(&dummy, sizeof(dummy));
3956 * How big should our new indirect block be? It has to be at least
3957 * as large as its parent for splits to work properly.
3959 * The freemap uses a specific indirect block size. The number of
3960 * levels are built dynamically and ultimately depend on the size
3961 * volume. Because freemap blocks are taken from the reserved areas
3962 * of the volume our goal is efficiency (fewer levels) and not so
3963 * much to save disk space.
3965 * The first indirect block level for a directory usually uses
3966 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3967 * the hash mechanism, this typically gives us a nominal
3968 * 32 * 4 entries with one level of indirection.
3970 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3971 * indirect blocks. The initial 4 entries in the inode gives us
3972 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3973 * of indirection gives us 137GB, and so forth. H2 can support
3974 * huge file sizes but they are not typical, so we try to stick
3975 * with compactness and do not use a larger indirect block size.
3977 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3978 * due to the way indirect blocks are created this usually winds
3979 * up being extremely inefficient for small files. Even though
3980 * 16KB requires more levels of indirection for very large files,
3981 * the 16KB records can be ganged together into 64KB DIOs.
3983 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3984 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3985 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3986 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3987 if (parent->data->ipdata.meta.type ==
3988 HAMMER2_OBJTYPE_DIRECTORY)
3989 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3991 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3994 nbytes = HAMMER2_IND_BYTES_NOM;
3996 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3997 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3998 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3999 nbytes = count * sizeof(hammer2_blockref_t);
4001 ncount = nbytes / sizeof(hammer2_blockref_t);
4004 * When creating an indirect block for a freemap node or leaf
4005 * the key/keybits must be fitted to static radix levels because
4006 * particular radix levels use particular reserved blocks in the
4009 * This routine calculates the key/radix of the indirect block
4010 * we need to create, and whether it is on the high-side or the
4014 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4015 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4016 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
4019 case HAMMER2_BREF_TYPE_DATA:
4020 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
4021 base, count, ncount);
4023 case HAMMER2_BREF_TYPE_DIRENT:
4024 case HAMMER2_BREF_TYPE_INODE:
4025 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
4026 base, count, ncount);
4029 panic("illegal indirect block for bref type %d", for_type);
4034 * Normalize the key for the radix being represented, keeping the
4035 * high bits and throwing away the low bits.
4037 key &= ~(((hammer2_key_t)1 << keybits) - 1);
4040 * Ok, create our new indirect block
4042 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
4043 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
4044 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
4046 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
4048 dummy.bref.key = key;
4049 dummy.bref.keybits = keybits;
4050 dummy.bref.data_off = hammer2_getradix(nbytes);
4051 dummy.bref.methods =
4052 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
4053 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
4055 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
4056 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
4057 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
4058 /* ichain has one ref at this point */
4061 * We have to mark it modified to allocate its block, but use
4062 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
4063 * it won't be acted upon by the flush code.
4065 *errorp = hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
4067 kprintf("hammer2_alloc_indirect: error %08x %s\n",
4068 *errorp, hammer2_error_str(*errorp));
4069 hammer2_chain_unlock(ichain);
4070 hammer2_chain_drop(ichain);
4075 * Iterate the original parent and move the matching brefs into
4076 * the new indirect block.
4078 * XXX handle flushes.
4081 key_end = HAMMER2_KEY_MAX;
4082 key_next = 0; /* avoid gcc warnings */
4083 hammer2_spin_ex(&parent->core.spin);
4089 * Parent may have been modified, relocating its block array.
4090 * Reload the base pointer.
4092 base = hammer2_chain_base_and_count(parent, &count);
4094 if (++loops > 100000) {
4095 hammer2_spin_unex(&parent->core.spin);
4096 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
4097 reason, parent, base, count, key_next);
4101 * NOTE: spinlock stays intact, returned chain (if not NULL)
4102 * is not referenced or locked which means that we
4103 * cannot safely check its flagged / deletion status
4106 chain = hammer2_combined_find(parent, base, count,
4110 generation = parent->core.generation;
4113 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4116 * Skip keys that are not within the key/radix of the new
4117 * indirect block. They stay in the parent.
4119 if ((~(((hammer2_key_t)1 << keybits) - 1) &
4120 (key ^ bref->key)) != 0) {
4121 goto next_key_spinlocked;
4125 * Load the new indirect block by acquiring the related
4126 * chains (potentially from media as it might not be
4127 * in-memory). Then move it to the new parent (ichain).
4129 * chain is referenced but not locked. We must lock the
4130 * chain to obtain definitive state.
4135 * Use chain already present in the RBTREE
4137 hammer2_chain_ref(chain);
4138 hammer2_spin_unex(&parent->core.spin);
4139 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
4142 * Get chain for blockref element. _get returns NULL
4143 * on insertion race.
4145 hammer2_spin_unex(&parent->core.spin);
4146 chain = hammer2_chain_get(parent, generation, &bcopy,
4147 HAMMER2_RESOLVE_NEVER);
4148 if (chain == NULL) {
4150 hammer2_spin_ex(&parent->core.spin);
4156 * This is always live so if the chain has been deleted
4157 * we raced someone and we have to retry.
4159 * NOTE: Lookups can race delete-duplicate because
4160 * delete-duplicate does not lock the parent's core
4161 * (they just use the spinlock on the core).
4163 * (note reversed logic for this one)
4165 if (bcmp(&bcopy, &chain->bref, sizeof(bcopy)) ||
4166 chain->parent != parent ||
4167 (chain->flags & HAMMER2_CHAIN_DELETED)) {
4168 hammer2_chain_unlock(chain);
4169 hammer2_chain_drop(chain);
4170 if (hammer2_debug & 0x0040) {
4171 kprintf("LOST PARENT RETRY "
4172 "RETRY (%p,%p)->%p %08x\n",
4173 parent, chain->parent, chain, chain->flags);
4175 hammer2_spin_ex(&parent->core.spin);
4180 * Shift the chain to the indirect block.
4182 * WARNING! No reason for us to load chain data, pass NOSTATS
4183 * to prevent delete/insert from trying to access
4184 * inode stats (and thus asserting if there is no
4185 * chain->data loaded).
4187 * WARNING! The (parent, chain) deletion may modify the parent
4188 * and invalidate the base pointer.
4190 * WARNING! Parent must already be marked modified, so we
4191 * can assume that chain_delete always suceeds.
4193 * WARNING! hammer2_chain_repchange() does not have to be
4194 * called (and doesn't work anyway because we are
4195 * only doing a partial shift). A recursion that is
4196 * in-progress can continue at the current parent
4197 * and will be able to properly find its next key.
4199 error = hammer2_chain_delete(parent, chain, mtid, 0);
4200 KKASSERT(error == 0);
4201 hammer2_chain_rename(&ichain, chain, mtid, 0);
4202 hammer2_chain_unlock(chain);
4203 hammer2_chain_drop(chain);
4204 KKASSERT(parent->refs > 0);
4206 base = NULL; /* safety */
4207 hammer2_spin_ex(&parent->core.spin);
4208 next_key_spinlocked:
4209 if (--maxloops == 0)
4210 panic("hammer2_chain_create_indirect: maxloops");
4212 if (key_next == 0 || key_next > key_end)
4217 hammer2_spin_unex(&parent->core.spin);
4220 * Insert the new indirect block into the parent now that we've
4221 * cleared out some entries in the parent. We calculated a good
4222 * insertion index in the loop above (ichain->index).
4224 * We don't have to set UPDATE here because we mark ichain
4225 * modified down below (so the normal modified -> flush -> set-moved
4226 * sequence applies).
4228 * The insertion shouldn't race as this is a completely new block
4229 * and the parent is locked.
4231 base = NULL; /* safety, parent modify may change address */
4232 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
4233 KKASSERT(parent->core.live_count < count);
4234 hammer2_chain_insert(parent, ichain,
4235 HAMMER2_CHAIN_INSERT_SPIN |
4236 HAMMER2_CHAIN_INSERT_LIVE,
4240 * Make sure flushes propogate after our manual insertion.
4242 hammer2_chain_setflush(ichain);
4243 hammer2_chain_setflush(parent);
4246 * Figure out what to return.
4248 if (~(((hammer2_key_t)1 << keybits) - 1) &
4249 (create_key ^ key)) {
4251 * Key being created is outside the key range,
4252 * return the original parent.
4254 hammer2_chain_unlock(ichain);
4255 hammer2_chain_drop(ichain);
4258 * Otherwise its in the range, return the new parent.
4259 * (leave both the new and old parent locked).
4268 * Do maintenance on an indirect chain. Both parent and chain are locked.
4270 * Returns non-zero if (chain) is deleted, either due to being empty or
4271 * because its children were safely moved into the parent.
4274 hammer2_chain_indirect_maintenance(hammer2_chain_t *parent,
4275 hammer2_chain_t *chain)
4277 hammer2_blockref_t *chain_base;
4278 hammer2_blockref_t *base;
4279 hammer2_blockref_t *bref;
4280 hammer2_blockref_t bcopy;
4281 hammer2_key_t key_next;
4282 hammer2_key_t key_beg;
4283 hammer2_key_t key_end;
4284 hammer2_chain_t *sub;
4291 * Make sure we have an accurate live_count
4293 if ((chain->flags & (HAMMER2_CHAIN_INITIAL |
4294 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4295 base = &chain->data->npdata[0];
4296 count = chain->bytes / sizeof(hammer2_blockref_t);
4297 hammer2_chain_countbrefs(chain, base, count);
4301 * If the indirect block is empty we can delete it.
4302 * (ignore deletion error)
4304 if (chain->core.live_count == 0 && RB_EMPTY(&chain->core.rbtree)) {
4305 hammer2_chain_delete(parent, chain,
4306 chain->bref.modify_tid,
4307 HAMMER2_DELETE_PERMANENT);
4308 hammer2_chain_repchange(parent, chain);
4312 base = hammer2_chain_base_and_count(parent, &count);
4314 if ((parent->flags & (HAMMER2_CHAIN_INITIAL |
4315 HAMMER2_CHAIN_COUNTEDBREFS)) == 0) {
4316 hammer2_chain_countbrefs(parent, base, count);
4320 * Determine if we can collapse chain into parent, calculate
4321 * hysteresis for chain emptiness.
4323 if (parent->core.live_count + chain->core.live_count - 1 > count)
4325 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4326 if (chain->core.live_count > chain_count * 3 / 4)
4330 * Ok, theoretically we can collapse chain's contents into
4331 * parent. chain is locked, but any in-memory children of chain
4332 * are not. For this to work, we must be able to dispose of any
4333 * in-memory children of chain.
4335 * For now require that there are no in-memory children of chain.
4337 * WARNING! Both chain and parent must remain locked across this
4342 * Parent must be marked modified. Don't try to collapse it if we
4343 * can't mark it modified. Once modified, destroy chain to make room
4344 * and to get rid of what will be a conflicting key (this is included
4345 * in the calculation above). Finally, move the children of chain
4346 * into chain's parent.
4348 * This order creates an accounting problem for bref.embed.stats
4349 * because we destroy chain before we remove its children. Any
4350 * elements whos blockref is already synchronized will be counted
4351 * twice. To deal with the problem we clean out chain's stats prior
4354 error = hammer2_chain_modify(parent, 0, 0, 0);
4356 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4357 hammer2_error_str(error));
4360 error = hammer2_chain_modify(chain, chain->bref.modify_tid, 0, 0);
4362 krateprintf(&krate_h2me, "hammer2: indirect_maint: %s\n",
4363 hammer2_error_str(error));
4367 chain->bref.embed.stats.inode_count = 0;
4368 chain->bref.embed.stats.data_count = 0;
4369 error = hammer2_chain_delete(parent, chain,
4370 chain->bref.modify_tid,
4371 HAMMER2_DELETE_PERMANENT);
4372 KKASSERT(error == 0);
4375 * The combined_find call requires core.spin to be held. One would
4376 * think there wouldn't be any conflicts since we hold chain
4377 * exclusively locked, but the caching mechanism for 0-ref children
4378 * does not require a chain lock.
4380 hammer2_spin_ex(&chain->core.spin);
4384 key_end = HAMMER2_KEY_MAX;
4386 chain_base = &chain->data->npdata[0];
4387 chain_count = chain->bytes / sizeof(hammer2_blockref_t);
4388 sub = hammer2_combined_find(chain, chain_base, chain_count,
4392 generation = chain->core.generation;
4395 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4399 hammer2_chain_ref(sub);
4400 hammer2_spin_unex(&chain->core.spin);
4401 hammer2_chain_lock(sub, HAMMER2_RESOLVE_NEVER);
4403 hammer2_spin_unex(&chain->core.spin);
4404 sub = hammer2_chain_get(chain, generation, &bcopy,
4405 HAMMER2_RESOLVE_NEVER);
4407 hammer2_spin_ex(&chain->core.spin);
4411 if (bcmp(&bcopy, &sub->bref, sizeof(bcopy)) ||
4412 sub->parent != chain ||
4413 (sub->flags & HAMMER2_CHAIN_DELETED)) {
4414 hammer2_chain_unlock(sub);
4415 hammer2_chain_drop(sub);
4416 hammer2_spin_ex(&chain->core.spin);
4417 sub = NULL; /* safety */
4420 error = hammer2_chain_delete(chain, sub,
4421 sub->bref.modify_tid, 0);
4422 KKASSERT(error == 0);
4423 hammer2_chain_rename(&parent, sub,
4424 sub->bref.modify_tid,
4425 HAMMER2_INSERT_SAMEPARENT);
4426 hammer2_chain_unlock(sub);
4427 hammer2_chain_drop(sub);
4428 hammer2_spin_ex(&chain->core.spin);
4434 hammer2_spin_unex(&chain->core.spin);
4436 hammer2_chain_repchange(parent, chain);
4442 * Freemap indirect blocks
4444 * Calculate the keybits and highside/lowside of the freemap node the
4445 * caller is creating.
4447 * This routine will specify the next higher-level freemap key/radix
4448 * representing the lowest-ordered set. By doing so, eventually all
4449 * low-ordered sets will be moved one level down.
4451 * We have to be careful here because the freemap reserves a limited
4452 * number of blocks for a limited number of levels. So we can't just
4453 * push indiscriminately.
4456 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
4457 int keybits, hammer2_blockref_t *base, int count)
4459 hammer2_chain_t *chain;
4460 hammer2_blockref_t *bref;
4462 hammer2_key_t key_beg;
4463 hammer2_key_t key_end;
4464 hammer2_key_t key_next;
4467 int maxloops = 300000;
4475 * Calculate the range of keys in the array being careful to skip
4476 * slots which are overridden with a deletion.
4479 key_end = HAMMER2_KEY_MAX;
4480 hammer2_spin_ex(&parent->core.spin);
4483 if (--maxloops == 0) {
4484 panic("indkey_freemap shit %p %p:%d\n",
4485 parent, base, count);
4487 chain = hammer2_combined_find(parent, base, count,
4499 * Skip deleted chains.
4501 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4502 if (key_next == 0 || key_next > key_end)
4509 * Use the full live (not deleted) element for the scan
4510 * iteration. HAMMER2 does not allow partial replacements.
4512 * XXX should be built into hammer2_combined_find().
4514 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4516 if (keybits > bref->keybits) {
4518 keybits = bref->keybits;
4519 } else if (keybits == bref->keybits && bref->key < key) {
4526 hammer2_spin_unex(&parent->core.spin);
4529 * Return the keybits for a higher-level FREEMAP_NODE covering
4533 case HAMMER2_FREEMAP_LEVEL0_RADIX:
4534 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
4536 case HAMMER2_FREEMAP_LEVEL1_RADIX:
4537 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
4539 case HAMMER2_FREEMAP_LEVEL2_RADIX:
4540 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
4542 case HAMMER2_FREEMAP_LEVEL3_RADIX:
4543 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
4545 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4546 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4548 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4549 panic("hammer2_chain_indkey_freemap: level too high");
4552 panic("hammer2_chain_indkey_freemap: bad radix");
4561 * File indirect blocks
4563 * Calculate the key/keybits for the indirect block to create by scanning
4564 * existing keys. The key being created is also passed in *keyp and can be
4565 * inside or outside the indirect block. Regardless, the indirect block
4566 * must hold at least two keys in order to guarantee sufficient space.
4568 * We use a modified version of the freemap's fixed radix tree, but taylored
4569 * for file data. Basically we configure an indirect block encompassing the
4573 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4574 int keybits, hammer2_blockref_t *base, int count,
4577 hammer2_chain_t *chain;
4578 hammer2_blockref_t *bref;
4580 hammer2_key_t key_beg;
4581 hammer2_key_t key_end;
4582 hammer2_key_t key_next;
4586 int maxloops = 300000;
4594 * Calculate the range of keys in the array being careful to skip
4595 * slots which are overridden with a deletion.
4597 * Locate the smallest key.
4600 key_end = HAMMER2_KEY_MAX;
4601 hammer2_spin_ex(&parent->core.spin);
4604 if (--maxloops == 0) {
4605 panic("indkey_freemap shit %p %p:%d\n",
4606 parent, base, count);
4608 chain = hammer2_combined_find(parent, base, count,
4620 * Skip deleted chains.
4622 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4623 if (key_next == 0 || key_next > key_end)
4630 * Use the full live (not deleted) element for the scan
4631 * iteration. HAMMER2 does not allow partial replacements.
4633 * XXX should be built into hammer2_combined_find().
4635 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4637 if (keybits > bref->keybits) {
4639 keybits = bref->keybits;
4640 } else if (keybits == bref->keybits && bref->key < key) {
4647 hammer2_spin_unex(&parent->core.spin);
4650 * Calculate the static keybits for a higher-level indirect block
4651 * that contains the key.
4656 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4657 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4659 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4660 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4662 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4663 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4666 panic("bad ncount %d\n", ncount);
4672 * The largest radix that can be returned for an indirect block is
4673 * 63 bits. (The largest practical indirect block radix is actually
4674 * 62 bits because the top-level inode or volume root contains four
4675 * entries, but allow 63 to be returned).
4680 return keybits + nradix;
4686 * Directory indirect blocks.
4688 * Covers both the inode index (directory of inodes), and directory contents
4689 * (filenames hardlinked to inodes).
4691 * Because directory keys are hashed we generally try to cut the space in
4692 * half. We accomodate the inode index (which tends to have linearly
4693 * increasing inode numbers) by ensuring that the keyspace is at least large
4694 * enough to fill up the indirect block being created.
4697 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4698 int keybits, hammer2_blockref_t *base, int count,
4701 hammer2_blockref_t *bref;
4702 hammer2_chain_t *chain;
4703 hammer2_key_t key_beg;
4704 hammer2_key_t key_end;
4705 hammer2_key_t key_next;
4710 int maxloops = 300000;
4713 * NOTE: We can't take a shortcut here anymore for inodes because
4714 * the root directory can contain a mix of inodes and directory
4715 * entries (we used to just return 63 if parent->bref.type was
4716 * HAMMER2_BREF_TYPE_INODE.
4723 * Calculate the range of keys in the array being careful to skip
4724 * slots which are overridden with a deletion.
4727 key_end = HAMMER2_KEY_MAX;
4728 hammer2_spin_ex(&parent->core.spin);
4731 if (--maxloops == 0) {
4732 panic("indkey_freemap shit %p %p:%d\n",
4733 parent, base, count);
4735 chain = hammer2_combined_find(parent, base, count,
4749 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4750 if (key_next == 0 || key_next > key_end)
4757 * Use the full live (not deleted) element for the scan
4758 * iteration. HAMMER2 does not allow partial replacements.
4760 * XXX should be built into hammer2_combined_find().
4762 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4765 * Expand our calculated key range (key, keybits) to fit
4766 * the scanned key. nkeybits represents the full range
4767 * that we will later cut in half (two halves @ nkeybits - 1).
4770 if (nkeybits < bref->keybits) {
4771 if (bref->keybits > 64) {
4772 kprintf("bad bref chain %p bref %p\n",
4776 nkeybits = bref->keybits;
4778 while (nkeybits < 64 &&
4779 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4780 (key ^ bref->key)) != 0) {
4785 * If the new key range is larger we have to determine
4786 * which side of the new key range the existing keys fall
4787 * under by checking the high bit, then collapsing the
4788 * locount into the hicount or vise-versa.
4790 if (keybits != nkeybits) {
4791 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4802 * The newly scanned key will be in the lower half or the
4803 * upper half of the (new) key range.
4805 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4814 hammer2_spin_unex(&parent->core.spin);
4815 bref = NULL; /* now invalid (safety) */
4818 * Adjust keybits to represent half of the full range calculated
4819 * above (radix 63 max) for our new indirect block.
4824 * Expand keybits to hold at least ncount elements. ncount will be
4825 * a power of 2. This is to try to completely fill leaf nodes (at
4826 * least for keys which are not hashes).
4828 * We aren't counting 'in' or 'out', we are counting 'high side'
4829 * and 'low side' based on the bit at (1LL << keybits). We want
4830 * everything to be inside in these cases so shift it all to
4831 * the low or high side depending on the new high bit.
4833 while (((hammer2_key_t)1 << keybits) < ncount) {
4835 if (key & ((hammer2_key_t)1 << keybits)) {
4844 if (hicount > locount)
4845 key |= (hammer2_key_t)1 << keybits;
4847 key &= ~(hammer2_key_t)1 << keybits;
4857 * Directory indirect blocks.
4859 * Covers both the inode index (directory of inodes), and directory contents
4860 * (filenames hardlinked to inodes).
4862 * Because directory keys are hashed we generally try to cut the space in
4863 * half. We accomodate the inode index (which tends to have linearly
4864 * increasing inode numbers) by ensuring that the keyspace is at least large
4865 * enough to fill up the indirect block being created.
4868 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4869 int keybits, hammer2_blockref_t *base, int count,
4872 hammer2_blockref_t *bref;
4873 hammer2_chain_t *chain;
4874 hammer2_key_t key_beg;
4875 hammer2_key_t key_end;
4876 hammer2_key_t key_next;
4881 int maxloops = 300000;
4884 * Shortcut if the parent is the inode. In this situation the
4885 * parent has 4+1 directory entries and we are creating an indirect
4886 * block capable of holding many more.
4888 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4897 * Calculate the range of keys in the array being careful to skip
4898 * slots which are overridden with a deletion.
4901 key_end = HAMMER2_KEY_MAX;
4902 hammer2_spin_ex(&parent->core.spin);
4905 if (--maxloops == 0) {
4906 panic("indkey_freemap shit %p %p:%d\n",
4907 parent, base, count);
4909 chain = hammer2_combined_find(parent, base, count,
4923 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4924 if (key_next == 0 || key_next > key_end)
4931 * Use the full live (not deleted) element for the scan
4932 * iteration. HAMMER2 does not allow partial replacements.
4934 * XXX should be built into hammer2_combined_find().
4936 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4939 * Expand our calculated key range (key, keybits) to fit
4940 * the scanned key. nkeybits represents the full range
4941 * that we will later cut in half (two halves @ nkeybits - 1).
4944 if (nkeybits < bref->keybits) {
4945 if (bref->keybits > 64) {
4946 kprintf("bad bref chain %p bref %p\n",
4950 nkeybits = bref->keybits;
4952 while (nkeybits < 64 &&
4953 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4954 (key ^ bref->key)) != 0) {
4959 * If the new key range is larger we have to determine
4960 * which side of the new key range the existing keys fall
4961 * under by checking the high bit, then collapsing the
4962 * locount into the hicount or vise-versa.
4964 if (keybits != nkeybits) {
4965 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4976 * The newly scanned key will be in the lower half or the
4977 * upper half of the (new) key range.
4979 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4988 hammer2_spin_unex(&parent->core.spin);
4989 bref = NULL; /* now invalid (safety) */
4992 * Adjust keybits to represent half of the full range calculated
4993 * above (radix 63 max) for our new indirect block.
4998 * Expand keybits to hold at least ncount elements. ncount will be
4999 * a power of 2. This is to try to completely fill leaf nodes (at
5000 * least for keys which are not hashes).
5002 * We aren't counting 'in' or 'out', we are counting 'high side'
5003 * and 'low side' based on the bit at (1LL << keybits). We want
5004 * everything to be inside in these cases so shift it all to
5005 * the low or high side depending on the new high bit.
5007 while (((hammer2_key_t)1 << keybits) < ncount) {
5009 if (key & ((hammer2_key_t)1 << keybits)) {
5018 if (hicount > locount)
5019 key |= (hammer2_key_t)1 << keybits;
5021 key &= ~(hammer2_key_t)1 << keybits;
5031 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
5034 * Both parent and chain must be locked exclusively.
5036 * This function will modify the parent if the blockref requires removal
5037 * from the parent's block table.
5039 * This function is NOT recursive. Any entity already pushed into the
5040 * chain (such as an inode) may still need visibility into its contents,
5041 * as well as the ability to read and modify the contents. For example,
5042 * for an unlinked file which is still open.
5044 * Also note that the flusher is responsible for cleaning up empty
5048 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
5049 hammer2_tid_t mtid, int flags)
5053 KKASSERT(hammer2_mtx_owned(&chain->lock));
5056 * Nothing to do if already marked.
5058 * We need the spinlock on the core whos RBTREE contains chain
5059 * to protect against races.
5061 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
5062 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
5063 chain->parent == parent);
5064 error = _hammer2_chain_delete_helper(parent, chain,
5069 * Permanent deletions mark the chain as destroyed.
5071 * NOTE: We do not setflush the chain unless the deletion is
5072 * permanent, since the deletion of a chain does not actually
5073 * require it to be flushed.
5076 if (flags & HAMMER2_DELETE_PERMANENT) {
5077 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
5078 hammer2_chain_setflush(chain);
5086 * Returns the index of the nearest element in the blockref array >= elm.
5087 * Returns (count) if no element could be found.
5089 * Sets *key_nextp to the next key for loop purposes but does not modify
5090 * it if the next key would be higher than the current value of *key_nextp.
5091 * Note that *key_nexp can overflow to 0, which should be tested by the
5094 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5095 * held through the operation.
5098 hammer2_base_find(hammer2_chain_t *parent,
5099 hammer2_blockref_t *base, int count,
5100 hammer2_key_t *key_nextp,
5101 hammer2_key_t key_beg, hammer2_key_t key_end)
5103 hammer2_blockref_t *scan;
5104 hammer2_key_t scan_end;
5109 * Require the live chain's already have their core's counted
5110 * so we can optimize operations.
5112 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
5117 if (count == 0 || base == NULL)
5121 * Sequential optimization using parent->cache_index. This is
5122 * the most likely scenario.
5124 * We can avoid trailing empty entries on live chains, otherwise
5125 * we might have to check the whole block array.
5127 i = parent->cache_index; /* SMP RACE OK */
5129 limit = parent->core.live_zero;
5134 KKASSERT(i < count);
5140 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
5144 parent->cache_index = i;
5147 * Search forwards, stop when we find a scan element which
5148 * encloses the key or until we know that there are no further
5152 if (scan->type != 0) {
5153 scan_end = scan->key +
5154 ((hammer2_key_t)1 << scan->keybits) - 1;
5155 if (scan->key > key_beg || scan_end >= key_beg)
5164 parent->cache_index = i;
5168 scan_end = scan->key +
5169 ((hammer2_key_t)1 << scan->keybits);
5170 if (scan_end && (*key_nextp > scan_end ||
5172 *key_nextp = scan_end;
5180 * Do a combined search and return the next match either from the blockref
5181 * array or from the in-memory chain. Sets *bresp to the returned bref in
5182 * both cases, or sets it to NULL if the search exhausted. Only returns
5183 * a non-NULL chain if the search matched from the in-memory chain.
5185 * When no in-memory chain has been found and a non-NULL bref is returned
5189 * The returned chain is not locked or referenced. Use the returned bref
5190 * to determine if the search exhausted or not. Iterate if the base find
5191 * is chosen but matches a deleted chain.
5193 * WARNING! Must be called with parent's spinlock held. Spinlock remains
5194 * held through the operation.
5197 hammer2_combined_find(hammer2_chain_t *parent,
5198 hammer2_blockref_t *base, int count,
5199 hammer2_key_t *key_nextp,
5200 hammer2_key_t key_beg, hammer2_key_t key_end,
5201 hammer2_blockref_t **bresp)
5203 hammer2_blockref_t *bref;
5204 hammer2_chain_t *chain;
5208 * Lookup in block array and in rbtree.
5210 *key_nextp = key_end + 1;
5211 i = hammer2_base_find(parent, base, count, key_nextp,
5213 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
5218 if (i == count && chain == NULL) {
5224 * Only chain matched.
5227 bref = &chain->bref;
5232 * Only blockref matched.
5234 if (chain == NULL) {
5240 * Both in-memory and blockref matched, select the nearer element.
5242 * If both are flush with the left-hand side or both are the
5243 * same distance away, select the chain. In this situation the
5244 * chain must have been loaded from the matching blockmap.
5246 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
5247 chain->bref.key == base[i].key) {
5248 KKASSERT(chain->bref.key == base[i].key);
5249 bref = &chain->bref;
5254 * Select the nearer key
5256 if (chain->bref.key < base[i].key) {
5257 bref = &chain->bref;
5264 * If the bref is out of bounds we've exhausted our search.
5267 if (bref->key > key_end) {
5277 * Locate the specified block array element and delete it. The element
5280 * The spin lock on the related chain must be held.
5282 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5283 * need to be adjusted when we commit the media change.
5286 hammer2_base_delete(hammer2_chain_t *parent,
5287 hammer2_blockref_t *base, int count,
5288 hammer2_chain_t *chain)
5290 hammer2_blockref_t *elm = &chain->bref;
5291 hammer2_blockref_t *scan;
5292 hammer2_key_t key_next;
5296 * Delete element. Expect the element to exist.
5298 * XXX see caller, flush code not yet sophisticated enough to prevent
5299 * re-flushed in some cases.
5301 key_next = 0; /* max range */
5302 i = hammer2_base_find(parent, base, count, &key_next,
5303 elm->key, elm->key);
5305 if (i == count || scan->type == 0 ||
5306 scan->key != elm->key ||
5307 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
5308 scan->keybits != elm->keybits)) {
5309 hammer2_spin_unex(&parent->core.spin);
5310 panic("delete base %p element not found at %d/%d elm %p\n",
5311 base, i, count, elm);
5316 * Update stats and zero the entry.
5318 * NOTE: Handle radix == 0 (0 bytes) case.
5320 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
5321 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
5322 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
5324 switch(scan->type) {
5325 case HAMMER2_BREF_TYPE_INODE:
5326 --parent->bref.embed.stats.inode_count;
5328 case HAMMER2_BREF_TYPE_DATA:
5329 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5330 atomic_set_int(&chain->flags,
5331 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5333 if (parent->bref.leaf_count)
5334 --parent->bref.leaf_count;
5337 case HAMMER2_BREF_TYPE_INDIRECT:
5338 if (scan->type != HAMMER2_BREF_TYPE_DATA) {
5339 parent->bref.embed.stats.data_count -=
5340 scan->embed.stats.data_count;
5341 parent->bref.embed.stats.inode_count -=
5342 scan->embed.stats.inode_count;
5344 if (scan->type == HAMMER2_BREF_TYPE_INODE)
5346 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5347 atomic_set_int(&chain->flags,
5348 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5350 if (parent->bref.leaf_count <= scan->leaf_count)
5351 parent->bref.leaf_count = 0;
5353 parent->bref.leaf_count -= scan->leaf_count;
5356 case HAMMER2_BREF_TYPE_DIRENT:
5357 if (parent->bref.leaf_count == HAMMER2_BLOCKREF_LEAF_MAX) {
5358 atomic_set_int(&chain->flags,
5359 HAMMER2_CHAIN_HINT_LEAF_COUNT);
5361 if (parent->bref.leaf_count)
5362 --parent->bref.leaf_count;
5368 bzero(scan, sizeof(*scan));
5371 * We can only optimize parent->core.live_zero for live chains.
5373 if (parent->core.live_zero == i + 1) {
5374 while (--i >= 0 && base[i].type == 0)
5376 parent->core.live_zero = i + 1;
5380 * Clear appropriate blockmap flags in chain.
5382 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
5383 HAMMER2_CHAIN_BMAPUPD);
5387 * Insert the specified element. The block array must not already have the
5388 * element and must have space available for the insertion.
5390 * The spin lock on the related chain must be held.
5392 * NOTE: live_count was adjusted when the chain was deleted, so it does not
5393 * need to be adjusted when we commit the media change.
5396 hammer2_base_insert(hammer2_chain_t *parent,
5397 hammer2_blockref_t *base, int count,
5398 hammer2_chain_t *chain, hammer2_blockref_t *elm)
5400 hammer2_key_t key_next;
5409 * Insert new element. Expect the element to not already exist
5410 * unless we are replacing it.
5412 * XXX see caller, flush code not yet sophisticated enough to prevent
5413 * re-flushed in some cases.
5415 key_next = 0; /* max range */
5416 i = hammer2_base_find(parent, base, count, &key_next,
5417 elm->key, elm->key);
5420 * Shortcut fill optimization, typical ordered insertion(s) may not
5423 KKASSERT(i >= 0 && i <= count);
5426 * Set appropriate blockmap flags in chain (if not NULL)
5429 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
5432 * Update stats and zero the entry
5434 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
5435 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
5436 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
5439 case HAMMER2_BREF_TYPE_INODE:
5440 ++parent->bref.embed.stats.inode_count;
5442 case HAMMER2_BREF_TYPE_DATA:
5443 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5444 ++parent->bref.leaf_count;
5446 case HAMMER2_BREF_TYPE_INDIRECT:
5447 if (elm->type != HAMMER2_BREF_TYPE_DATA) {
5448 parent->bref.embed.stats.data_count +=
5449 elm->embed.stats.data_count;
5450 parent->bref.embed.stats.inode_count +=
5451 elm->embed.stats.inode_count;
5453 if (elm->type == HAMMER2_BREF_TYPE_INODE)
5455 if (parent->bref.leaf_count + elm->leaf_count <
5456 HAMMER2_BLOCKREF_LEAF_MAX) {
5457 parent->bref.leaf_count += elm->leaf_count;
5459 parent->bref.leaf_count = HAMMER2_BLOCKREF_LEAF_MAX;
5462 case HAMMER2_BREF_TYPE_DIRENT:
5463 if (parent->bref.leaf_count != HAMMER2_BLOCKREF_LEAF_MAX)
5464 ++parent->bref.leaf_count;
5472 * We can only optimize parent->core.live_zero for live chains.
5474 if (i == count && parent->core.live_zero < count) {
5475 i = parent->core.live_zero++;
5480 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
5481 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
5482 hammer2_spin_unex(&parent->core.spin);
5483 panic("insert base %p overlapping elements at %d elm %p\n",
5488 * Try to find an empty slot before or after.
5492 while (j > 0 || k < count) {
5494 if (j >= 0 && base[j].type == 0) {
5498 bcopy(&base[j+1], &base[j],
5499 (i - j - 1) * sizeof(*base));
5505 if (k < count && base[k].type == 0) {
5506 bcopy(&base[i], &base[i+1],
5507 (k - i) * sizeof(hammer2_blockref_t));
5511 * We can only update parent->core.live_zero for live
5514 if (parent->core.live_zero <= k)
5515 parent->core.live_zero = k + 1;
5520 panic("hammer2_base_insert: no room!");
5527 for (l = 0; l < count; ++l) {
5529 key_next = base[l].key +
5530 ((hammer2_key_t)1 << base[l].keybits) - 1;
5534 while (++l < count) {
5536 if (base[l].key <= key_next)
5537 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
5538 key_next = base[l].key +
5539 ((hammer2_key_t)1 << base[l].keybits) - 1;
5549 * Sort the blockref array for the chain. Used by the flush code to
5550 * sort the blockref[] array.
5552 * The chain must be exclusively locked AND spin-locked.
5554 typedef hammer2_blockref_t *hammer2_blockref_p;
5558 hammer2_base_sort_callback(const void *v1, const void *v2)
5560 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
5561 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
5564 * Make sure empty elements are placed at the end of the array
5566 if (bref1->type == 0) {
5567 if (bref2->type == 0)
5570 } else if (bref2->type == 0) {
5577 if (bref1->key < bref2->key)
5579 if (bref1->key > bref2->key)
5585 hammer2_base_sort(hammer2_chain_t *chain)
5587 hammer2_blockref_t *base;
5590 switch(chain->bref.type) {
5591 case HAMMER2_BREF_TYPE_INODE:
5593 * Special shortcut for embedded data returns the inode
5594 * itself. Callers must detect this condition and access
5595 * the embedded data (the strategy code does this for us).
5597 * This is only applicable to regular files and softlinks.
5599 if (chain->data->ipdata.meta.op_flags &
5600 HAMMER2_OPFLAG_DIRECTDATA) {
5603 base = &chain->data->ipdata.u.blockset.blockref[0];
5604 count = HAMMER2_SET_COUNT;
5606 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5607 case HAMMER2_BREF_TYPE_INDIRECT:
5609 * Optimize indirect blocks in the INITIAL state to avoid
5612 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5613 base = &chain->data->npdata[0];
5614 count = chain->bytes / sizeof(hammer2_blockref_t);
5616 case HAMMER2_BREF_TYPE_VOLUME:
5617 base = &chain->data->voldata.sroot_blockset.blockref[0];
5618 count = HAMMER2_SET_COUNT;
5620 case HAMMER2_BREF_TYPE_FREEMAP:
5621 base = &chain->data->blkset.blockref[0];
5622 count = HAMMER2_SET_COUNT;
5625 kprintf("hammer2_chain_lookup: unrecognized "
5626 "blockref(A) type: %d",
5629 tsleep(&base, 0, "dead", 0);
5630 panic("hammer2_chain_lookup: unrecognized "
5631 "blockref(A) type: %d",
5633 base = NULL; /* safety */
5634 count = 0; /* safety */
5636 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5642 * Chain memory management
5645 hammer2_chain_wait(hammer2_chain_t *chain)
5647 tsleep(chain, 0, "chnflw", 1);
5650 const hammer2_media_data_t *
5651 hammer2_chain_rdata(hammer2_chain_t *chain)
5653 KKASSERT(chain->data != NULL);
5654 return (chain->data);
5657 hammer2_media_data_t *
5658 hammer2_chain_wdata(hammer2_chain_t *chain)
5660 KKASSERT(chain->data != NULL);
5661 return (chain->data);
5665 * Set the check data for a chain. This can be a heavy-weight operation
5666 * and typically only runs on-flush. For file data check data is calculated
5667 * when the logical buffers are flushed.
5670 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5672 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5674 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5675 case HAMMER2_CHECK_NONE:
5677 case HAMMER2_CHECK_DISABLED:
5679 case HAMMER2_CHECK_ISCSI32:
5680 chain->bref.check.iscsi32.value =
5681 hammer2_icrc32(bdata, chain->bytes);
5683 case HAMMER2_CHECK_XXHASH64:
5684 chain->bref.check.xxhash64.value =
5685 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5687 case HAMMER2_CHECK_SHA192:
5689 SHA256_CTX hash_ctx;
5691 uint8_t digest[SHA256_DIGEST_LENGTH];
5692 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5695 SHA256_Init(&hash_ctx);
5696 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5697 SHA256_Final(u.digest, &hash_ctx);
5698 u.digest64[2] ^= u.digest64[3];
5700 chain->bref.check.sha192.data,
5701 sizeof(chain->bref.check.sha192.data));
5704 case HAMMER2_CHECK_FREEMAP:
5705 chain->bref.check.freemap.icrc32 =
5706 hammer2_icrc32(bdata, chain->bytes);
5709 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5710 chain->bref.methods);
5716 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5722 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5725 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5726 case HAMMER2_CHECK_NONE:
5729 case HAMMER2_CHECK_DISABLED:
5732 case HAMMER2_CHECK_ISCSI32:
5733 check32 = hammer2_icrc32(bdata, chain->bytes);
5734 r = (chain->bref.check.iscsi32.value == check32);
5736 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5737 "(flags=%08x, bref/data %08x/%08x)\n",
5738 chain->bref.data_off,
5740 chain->bref.methods,
5742 chain->bref.check.iscsi32.value,
5745 hammer2_process_icrc32 += chain->bytes;
5747 case HAMMER2_CHECK_XXHASH64:
5748 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5749 r = (chain->bref.check.xxhash64.value == check64);
5751 kprintf("chain %016jx.%02x key=%016jx "
5752 "meth=%02x CHECK FAIL "
5753 "(flags=%08x, bref/data %016jx/%016jx)\n",
5754 chain->bref.data_off,
5757 chain->bref.methods,
5759 chain->bref.check.xxhash64.value,
5762 hammer2_process_xxhash64 += chain->bytes;
5764 case HAMMER2_CHECK_SHA192:
5766 SHA256_CTX hash_ctx;
5768 uint8_t digest[SHA256_DIGEST_LENGTH];
5769 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5772 SHA256_Init(&hash_ctx);
5773 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5774 SHA256_Final(u.digest, &hash_ctx);
5775 u.digest64[2] ^= u.digest64[3];
5777 chain->bref.check.sha192.data,
5778 sizeof(chain->bref.check.sha192.data)) == 0) {
5782 kprintf("chain %016jx.%02x meth=%02x "
5784 chain->bref.data_off,
5786 chain->bref.methods);
5790 case HAMMER2_CHECK_FREEMAP:
5791 r = (chain->bref.check.freemap.icrc32 ==
5792 hammer2_icrc32(bdata, chain->bytes));
5794 kprintf("chain %016jx.%02x meth=%02x "
5796 chain->bref.data_off,
5798 chain->bref.methods);
5799 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5800 chain->bref.check.freemap.icrc32,
5801 hammer2_icrc32(bdata, chain->bytes),
5804 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5805 chain->dio, chain->dio->bp->b_loffset,
5806 chain->dio->bp->b_bufsize, bdata,
5807 chain->dio->bp->b_data);
5812 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5813 chain->bref.methods);
5821 * Acquire the chain and parent representing the specified inode for the
5822 * device at the specified cluster index.
5824 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5826 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5827 * will be NULL. *parentp may still be set error or not, or NULL if the
5828 * parent itself could not be resolved.
5830 * Caller must pass-in a valid (and locked), or NULL *parentp or *chainp.
5831 * This function replaces *parentp and *chainp. Generally speaking, if
5832 * the caller found a directory entry and wants the inode, the caller should
5833 * pass the parent,chain representing the directory entry so this function
5834 * can dispose of it properly to avoid any possible lock order reversals.
5837 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5838 int clindex, int flags,
5839 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5841 hammer2_chain_t *parent;
5842 hammer2_chain_t *rchain;
5843 hammer2_key_t key_dummy;
5847 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5848 HAMMER2_RESOLVE_SHARED : 0;
5851 * Caller expects us to replace these.
5854 hammer2_chain_unlock(*chainp);
5855 hammer2_chain_drop(*chainp);
5859 hammer2_chain_unlock(*parentp);
5860 hammer2_chain_drop(*parentp);
5865 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5866 * inodes from root directory entries in the key lookup).
5868 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5871 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5875 error = HAMMER2_ERROR_EIO;
5884 * Used by the bulkscan code to snapshot the synchronized storage for
5885 * a volume, allowing it to be scanned concurrently against normal
5889 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5891 hammer2_chain_t *copy;
5893 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5894 copy->data = kmalloc(sizeof(copy->data->voldata),
5897 hammer2_voldata_lock(hmp);
5898 copy->data->voldata = hmp->volsync;
5899 hammer2_voldata_unlock(hmp);
5905 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5907 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5908 KKASSERT(copy->data);
5909 kfree(copy->data, copy->hmp->mchain);
5911 atomic_add_long(&hammer2_chain_allocs, -1);
5912 hammer2_chain_drop(copy);
5916 * Returns non-zero if the chain (INODE or DIRENT) matches the
5920 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5923 const hammer2_inode_data_t *ripdata;
5924 const hammer2_dirent_head_t *den;
5926 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5927 ripdata = &chain->data->ipdata;
5928 if (ripdata->meta.name_len == name_len &&
5929 bcmp(ripdata->filename, name, name_len) == 0) {
5933 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5934 chain->bref.embed.dirent.namlen == name_len) {
5935 den = &chain->bref.embed.dirent;
5936 if (name_len > sizeof(chain->bref.check.buf) &&
5937 bcmp(chain->data->buf, name, name_len) == 0) {
5940 if (name_len <= sizeof(chain->bref.check.buf) &&
5941 bcmp(chain->bref.check.buf, name, name_len) == 0) {