hammer2 - error handling 2/N (chain_lookup/chain_next)
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
blob0d2ff2a1de9ae0e116dd94857f94bf763fa2c087
1 /*
2 * Copyright (c) 2011-2015 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * and Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
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
17 * distribution.
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
33 * SUCH DAMAGE.
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
41 * HAMMER2 topology.
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
47 * upward to the root.
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>
59 #include <sys/lock.h>
60 #include <sys/kern_syscall.h>
61 #include <sys/uuid.h>
63 #include <crypto/sha2/sha2.h>
65 #include "hammer2.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);
80 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
81 * overlap in the RB trees. Deleted chains are moved from rbtree to either
82 * dbtree or to dbq.
84 * Chains in delete-duplicate sequences can always iterate through core_entry
85 * to locate the live version of the chain.
87 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
89 int
90 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
92 hammer2_key_t c1_beg;
93 hammer2_key_t c1_end;
94 hammer2_key_t c2_beg;
95 hammer2_key_t c2_end;
98 * Compare chains. Overlaps are not supposed to happen and catch
99 * any software issues early we count overlaps as a match.
101 c1_beg = chain1->bref.key;
102 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
103 c2_beg = chain2->bref.key;
104 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
106 if (c1_end < c2_beg) /* fully to the left */
107 return(-1);
108 if (c1_beg > c2_end) /* fully to the right */
109 return(1);
110 return(0); /* overlap (must not cross edge boundary) */
114 * Assert that a chain has no media data associated with it.
116 static __inline void
117 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
119 KKASSERT(chain->dio == NULL);
120 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
121 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
122 chain->data) {
123 panic("hammer2_assert_no_data: chain %p still has data", chain);
128 * Make a chain visible to the flusher. The flusher needs to be able to
129 * do flushes of subdirectory chains or single files so it does a top-down
130 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
131 * or UPDATE chains and flushes back up the chain to the volume root.
133 * This routine sets ONFLUSH upward until it hits the volume root. For
134 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
135 * Extra ONFLUSH flagging doesn't hurt the filesystem.
137 void
138 hammer2_chain_setflush(hammer2_chain_t *chain)
140 hammer2_chain_t *parent;
142 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
143 hammer2_spin_sh(&chain->core.spin);
144 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
145 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
146 if ((parent = chain->parent) == NULL)
147 break;
148 hammer2_spin_sh(&parent->core.spin);
149 hammer2_spin_unsh(&chain->core.spin);
150 chain = parent;
152 hammer2_spin_unsh(&chain->core.spin);
157 * Allocate a new disconnected chain element representing the specified
158 * bref. chain->refs is set to 1 and the passed bref is copied to
159 * chain->bref. chain->bytes is derived from the bref.
161 * chain->pmp inherits pmp unless the chain is an inode (other than the
162 * super-root inode).
164 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
166 hammer2_chain_t *
167 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
168 hammer2_blockref_t *bref)
170 hammer2_chain_t *chain;
171 u_int bytes;
174 * Special case - radix of 0 indicates a chain that does not
175 * need a data reference (context is completely embedded in the
176 * bref).
178 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
179 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
180 else
181 bytes = 0;
183 atomic_add_long(&hammer2_chain_allocs, 1);
186 * Construct the appropriate system structure.
188 switch(bref->type) {
189 case HAMMER2_BREF_TYPE_DIRENT:
190 case HAMMER2_BREF_TYPE_INODE:
191 case HAMMER2_BREF_TYPE_INDIRECT:
192 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
193 case HAMMER2_BREF_TYPE_DATA:
194 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
196 * Chain's are really only associated with the hmp but we
197 * maintain a pmp association for per-mount memory tracking
198 * purposes. The pmp can be NULL.
200 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
201 break;
202 case HAMMER2_BREF_TYPE_VOLUME:
203 case HAMMER2_BREF_TYPE_FREEMAP:
205 * Only hammer2_chain_bulksnap() calls this function with these
206 * types.
208 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
209 break;
210 default:
211 chain = NULL;
212 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
213 bref->type);
217 * Initialize the new chain structure. pmp must be set to NULL for
218 * chains belonging to the super-root topology of a device mount.
220 if (pmp == hmp->spmp)
221 chain->pmp = NULL;
222 else
223 chain->pmp = pmp;
224 chain->hmp = hmp;
225 chain->bref = *bref;
226 chain->bytes = bytes;
227 chain->refs = 1;
228 chain->flags = HAMMER2_CHAIN_ALLOCATED;
231 * Set the PFS boundary flag if this chain represents a PFS root.
233 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
234 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
235 hammer2_chain_core_init(chain);
237 return (chain);
241 * Initialize a chain's core structure. This structure used to be allocated
242 * but is now embedded.
244 * The core is not locked. No additional refs on the chain are made.
245 * (trans) must not be NULL if (core) is not NULL.
247 void
248 hammer2_chain_core_init(hammer2_chain_t *chain)
251 * Fresh core under nchain (no multi-homing of ochain's
252 * sub-tree).
254 RB_INIT(&chain->core.rbtree); /* live chains */
255 hammer2_mtx_init(&chain->lock, "h2chain");
259 * Add a reference to a chain element, preventing its destruction.
261 * (can be called with spinlock held)
263 void
264 hammer2_chain_ref(hammer2_chain_t *chain)
266 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
268 * 0->non-zero transition must ensure that chain is removed
269 * from the LRU list.
271 * NOTE: Already holding lru_spin here so we cannot call
272 * hammer2_chain_ref() to get it off lru_list, do
273 * it manually.
275 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
276 hammer2_pfs_t *pmp = chain->pmp;
277 hammer2_spin_ex(&pmp->lru_spin);
278 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
279 atomic_add_int(&pmp->lru_count, -1);
280 atomic_clear_int(&chain->flags,
281 HAMMER2_CHAIN_ONLRU);
282 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
284 hammer2_spin_unex(&pmp->lru_spin);
287 #if 0
288 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
289 print_backtrace(8);
290 #endif
294 * Ref a locked chain and force the data to be held across an unlock.
295 * Chain must be currently locked. The user of the chain who desires
296 * to release the hold must call hammer2_chain_lock_unhold() to relock
297 * and unhold the chain, then unlock normally, or may simply call
298 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
300 void
301 hammer2_chain_ref_hold(hammer2_chain_t *chain)
303 atomic_add_int(&chain->lockcnt, 1);
304 hammer2_chain_ref(chain);
308 * Insert the chain in the core rbtree.
310 * Normal insertions are placed in the live rbtree. Insertion of a deleted
311 * chain is a special case used by the flush code that is placed on the
312 * unstaged deleted list to avoid confusing the live view.
314 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
315 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
316 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
318 static
320 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
321 int flags, int generation)
323 hammer2_chain_t *xchain;
324 int error = 0;
326 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
327 hammer2_spin_ex(&parent->core.spin);
330 * Interlocked by spinlock, check for race
332 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
333 parent->core.generation != generation) {
334 error = EAGAIN;
335 goto failed;
339 * Insert chain
341 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
342 KASSERT(xchain == NULL,
343 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
344 chain, xchain, chain->bref.key));
345 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
346 chain->parent = parent;
347 ++parent->core.chain_count;
348 ++parent->core.generation; /* XXX incs for _get() too, XXX */
351 * We have to keep track of the effective live-view blockref count
352 * so the create code knows when to push an indirect block.
354 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
355 atomic_add_int(&parent->core.live_count, 1);
356 failed:
357 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
358 hammer2_spin_unex(&parent->core.spin);
359 return error;
363 * Drop the caller's reference to the chain. When the ref count drops to
364 * zero this function will try to disassociate the chain from its parent and
365 * deallocate it, then recursely drop the parent using the implied ref
366 * from the chain's chain->parent.
368 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
369 * races an acquisition by another cpu. Therefore we can loop if we are
370 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
371 * race against another drop.
373 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
375 void
376 hammer2_chain_drop(hammer2_chain_t *chain)
378 u_int refs;
380 if (hammer2_debug & 0x200000)
381 Debugger("drop");
382 #if 0
383 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
384 print_backtrace(8);
385 #endif
387 KKASSERT(chain->refs > 0);
389 while (chain) {
390 refs = chain->refs;
391 cpu_ccfence();
392 KKASSERT(refs > 0);
394 if (refs == 1) {
395 if (mtx_lock_ex_try(&chain->lock) == 0)
396 chain = hammer2_chain_lastdrop(chain);
397 /* retry the same chain */
398 } else {
399 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
400 break;
401 /* retry the same chain */
403 cpu_pause();
408 * Unhold a held and probably not-locked chain, ensure that the data is
409 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
410 * lock and then simply unlocking the chain.
412 void
413 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
415 u_int lockcnt;
416 int iter = 0;
418 for (;;) {
419 lockcnt = chain->lockcnt;
420 cpu_ccfence();
421 if (lockcnt > 1) {
422 if (atomic_cmpset_int(&chain->lockcnt,
423 lockcnt, lockcnt - 1)) {
424 break;
426 } else if (mtx_lock_ex_try(&chain->lock) == 0) {
427 hammer2_chain_unlock(chain);
428 break;
429 } else {
431 * This situation can easily occur on SMP due to
432 * the gap inbetween the 1->0 transition and the
433 * final unlock. We cannot safely block on the
434 * mutex because lockcnt might go above 1.
436 * XXX Sleep for one tick if it takes too long.
438 if (++iter > 1000) {
439 if (iter > 1000 + hz) {
440 kprintf("hammer2: h2race1 %p\n", chain);
441 iter = 1000;
443 tsleep(&iter, 0, "h2race1", 1);
445 cpu_pause();
448 hammer2_chain_drop(chain);
452 * Handles the (potential) last drop of chain->refs from 1->0. Called with
453 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
454 * possible against refs and lockcnt. We must dispose of the mutex on chain.
456 * This function returns an unlocked chain for recursive drop or NULL. It
457 * can return the same chain if it determines it has raced another ref.
459 * --
461 * When two chains need to be recursively dropped we use the chain we
462 * would otherwise free to placehold the additional chain. It's a bit
463 * convoluted but we can't just recurse without potentially blowing out
464 * the kernel stack.
466 * The chain cannot be freed if it has any children.
467 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
468 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
469 * Any dedup registration can remain intact.
471 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
473 static
474 hammer2_chain_t *
475 hammer2_chain_lastdrop(hammer2_chain_t *chain)
477 hammer2_pfs_t *pmp;
478 hammer2_dev_t *hmp;
479 hammer2_chain_t *parent;
480 hammer2_chain_t *rdrop;
481 #if 0
482 hammer2_io_t *dio;
483 #endif
485 #if 0
487 * On last drop if there is no parent and data_off is good (at
488 * least does not represent the volume root), the modified chain
489 * is probably going to be destroyed. We have to make sure that
490 * the data area is not registered for dedup.
492 * XXX removed. In fact, we do not have to make sure that the
493 * data area is not registered for dedup. The data area
494 * can, in fact, still be used for dedup because it is
495 * still allocated in the freemap and the underlying I/O
496 * will still be flushed.
498 if (chain->parent == NULL &&
499 (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
500 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
501 hmp = chain->hmp;
502 hammer2_io_dedup_delete(hmp, chain->bref.type,
503 chain->bref.data_off, chain->bytes);
505 #endif
507 * We need chain's spinlock to interlock the sub-tree test.
508 * We already have chain's mutex, protecting chain->parent.
510 * Remember that chain->refs can be in flux.
512 hammer2_spin_ex(&chain->core.spin);
514 if ((parent = chain->parent) != NULL) {
516 * If the chain has a parent the UPDATE bit prevents scrapping
517 * as the chain is needed to properly flush the parent. Try
518 * to complete the 1->0 transition and return NULL. Retry
519 * (return chain) if we are unable to complete the 1->0
520 * transition, else return NULL (nothing more to do).
522 * If the chain has a parent the MODIFIED bit prevents
523 * scrapping.
525 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
527 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
528 HAMMER2_CHAIN_MODIFIED)) {
529 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
530 hammer2_spin_unex(&chain->core.spin);
531 #if 0
532 dio = hammer2_chain_drop_data(chain, 0);
533 if (dio)
534 hammer2_io_bqrelse(&dio);
535 #endif
536 hammer2_chain_assert_no_data(chain);
537 hammer2_mtx_unlock(&chain->lock);
538 chain = NULL;
539 } else {
540 hammer2_spin_unex(&chain->core.spin);
541 hammer2_mtx_unlock(&chain->lock);
543 return (chain);
545 /* spinlock still held */
546 } else {
548 * The chain has no parent and can be flagged for destruction.
549 * Since it has no parent, UPDATE can also be cleared.
551 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
552 if (chain->flags & HAMMER2_CHAIN_UPDATE)
553 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
556 * If the chain has children we must still flush the chain.
557 * Any dedup is already handled by the underlying DIO, so
558 * we do not have to specifically flush it here.
560 * In the case where it has children, the DESTROY flag test
561 * in the flush code will prevent unnecessary flushes of
562 * MODIFIED chains that are not flagged DEDUP so don't worry
563 * about that here.
565 if (chain->core.chain_count) {
567 * Put on flushq (should ensure refs > 1), retry
568 * the drop.
570 hammer2_spin_unex(&chain->core.spin);
571 hammer2_delayed_flush(chain);
572 hammer2_mtx_unlock(&chain->lock);
574 return(chain); /* retry drop */
578 * Otherwise we can scrap the MODIFIED bit if it is set,
579 * and continue along the freeing path.
581 * Be sure to clean-out any dedup bits. Without a parent
582 * this chain will no longer be visible to the flush code.
583 * Easy check data_off to avoid the volume root.
585 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
586 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
587 atomic_add_long(&hammer2_count_modified_chains, -1);
588 if (chain->pmp)
589 hammer2_pfs_memory_wakeup(chain->pmp);
591 /* spinlock still held */
594 /* spinlock still held */
595 #if 0
596 dio = NULL;
597 #endif
600 * If any children exist we must leave the chain intact with refs == 0.
601 * They exist because chains are retained below us which have refs or
602 * may require flushing.
604 * Retry (return chain) if we fail to transition the refs to 0, else
605 * return NULL indication nothing more to do.
607 * Chains with children are NOT put on the LRU list.
609 if (chain->core.chain_count) {
610 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
611 hammer2_spin_unex(&chain->core.spin);
612 hammer2_chain_assert_no_data(chain);
613 hammer2_mtx_unlock(&chain->lock);
614 chain = NULL;
615 } else {
616 hammer2_spin_unex(&chain->core.spin);
617 hammer2_mtx_unlock(&chain->lock);
619 return (chain);
621 /* spinlock still held */
622 /* no chains left under us */
625 * chain->core has no children left so no accessors can get to our
626 * chain from there. Now we have to lock the parent core to interlock
627 * remaining possible accessors that might bump chain's refs before
628 * we can safely drop chain's refs with intent to free the chain.
630 hmp = chain->hmp;
631 pmp = chain->pmp; /* can be NULL */
632 rdrop = NULL;
634 parent = chain->parent;
637 * WARNING! chain's spin lock is still held here, and other spinlocks
638 * will be acquired and released in the code below. We
639 * cannot be making fancy procedure calls!
643 * We can cache the chain if it is associated with a pmp
644 * and not flagged as being destroyed or requesting a full
645 * release. In this situation the chain is not removed
646 * from its parent, i.e. it can still be looked up.
648 * We intentionally do not cache DATA chains because these
649 * were likely used to load data into the logical buffer cache
650 * and will not be accessed again for some time.
652 if ((chain->flags &
653 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
654 chain->pmp &&
655 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
656 if (parent)
657 hammer2_spin_ex(&parent->core.spin);
658 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
660 * 1->0 transition failed, retry. Do not drop
661 * the chain's data yet!
663 if (parent)
664 hammer2_spin_unex(&parent->core.spin);
665 hammer2_spin_unex(&chain->core.spin);
666 hammer2_mtx_unlock(&chain->lock);
668 return(chain);
672 * Success
674 #if 0
675 dio = hammer2_chain_drop_data(chain, 1);
676 #endif
677 hammer2_chain_assert_no_data(chain);
679 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
680 hammer2_spin_ex(&pmp->lru_spin);
681 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
682 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
685 * If we are over the LRU limit we need to drop something.
687 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
688 rdrop = TAILQ_FIRST(&pmp->lru_list);
689 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
690 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
691 atomic_add_int(&rdrop->refs, 1);
692 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
693 } else {
694 atomic_add_int(&pmp->lru_count, 1);
696 hammer2_spin_unex(&pmp->lru_spin);
697 if (parent) {
698 hammer2_spin_unex(&parent->core.spin);
699 parent = NULL; /* safety */
701 hammer2_spin_unex(&chain->core.spin);
702 hammer2_mtx_unlock(&chain->lock);
703 #if 0
704 if (dio)
705 hammer2_io_bqrelse(&dio);
706 #endif
708 return rdrop;
709 /* NOT REACHED */
713 * Spinlock the parent and try to drop the last ref on chain.
714 * On success determine if we should dispose of the chain
715 * (remove the chain from its parent, etc).
717 * (normal core locks are top-down recursive but we define
718 * core spinlocks as bottom-up recursive, so this is safe).
720 if (parent) {
721 hammer2_spin_ex(&parent->core.spin);
722 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
723 #if 0
724 /* XXX remove, don't try to drop data on fail */
725 hammer2_spin_unex(&parent->core.spin);
726 dio = hammer2_chain_drop_data(chain, 0);
727 hammer2_spin_unex(&chain->core.spin);
728 if (dio)
729 hammer2_io_bqrelse(&dio);
730 #endif
732 * 1->0 transition failed, retry.
734 hammer2_spin_unex(&parent->core.spin);
735 hammer2_spin_unex(&chain->core.spin);
736 hammer2_mtx_unlock(&chain->lock);
738 return(chain);
742 * 1->0 transition successful, parent spin held to prevent
743 * new lookups, chain spinlock held to protect parent field.
744 * Remove chain from the parent.
746 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
747 RB_REMOVE(hammer2_chain_tree,
748 &parent->core.rbtree, chain);
749 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
750 --parent->core.chain_count;
751 chain->parent = NULL;
755 * If our chain was the last chain in the parent's core the
756 * core is now empty and its parent might have to be
757 * re-dropped if it has 0 refs.
759 if (parent->core.chain_count == 0) {
760 rdrop = parent;
761 atomic_add_int(&rdrop->refs, 1);
763 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
764 rdrop = NULL;
767 hammer2_spin_unex(&parent->core.spin);
768 parent = NULL; /* safety */
769 /* FALL THROUGH */
770 } else {
772 * No-parent case.
774 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
776 * 1->0 transition failed, retry.
778 hammer2_spin_unex(&parent->core.spin);
779 hammer2_spin_unex(&chain->core.spin);
780 hammer2_mtx_unlock(&chain->lock);
782 return(chain);
787 * Successful 1->0 transition, no parent, no children... no way for
788 * anyone to ref this chain any more. We can clean-up and free it.
790 * We still have the core spinlock, and core's chain_count is 0.
791 * Any parent spinlock is gone.
793 hammer2_spin_unex(&chain->core.spin);
794 hammer2_chain_assert_no_data(chain);
795 hammer2_mtx_unlock(&chain->lock);
796 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
797 chain->core.chain_count == 0);
800 * All locks are gone, no pointers remain to the chain, finish
801 * freeing it.
803 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
804 HAMMER2_CHAIN_MODIFIED)) == 0);
805 #if 0
806 dio = hammer2_chain_drop_data(chain, 1);
807 if (dio)
808 hammer2_io_bqrelse(&dio);
809 #endif
812 * Once chain resources are gone we can use the now dead chain
813 * structure to placehold what might otherwise require a recursive
814 * drop, because we have potentially two things to drop and can only
815 * return one directly.
817 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
818 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
819 chain->hmp = NULL;
820 kfree(chain, hmp->mchain);
824 * Possible chaining loop when parent re-drop needed.
826 return(rdrop);
830 * On last lock release.
832 static hammer2_io_t *
833 hammer2_chain_drop_data(hammer2_chain_t *chain)
835 hammer2_io_t *dio;
837 if ((dio = chain->dio) != NULL) {
838 chain->dio = NULL;
839 chain->data = NULL;
840 } else {
841 switch(chain->bref.type) {
842 case HAMMER2_BREF_TYPE_VOLUME:
843 case HAMMER2_BREF_TYPE_FREEMAP:
844 break;
845 default:
846 if (chain->data != NULL) {
847 hammer2_spin_unex(&chain->core.spin);
848 panic("chain data not null: "
849 "chain %p bref %016jx.%02x "
850 "refs %d parent %p dio %p data %p",
851 chain, chain->bref.data_off,
852 chain->bref.type, chain->refs,
853 chain->parent,
854 chain->dio, chain->data);
856 KKASSERT(chain->data == NULL);
857 break;
860 return dio;
864 * Lock a referenced chain element, acquiring its data with I/O if necessary,
865 * and specify how you would like the data to be resolved.
867 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
869 * The lock is allowed to recurse, multiple locking ops will aggregate
870 * the requested resolve types. Once data is assigned it will not be
871 * removed until the last unlock.
873 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
874 * (typically used to avoid device/logical buffer
875 * aliasing for data)
877 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
878 * the INITIAL-create state (indirect blocks only).
880 * Do not resolve data elements for DATA chains.
881 * (typically used to avoid device/logical buffer
882 * aliasing for data)
884 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
886 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
887 * it will be locked exclusive.
889 * NOTE: Embedded elements (volume header, inodes) are always resolved
890 * regardless.
892 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
893 * element will instantiate and zero its buffer, and flush it on
894 * release.
896 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
897 * so as not to instantiate a device buffer, which could alias against
898 * a logical file buffer. However, if ALWAYS is specified the
899 * device buffer will be instantiated anyway.
901 * WARNING! This function blocks on I/O if data needs to be fetched. This
902 * blocking can run concurrent with other compatible lock holders
903 * who do not need data returning. The lock is not upgraded to
904 * exclusive during a data fetch, a separate bit is used to
905 * interlock I/O. However, an exclusive lock holder can still count
906 * on being interlocked against an I/O fetch managed by a shared
907 * lock holder.
909 void
910 hammer2_chain_lock(hammer2_chain_t *chain, int how)
913 * Ref and lock the element. Recursive locks are allowed.
915 KKASSERT(chain->refs > 0);
916 atomic_add_int(&chain->lockcnt, 1);
919 * Get the appropriate lock. If LOCKAGAIN is flagged with SHARED
920 * the caller expects a shared lock to already be present and we
921 * are giving it another ref. This case must importantly not block
922 * if there is a pending exclusive lock request.
924 if (how & HAMMER2_RESOLVE_SHARED) {
925 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
926 hammer2_mtx_sh_again(&chain->lock);
927 } else {
928 hammer2_mtx_sh(&chain->lock);
930 } else {
931 hammer2_mtx_ex(&chain->lock);
933 ++curthread->td_tracker;
936 * If we already have a valid data pointer no further action is
937 * necessary.
939 if (chain->data)
940 return;
943 * Do we have to resolve the data? This is generally only
944 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
945 * Other BREF types expects the data to be there.
947 switch(how & HAMMER2_RESOLVE_MASK) {
948 case HAMMER2_RESOLVE_NEVER:
949 return;
950 case HAMMER2_RESOLVE_MAYBE:
951 if (chain->flags & HAMMER2_CHAIN_INITIAL)
952 return;
953 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
954 return;
955 #if 0
956 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
957 return;
958 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
959 return;
960 #endif
961 /* fall through */
962 case HAMMER2_RESOLVE_ALWAYS:
963 default:
964 break;
968 * Caller requires data
970 hammer2_chain_load_data(chain);
974 * Lock the chain, retain the hold, and drop the data persistence count.
975 * The data should remain valid because we never transitioned lockcnt
976 * through 0.
978 void
979 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
981 hammer2_chain_lock(chain, how);
982 atomic_add_int(&chain->lockcnt, -1);
985 #if 0
987 * Downgrade an exclusive chain lock to a shared chain lock.
989 * NOTE: There is no upgrade equivalent due to the ease of
990 * deadlocks in that direction.
992 void
993 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
995 hammer2_mtx_downgrade(&chain->lock);
997 #endif
999 #if 0
1001 * Obtains a second shared lock on the chain, does not account the second
1002 * shared lock as being owned by the current thread.
1004 * Caller must already own a shared lock on this chain.
1006 * The lock function is required to obtain the second shared lock without
1007 * blocking on pending exclusive requests.
1009 void
1010 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
1012 hammer2_mtx_sh_again(&chain->lock);
1013 atomic_add_int(&chain->lockcnt, 1);
1014 /* do not count in td_tracker for this thread */
1018 * Accounts for a shared lock that was pushed to us as being owned by our
1019 * thread.
1021 void
1022 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
1024 ++curthread->td_tracker;
1026 #endif
1029 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1030 * may be of any type.
1032 * Once chain->data is set it cannot be disposed of until all locks are
1033 * released.
1035 void
1036 hammer2_chain_load_data(hammer2_chain_t *chain)
1038 hammer2_blockref_t *bref;
1039 hammer2_dev_t *hmp;
1040 hammer2_io_t *dio;
1041 char *bdata;
1042 int error;
1045 * Degenerate case, data already present, or chain is not expected
1046 * to have any data.
1048 if (chain->data)
1049 return;
1050 if ((chain->bref.data_off & HAMMER2_OFF_MASK_RADIX) == 0)
1051 return;
1053 hmp = chain->hmp;
1054 KKASSERT(hmp != NULL);
1057 * Gain the IOINPROG bit, interlocked block.
1059 for (;;) {
1060 u_int oflags;
1061 u_int nflags;
1063 oflags = chain->flags;
1064 cpu_ccfence();
1065 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1066 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1067 tsleep_interlock(&chain->flags, 0);
1068 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1069 tsleep(&chain->flags, PINTERLOCKED,
1070 "h2iocw", 0);
1072 /* retry */
1073 } else {
1074 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1075 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1076 break;
1078 /* retry */
1083 * We own CHAIN_IOINPROG
1085 * Degenerate case if we raced another load.
1087 if (chain->data)
1088 goto done;
1091 * We must resolve to a device buffer, either by issuing I/O or
1092 * by creating a zero-fill element. We do not mark the buffer
1093 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1094 * API must still be used to do that).
1096 * The device buffer is variable-sized in powers of 2 down
1097 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1098 * chunk always contains buffers of the same size. (XXX)
1100 * The minimum physical IO size may be larger than the variable
1101 * block size.
1103 bref = &chain->bref;
1106 * The getblk() optimization can only be used on newly created
1107 * elements if the physical block size matches the request.
1109 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1110 error = hammer2_io_new(hmp, bref->type,
1111 bref->data_off, chain->bytes,
1112 &chain->dio);
1113 } else {
1114 error = hammer2_io_bread(hmp, bref->type,
1115 bref->data_off, chain->bytes,
1116 &chain->dio);
1117 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1119 if (error) {
1120 chain->error = HAMMER2_ERROR_IO;
1121 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1122 (intmax_t)bref->data_off, error);
1123 hammer2_io_bqrelse(&chain->dio);
1124 goto done;
1126 chain->error = 0;
1129 * This isn't perfect and can be ignored on OSs which do not have
1130 * an indication as to whether a buffer is coming from cache or
1131 * if I/O was actually issued for the read. TESTEDGOOD will work
1132 * pretty well without the B_IOISSUED logic because chains are
1133 * cached, but in that situation (without B_IOISSUED) it will not
1134 * detect whether a re-read via I/O is corrupted verses the original
1135 * read.
1137 * We can't re-run the CRC on every fresh lock. That would be
1138 * insanely expensive.
1140 * If the underlying kernel buffer covers the entire chain we can
1141 * use the B_IOISSUED indication to determine if we have to re-run
1142 * the CRC on chain data for chains that managed to stay cached
1143 * across the kernel disposal of the original buffer.
1145 if ((dio = chain->dio) != NULL && dio->bp) {
1146 struct buf *bp = dio->bp;
1148 if (dio->psize == chain->bytes &&
1149 (bp->b_flags & B_IOISSUED)) {
1150 atomic_clear_int(&chain->flags,
1151 HAMMER2_CHAIN_TESTEDGOOD);
1152 bp->b_flags &= ~B_IOISSUED;
1157 * NOTE: A locked chain's data cannot be modified without first
1158 * calling hammer2_chain_modify().
1162 * Clear INITIAL. In this case we used io_new() and the buffer has
1163 * been zero'd and marked dirty.
1165 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1167 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1168 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1169 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1170 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1172 * check data not currently synchronized due to
1173 * modification. XXX assumes data stays in the buffer
1174 * cache, which might not be true (need biodep on flush
1175 * to calculate crc? or simple crc?).
1177 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1178 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1179 chain->error = HAMMER2_ERROR_CHECK;
1180 } else {
1181 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1186 * Setup the data pointer, either pointing it to an embedded data
1187 * structure and copying the data from the buffer, or pointing it
1188 * into the buffer.
1190 * The buffer is not retained when copying to an embedded data
1191 * structure in order to avoid potential deadlocks or recursions
1192 * on the same physical buffer.
1194 * WARNING! Other threads can start using the data the instant we
1195 * set chain->data non-NULL.
1197 switch (bref->type) {
1198 case HAMMER2_BREF_TYPE_VOLUME:
1199 case HAMMER2_BREF_TYPE_FREEMAP:
1201 * Copy data from bp to embedded buffer
1203 panic("hammer2_chain_load_data: unresolved volume header");
1204 break;
1205 case HAMMER2_BREF_TYPE_DIRENT:
1206 KKASSERT(chain->bytes != 0);
1207 /* fall through */
1208 case HAMMER2_BREF_TYPE_INODE:
1209 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1210 case HAMMER2_BREF_TYPE_INDIRECT:
1211 case HAMMER2_BREF_TYPE_DATA:
1212 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1213 default:
1215 * Point data at the device buffer and leave dio intact.
1217 chain->data = (void *)bdata;
1218 break;
1222 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1224 done:
1225 for (;;) {
1226 u_int oflags;
1227 u_int nflags;
1229 oflags = chain->flags;
1230 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1231 HAMMER2_CHAIN_IOSIGNAL);
1232 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1233 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1234 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1235 wakeup(&chain->flags);
1236 break;
1242 * Unlock and deref a chain element.
1244 * Remember that the presence of children under chain prevent the chain's
1245 * destruction but do not add additional references, so the dio will still
1246 * be dropped.
1248 void
1249 hammer2_chain_unlock(hammer2_chain_t *chain)
1251 hammer2_io_t *dio;
1252 u_int lockcnt;
1253 int iter = 0;
1255 --curthread->td_tracker;
1258 * If multiple locks are present (or being attempted) on this
1259 * particular chain we can just unlock, drop refs, and return.
1261 * Otherwise fall-through on the 1->0 transition.
1263 for (;;) {
1264 lockcnt = chain->lockcnt;
1265 KKASSERT(lockcnt > 0);
1266 cpu_ccfence();
1267 if (lockcnt > 1) {
1268 if (atomic_cmpset_int(&chain->lockcnt,
1269 lockcnt, lockcnt - 1)) {
1270 hammer2_mtx_unlock(&chain->lock);
1271 return;
1273 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1274 /* while holding the mutex exclusively */
1275 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1276 break;
1277 } else {
1279 * This situation can easily occur on SMP due to
1280 * the gap inbetween the 1->0 transition and the
1281 * final unlock. We cannot safely block on the
1282 * mutex because lockcnt might go above 1.
1284 * XXX Sleep for one tick if it takes too long.
1286 if (++iter > 1000) {
1287 if (iter > 1000 + hz) {
1288 kprintf("hammer2: h2race2 %p\n", chain);
1289 iter = 1000;
1291 tsleep(&iter, 0, "h2race2", 1);
1293 cpu_pause();
1295 /* retry */
1299 * Last unlock / mutex upgraded to exclusive. Drop the data
1300 * reference.
1302 dio = hammer2_chain_drop_data(chain);
1303 if (dio)
1304 hammer2_io_bqrelse(&dio);
1305 hammer2_mtx_unlock(&chain->lock);
1309 * Unlock and hold chain data intact
1311 void
1312 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1314 atomic_add_int(&chain->lockcnt, 1);
1315 hammer2_chain_unlock(chain);
1319 * Helper to obtain the blockref[] array base and count for a chain.
1321 * XXX Not widely used yet, various use cases need to be validated and
1322 * converted to use this function.
1324 static
1325 hammer2_blockref_t *
1326 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1328 hammer2_blockref_t *base;
1329 int count;
1331 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1332 base = NULL;
1334 switch(parent->bref.type) {
1335 case HAMMER2_BREF_TYPE_INODE:
1336 count = HAMMER2_SET_COUNT;
1337 break;
1338 case HAMMER2_BREF_TYPE_INDIRECT:
1339 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1340 count = parent->bytes / sizeof(hammer2_blockref_t);
1341 break;
1342 case HAMMER2_BREF_TYPE_VOLUME:
1343 count = HAMMER2_SET_COUNT;
1344 break;
1345 case HAMMER2_BREF_TYPE_FREEMAP:
1346 count = HAMMER2_SET_COUNT;
1347 break;
1348 default:
1349 panic("hammer2_chain_create_indirect: "
1350 "unrecognized blockref type: %d",
1351 parent->bref.type);
1352 count = 0;
1353 break;
1355 } else {
1356 switch(parent->bref.type) {
1357 case HAMMER2_BREF_TYPE_INODE:
1358 base = &parent->data->ipdata.u.blockset.blockref[0];
1359 count = HAMMER2_SET_COUNT;
1360 break;
1361 case HAMMER2_BREF_TYPE_INDIRECT:
1362 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1363 base = &parent->data->npdata[0];
1364 count = parent->bytes / sizeof(hammer2_blockref_t);
1365 break;
1366 case HAMMER2_BREF_TYPE_VOLUME:
1367 base = &parent->data->voldata.
1368 sroot_blockset.blockref[0];
1369 count = HAMMER2_SET_COUNT;
1370 break;
1371 case HAMMER2_BREF_TYPE_FREEMAP:
1372 base = &parent->data->blkset.blockref[0];
1373 count = HAMMER2_SET_COUNT;
1374 break;
1375 default:
1376 panic("hammer2_chain_create_indirect: "
1377 "unrecognized blockref type: %d",
1378 parent->bref.type);
1379 count = 0;
1380 break;
1383 *countp = count;
1385 return base;
1389 * This counts the number of live blockrefs in a block array and
1390 * also calculates the point at which all remaining blockrefs are empty.
1391 * This routine can only be called on a live chain.
1393 * NOTE: Flag is not set until after the count is complete, allowing
1394 * callers to test the flag without holding the spinlock.
1396 * NOTE: If base is NULL the related chain is still in the INITIAL
1397 * state and there are no blockrefs to count.
1399 * NOTE: live_count may already have some counts accumulated due to
1400 * creation and deletion and could even be initially negative.
1402 void
1403 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1404 hammer2_blockref_t *base, int count)
1406 hammer2_spin_ex(&chain->core.spin);
1407 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1408 if (base) {
1409 while (--count >= 0) {
1410 if (base[count].type)
1411 break;
1413 chain->core.live_zero = count + 1;
1414 while (count >= 0) {
1415 if (base[count].type)
1416 atomic_add_int(&chain->core.live_count,
1418 --count;
1420 } else {
1421 chain->core.live_zero = 0;
1423 /* else do not modify live_count */
1424 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1426 hammer2_spin_unex(&chain->core.spin);
1430 * Resize the chain's physical storage allocation in-place. This function does
1431 * not usually adjust the data pointer and must be followed by (typically) a
1432 * hammer2_chain_modify() call to copy any old data over and adjust the
1433 * data pointer.
1435 * Chains can be resized smaller without reallocating the storage. Resizing
1436 * larger will reallocate the storage. Excess or prior storage is reclaimed
1437 * asynchronously at a later time.
1439 * An nradix value of 0 is special-cased to mean that the storage should
1440 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1441 * byte).
1443 * Must be passed an exclusively locked parent and chain.
1445 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1446 * to avoid instantiating a device buffer that conflicts with the vnode data
1447 * buffer. However, because H2 can compress or encrypt data, the chain may
1448 * have a dio assigned to it in those situations, and they do not conflict.
1450 * XXX return error if cannot resize.
1452 void
1453 hammer2_chain_resize(hammer2_chain_t *chain,
1454 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1455 int nradix, int flags)
1457 hammer2_dev_t *hmp;
1458 size_t obytes;
1459 size_t nbytes;
1461 hmp = chain->hmp;
1464 * Only data and indirect blocks can be resized for now.
1465 * (The volu root, inodes, and freemap elements use a fixed size).
1467 KKASSERT(chain != &hmp->vchain);
1468 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1469 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1470 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1473 * Nothing to do if the element is already the proper size
1475 obytes = chain->bytes;
1476 nbytes = (nradix) ? (1U << nradix) : 0;
1477 if (obytes == nbytes)
1478 return;
1481 * Make sure the old data is instantiated so we can copy it. If this
1482 * is a data block, the device data may be superfluous since the data
1483 * might be in a logical block, but compressed or encrypted data is
1484 * another matter.
1486 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1488 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1491 * Relocate the block, even if making it smaller (because different
1492 * block sizes may be in different regions).
1494 * NOTE: Operation does not copy the data and may only be used
1495 * to resize data blocks in-place, or directory entry blocks
1496 * which are about to be modified in some manner.
1498 hammer2_freemap_alloc(chain, nbytes);
1499 chain->bytes = nbytes;
1502 * We don't want the followup chain_modify() to try to copy data
1503 * from the old (wrong-sized) buffer. It won't know how much to
1504 * copy. This case should only occur during writes when the
1505 * originator already has the data to write in-hand.
1507 if (chain->dio) {
1508 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1509 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1510 hammer2_io_brelse(&chain->dio);
1511 chain->data = NULL;
1516 * Set the chain modified so its data can be changed by the caller, or
1517 * install deduplicated data. The caller must call this routine for each
1518 * set of modifications it makes, even if the chain is already flagged
1519 * MODIFIED.
1521 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1522 * is a CLC (cluster level change) field and is not updated by parent
1523 * propagation during a flush.
1525 * Dedup Handling
1527 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1528 * even if the chain is still flagged MODIFIED. In this case the chain's
1529 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1531 * If the caller passes a non-zero dedup_off we will use it to assign the
1532 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1533 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1534 * must not modify the data content upon return.
1536 void
1537 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1538 hammer2_off_t dedup_off, int flags)
1540 hammer2_blockref_t obref;
1541 hammer2_dev_t *hmp;
1542 hammer2_io_t *dio;
1543 int error;
1544 int wasinitial;
1545 int newmod;
1546 char *bdata;
1548 hmp = chain->hmp;
1549 obref = chain->bref;
1550 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1553 * Data is not optional for freemap chains (we must always be sure
1554 * to copy the data on COW storage allocations).
1556 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1557 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1558 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1559 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1563 * Data must be resolved if already assigned, unless explicitly
1564 * flagged otherwise.
1566 if (chain->data == NULL && chain->bytes != 0 &&
1567 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1568 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1569 hammer2_chain_load_data(chain);
1573 * Set MODIFIED to indicate that the chain has been modified. A new
1574 * allocation is required when modifying a chain.
1576 * Set UPDATE to ensure that the blockref is updated in the parent.
1579 * If MODIFIED is already set determine if we can reuse the assigned
1580 * data block or if we need a new data block.
1582 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1584 * Must set modified bit.
1586 atomic_add_long(&hammer2_count_modified_chains, 1);
1587 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1588 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1591 * We may be able to avoid a copy-on-write if the chain's
1592 * check mode is set to NONE and the chain's current
1593 * modify_tid is beyond the last explicit snapshot tid.
1595 * This implements HAMMER2's overwrite-in-place feature.
1597 * NOTE! This data-block cannot be used as a de-duplication
1598 * source when the check mode is set to NONE.
1600 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1601 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1602 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1603 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1604 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1605 HAMMER2_CHECK_NONE &&
1606 chain->pmp &&
1607 chain->bref.modify_tid >
1608 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1610 * Sector overwrite allowed.
1612 newmod = 0;
1613 } else {
1615 * Sector overwrite not allowed, must copy-on-write.
1617 newmod = 1;
1619 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1621 * If the modified chain was registered for dedup we need
1622 * a new allocation. This only happens for delayed-flush
1623 * chains (i.e. which run through the front-end buffer
1624 * cache).
1626 newmod = 1;
1627 } else {
1629 * Already flagged modified, no new allocation is needed.
1631 newmod = 0;
1635 * Flag parent update required.
1637 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1638 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1641 * The modification or re-modification requires an allocation and
1642 * possible COW.
1644 * If dedup_off is non-zero, caller already has a data offset
1645 * containing the caller's desired data. The dedup offset is
1646 * allowed to be in a partially free state and we must be sure
1647 * to reset it to a fully allocated state to force two bulkfree
1648 * passes to free it again. The chain will not be marked MODIFIED
1649 * in the dedup case, as the dedup data cannot be changed without
1650 * a new allocation.
1652 * NOTE: Only applicable when chain->bytes != 0.
1654 * XXX can a chain already be marked MODIFIED without a data
1655 * assignment? If not, assert here instead of testing the case.
1657 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1658 chain->bytes) {
1659 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1660 newmod
1663 * NOTE: We do not have to remove the dedup
1664 * registration because the area is still
1665 * allocated and the underlying DIO will
1666 * still be flushed.
1668 if (dedup_off) {
1669 chain->bref.data_off = dedup_off;
1670 chain->bytes = 1 << (dedup_off &
1671 HAMMER2_OFF_MASK_RADIX);
1672 atomic_clear_int(&chain->flags,
1673 HAMMER2_CHAIN_MODIFIED);
1674 atomic_add_long(&hammer2_count_modified_chains,
1675 -1);
1676 if (chain->pmp)
1677 hammer2_pfs_memory_wakeup(chain->pmp);
1678 hammer2_freemap_adjust(hmp, &chain->bref,
1679 HAMMER2_FREEMAP_DORECOVER);
1680 atomic_set_int(&chain->flags,
1681 HAMMER2_CHAIN_DEDUPABLE);
1682 } else {
1683 hammer2_freemap_alloc(chain, chain->bytes);
1684 atomic_clear_int(&chain->flags,
1685 HAMMER2_CHAIN_DEDUPABLE);
1687 /* XXX failed allocation */
1692 * Update mirror_tid and modify_tid. modify_tid is only updated
1693 * if not passed as zero (during flushes, parent propagation passes
1694 * the value 0).
1696 * NOTE: chain->pmp could be the device spmp.
1698 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1699 if (mtid)
1700 chain->bref.modify_tid = mtid;
1703 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1704 * requires updating as well as to tell the delete code that the
1705 * chain's blockref might not exactly match (in terms of physical size
1706 * or block offset) the one in the parent's blocktable. The base key
1707 * of course will still match.
1709 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1710 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1713 * Short-cut data blocks which the caller does not need an actual
1714 * data reference to (aka OPTDATA), as long as the chain does not
1715 * already have a data pointer to the data. This generally means
1716 * that the modifications are being done via the logical buffer cache.
1717 * The INITIAL flag relates only to the device data buffer and thus
1718 * remains unchange in this situation.
1720 * This code also handles bytes == 0 (most dirents).
1722 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1723 (flags & HAMMER2_MODIFY_OPTDATA) &&
1724 chain->data == NULL) {
1725 KKASSERT(chain->dio == NULL);
1726 goto skip2;
1730 * Clearing the INITIAL flag (for indirect blocks) indicates that
1731 * we've processed the uninitialized storage allocation.
1733 * If this flag is already clear we are likely in a copy-on-write
1734 * situation but we have to be sure NOT to bzero the storage if
1735 * no data is present.
1737 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1738 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1739 wasinitial = 1;
1740 } else {
1741 wasinitial = 0;
1745 * Instantiate data buffer and possibly execute COW operation
1747 switch(chain->bref.type) {
1748 case HAMMER2_BREF_TYPE_VOLUME:
1749 case HAMMER2_BREF_TYPE_FREEMAP:
1751 * The data is embedded, no copy-on-write operation is
1752 * needed.
1754 KKASSERT(chain->dio == NULL);
1755 break;
1756 case HAMMER2_BREF_TYPE_DIRENT:
1758 * The data might be fully embedded.
1760 if (chain->bytes == 0) {
1761 KKASSERT(chain->dio == NULL);
1762 break;
1764 /* fall through */
1765 case HAMMER2_BREF_TYPE_INODE:
1766 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1767 case HAMMER2_BREF_TYPE_DATA:
1768 case HAMMER2_BREF_TYPE_INDIRECT:
1769 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1771 * Perform the copy-on-write operation
1773 * zero-fill or copy-on-write depending on whether
1774 * chain->data exists or not and set the dirty state for
1775 * the new buffer. hammer2_io_new() will handle the
1776 * zero-fill.
1778 * If a dedup_off was supplied this is an existing block
1779 * and no COW, copy, or further modification is required.
1781 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1783 if (wasinitial && dedup_off == 0) {
1784 error = hammer2_io_new(hmp, chain->bref.type,
1785 chain->bref.data_off,
1786 chain->bytes, &dio);
1787 } else {
1788 error = hammer2_io_bread(hmp, chain->bref.type,
1789 chain->bref.data_off,
1790 chain->bytes, &dio);
1792 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1795 * If an I/O error occurs make sure callers cannot accidently
1796 * modify the old buffer's contents and corrupt the filesystem.
1798 if (error) {
1799 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1800 hmp);
1801 chain->error = HAMMER2_ERROR_IO;
1802 hammer2_io_brelse(&dio);
1803 hammer2_io_brelse(&chain->dio);
1804 chain->data = NULL;
1805 break;
1807 chain->error = 0;
1808 bdata = hammer2_io_data(dio, chain->bref.data_off);
1810 if (chain->data) {
1812 * COW (unless a dedup).
1814 KKASSERT(chain->dio != NULL);
1815 if (chain->data != (void *)bdata && dedup_off == 0) {
1816 bcopy(chain->data, bdata, chain->bytes);
1818 } else if (wasinitial == 0) {
1820 * We have a problem. We were asked to COW but
1821 * we don't have any data to COW with!
1823 panic("hammer2_chain_modify: having a COW %p\n",
1824 chain);
1828 * Retire the old buffer, replace with the new. Dirty or
1829 * redirty the new buffer.
1831 * WARNING! The system buffer cache may have already flushed
1832 * the buffer, so we must be sure to [re]dirty it
1833 * for further modification.
1835 * If dedup_off was supplied, the caller is not
1836 * expected to make any further modification to the
1837 * buffer.
1839 if (chain->dio)
1840 hammer2_io_bqrelse(&chain->dio);
1841 chain->data = (void *)bdata;
1842 chain->dio = dio;
1843 if (dedup_off == 0)
1844 hammer2_io_setdirty(dio);
1845 break;
1846 default:
1847 panic("hammer2_chain_modify: illegal non-embedded type %d",
1848 chain->bref.type);
1849 break;
1852 skip2:
1854 * setflush on parent indicating that the parent must recurse down
1855 * to us. Do not call on chain itself which might already have it
1856 * set.
1858 if (chain->parent)
1859 hammer2_chain_setflush(chain->parent);
1863 * Modify the chain associated with an inode.
1865 void
1866 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1867 hammer2_tid_t mtid, int flags)
1869 hammer2_inode_modify(ip);
1870 hammer2_chain_modify(chain, mtid, 0, flags);
1874 * Volume header data locks
1876 void
1877 hammer2_voldata_lock(hammer2_dev_t *hmp)
1879 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1882 void
1883 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1885 lockmgr(&hmp->vollk, LK_RELEASE);
1888 void
1889 hammer2_voldata_modify(hammer2_dev_t *hmp)
1891 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1892 atomic_add_long(&hammer2_count_modified_chains, 1);
1893 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1894 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1899 * This function returns the chain at the nearest key within the specified
1900 * range. The returned chain will be referenced but not locked.
1902 * This function will recurse through chain->rbtree as necessary and will
1903 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1904 * the iteration value is less than the current value of *key_nextp.
1906 * The caller should use (*key_nextp) to calculate the actual range of
1907 * the returned element, which will be (key_beg to *key_nextp - 1), because
1908 * there might be another element which is superior to the returned element
1909 * and overlaps it.
1911 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1912 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1913 * it will wind up being (key_end + 1).
1915 * WARNING! Must be called with child's spinlock held. Spinlock remains
1916 * held through the operation.
1918 struct hammer2_chain_find_info {
1919 hammer2_chain_t *best;
1920 hammer2_key_t key_beg;
1921 hammer2_key_t key_end;
1922 hammer2_key_t key_next;
1925 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1926 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1928 static
1929 hammer2_chain_t *
1930 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1931 hammer2_key_t key_beg, hammer2_key_t key_end)
1933 struct hammer2_chain_find_info info;
1935 info.best = NULL;
1936 info.key_beg = key_beg;
1937 info.key_end = key_end;
1938 info.key_next = *key_nextp;
1940 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1941 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1942 &info);
1943 *key_nextp = info.key_next;
1944 #if 0
1945 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1946 parent, key_beg, key_end, *key_nextp);
1947 #endif
1949 return (info.best);
1952 static
1954 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1956 struct hammer2_chain_find_info *info = data;
1957 hammer2_key_t child_beg;
1958 hammer2_key_t child_end;
1960 child_beg = child->bref.key;
1961 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1963 if (child_end < info->key_beg)
1964 return(-1);
1965 if (child_beg > info->key_end)
1966 return(1);
1967 return(0);
1970 static
1972 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1974 struct hammer2_chain_find_info *info = data;
1975 hammer2_chain_t *best;
1976 hammer2_key_t child_end;
1979 * WARNING! Layerq is scanned forwards, exact matches should keep
1980 * the existing info->best.
1982 if ((best = info->best) == NULL) {
1984 * No previous best. Assign best
1986 info->best = child;
1987 } else if (best->bref.key <= info->key_beg &&
1988 child->bref.key <= info->key_beg) {
1990 * Illegal overlap.
1992 KKASSERT(0);
1993 /*info->best = child;*/
1994 } else if (child->bref.key < best->bref.key) {
1996 * Child has a nearer key and best is not flush with key_beg.
1997 * Set best to child. Truncate key_next to the old best key.
1999 info->best = child;
2000 if (info->key_next > best->bref.key || info->key_next == 0)
2001 info->key_next = best->bref.key;
2002 } else if (child->bref.key == best->bref.key) {
2004 * If our current best is flush with the child then this
2005 * is an illegal overlap.
2007 * key_next will automatically be limited to the smaller of
2008 * the two end-points.
2010 KKASSERT(0);
2011 info->best = child;
2012 } else {
2014 * Keep the current best but truncate key_next to the child's
2015 * base.
2017 * key_next will also automatically be limited to the smaller
2018 * of the two end-points (probably not necessary for this case
2019 * but we do it anyway).
2021 if (info->key_next > child->bref.key || info->key_next == 0)
2022 info->key_next = child->bref.key;
2026 * Always truncate key_next based on child's end-of-range.
2028 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2029 if (child_end && (info->key_next > child_end || info->key_next == 0))
2030 info->key_next = child_end;
2032 return(0);
2036 * Retrieve the specified chain from a media blockref, creating the
2037 * in-memory chain structure which reflects it. The returned chain is
2038 * held but not locked. The caller must lock it to crc-check and
2039 * dereference its data, and should check chain->error after locking
2040 * before assuming that the data is good.
2042 * To handle insertion races pass the INSERT_RACE flag along with the
2043 * generation number of the core. NULL will be returned if the generation
2044 * number changes before we have a chance to insert the chain. Insert
2045 * races can occur because the parent might be held shared.
2047 * Caller must hold the parent locked shared or exclusive since we may
2048 * need the parent's bref array to find our block.
2050 * WARNING! chain->pmp is always set to NULL for any chain representing
2051 * part of the super-root topology.
2053 hammer2_chain_t *
2054 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2055 hammer2_blockref_t *bref)
2057 hammer2_dev_t *hmp = parent->hmp;
2058 hammer2_chain_t *chain;
2059 int error;
2062 * Allocate a chain structure representing the existing media
2063 * entry. Resulting chain has one ref and is not locked.
2065 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2066 chain = hammer2_chain_alloc(hmp, NULL, bref);
2067 else
2068 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2069 /* ref'd chain returned */
2072 * Flag that the chain is in the parent's blockmap so delete/flush
2073 * knows what to do with it.
2075 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2078 * Link the chain into its parent. A spinlock is required to safely
2079 * access the RBTREE, and it is possible to collide with another
2080 * hammer2_chain_get() operation because the caller might only hold
2081 * a shared lock on the parent.
2083 * NOTE: Get races can occur quite often when we distribute
2084 * asynchronous read-aheads across multiple threads.
2086 KKASSERT(parent->refs > 0);
2087 error = hammer2_chain_insert(parent, chain,
2088 HAMMER2_CHAIN_INSERT_SPIN |
2089 HAMMER2_CHAIN_INSERT_RACE,
2090 generation);
2091 if (error) {
2092 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2093 /*kprintf("chain %p get race\n", chain);*/
2094 hammer2_chain_drop(chain);
2095 chain = NULL;
2096 } else {
2097 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2101 * Return our new chain referenced but not locked, or NULL if
2102 * a race occurred.
2104 return (chain);
2108 * Lookup initialization/completion API
2110 hammer2_chain_t *
2111 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2113 hammer2_chain_ref(parent);
2114 if (flags & HAMMER2_LOOKUP_SHARED) {
2115 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2116 HAMMER2_RESOLVE_SHARED);
2117 } else {
2118 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2120 return (parent);
2123 void
2124 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2126 if (parent) {
2127 hammer2_chain_unlock(parent);
2128 hammer2_chain_drop(parent);
2133 * Take the locked chain and return a locked parent. The chain remains
2134 * locked on return.
2136 * This will work even if the chain is errored, and the caller can check
2137 * parent->error on return if desired since the parent will be locked.
2139 * This function handles the lock order reversal.
2141 hammer2_chain_t *
2142 hammer2_chain_getparent(hammer2_chain_t *chain, int how)
2144 hammer2_chain_t *parent;
2147 * Be careful of order, chain must be unlocked before parent
2148 * is locked below to avoid a deadlock.
2150 * Safe access to fu->parent requires fu's core spinlock.
2152 again:
2153 hammer2_spin_ex(&chain->core.spin);
2154 parent = chain->parent;
2155 if (parent == NULL) {
2156 hammer2_spin_unex(&chain->core.spin);
2157 panic("hammer2_chain_getparent: no parent");
2159 hammer2_chain_ref(parent);
2160 hammer2_spin_unex(&chain->core.spin);
2162 hammer2_chain_unlock(chain);
2163 hammer2_chain_lock(parent, how);
2164 hammer2_chain_lock(chain, how);
2167 * Parent relinking races are quite common. We have to get it right
2168 * or we will blow up the block table.
2170 if (chain->parent != parent) {
2171 hammer2_chain_unlock(parent);
2172 hammer2_chain_drop(parent);
2173 goto again;
2175 return parent;
2179 * Take the locked chain and return a locked parent. The chain is unlocked
2180 * and dropped. *chainp is set to the returned parent as a convenience.
2182 * This will work even if the chain is errored, and the caller can check
2183 * parent->error on return if desired since the parent will be locked.
2185 * This function handles the lock order reversal.
2187 hammer2_chain_t *
2188 hammer2_chain_repparent(hammer2_chain_t **chainp, int how)
2190 hammer2_chain_t *chain;
2191 hammer2_chain_t *parent;
2194 * Be careful of order, chain must be unlocked before parent
2195 * is locked below to avoid a deadlock.
2197 * Safe access to fu->parent requires fu's core spinlock.
2199 chain = *chainp;
2200 again:
2201 hammer2_spin_ex(&chain->core.spin);
2202 parent = chain->parent;
2203 if (parent == NULL) {
2204 hammer2_spin_unex(&chain->core.spin);
2205 panic("hammer2_chain_getparent: no parent");
2207 hammer2_chain_ref(parent);
2208 hammer2_spin_unex(&chain->core.spin);
2210 hammer2_chain_unlock(chain);
2211 hammer2_chain_lock(parent, how);
2214 * Parent relinking races are quite common. We have to get it right
2215 * or we will blow up the block table.
2217 if (chain->parent != parent) {
2218 hammer2_chain_lock(chain, how);
2219 hammer2_chain_unlock(parent);
2220 hammer2_chain_drop(parent);
2221 goto again;
2223 hammer2_chain_drop(chain);
2224 *chainp = parent;
2226 return parent;
2230 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2231 * (*parentp) typically points to an inode but can also point to a related
2232 * indirect block and this function will recurse upwards and find the inode
2233 * again.
2235 * This function unconditionally sets *errorp, replacing any previous value.
2237 * (*parentp) must be exclusively locked and referenced and can be an inode
2238 * or an existing indirect block within the inode. If (*parent) is errored
2239 * out, this function will not attempt to recurse the radix tree and
2240 * will return NULL along with an appropriate *errorp. If NULL is returned
2241 * and *errorp is 0, the requested lookup could not be located.
2243 * On return (*parentp) will be modified to point at the deepest parent chain
2244 * element encountered during the search, as a helper for an insertion or
2245 * deletion. The new (*parentp) will be locked and referenced and the old
2246 * will be unlocked and dereferenced (no change if they are both the same).
2247 * This is particularly important if the caller wishes to insert a new chain,
2248 * (*parentp) will be set properly even if NULL is returned, as long as no
2249 * error occurred.
2251 * The matching chain will be returned exclusively locked. If NOLOCK is
2252 * requested the chain will be returned only referenced. Note that the
2253 * parent chain must always be locked shared or exclusive, matching the
2254 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2255 * when NOLOCK is specified but that complicates matters if *parentp must
2256 * inherit the chain.
2258 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2259 * data pointer or can otherwise be in flux.
2261 * NULL is returned if no match was found, but (*parentp) will still
2262 * potentially be adjusted.
2264 * On return (*key_nextp) will point to an iterative value for key_beg.
2265 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2267 * This function will also recurse up the chain if the key is not within the
2268 * current parent's range. (*parentp) can never be set to NULL. An iteration
2269 * can simply allow (*parentp) to float inside the loop.
2271 * NOTE! chain->data is not always resolved. By default it will not be
2272 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2273 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2274 * BREF_TYPE_DATA as the device buffer can alias the logical file
2275 * buffer).
2278 hammer2_chain_t *
2279 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2280 hammer2_key_t key_beg, hammer2_key_t key_end,
2281 int *errorp, int flags)
2283 hammer2_dev_t *hmp;
2284 hammer2_chain_t *parent;
2285 hammer2_chain_t *chain;
2286 hammer2_blockref_t *base;
2287 hammer2_blockref_t *bref;
2288 hammer2_blockref_t bcopy;
2289 hammer2_key_t scan_beg;
2290 hammer2_key_t scan_end;
2291 int count = 0;
2292 int how_always = HAMMER2_RESOLVE_ALWAYS;
2293 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2294 int how;
2295 int generation;
2296 int maxloops = 300000;
2298 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2299 how_maybe = how_always;
2300 how = HAMMER2_RESOLVE_ALWAYS;
2301 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2302 how = HAMMER2_RESOLVE_NEVER;
2303 } else {
2304 how = HAMMER2_RESOLVE_MAYBE;
2306 if (flags & HAMMER2_LOOKUP_SHARED) {
2307 how_maybe |= HAMMER2_RESOLVE_SHARED;
2308 how_always |= HAMMER2_RESOLVE_SHARED;
2309 how |= HAMMER2_RESOLVE_SHARED;
2313 * Recurse (*parentp) upward if necessary until the parent completely
2314 * encloses the key range or we hit the inode.
2316 * Handle races against the flusher deleting indirect nodes on its
2317 * way back up by continuing to recurse upward past the deletion.
2319 parent = *parentp;
2320 hmp = parent->hmp;
2321 *errorp = 0;
2323 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2324 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2325 scan_beg = parent->bref.key;
2326 scan_end = scan_beg +
2327 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2328 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2329 if (key_beg >= scan_beg && key_end <= scan_end)
2330 break;
2332 parent = hammer2_chain_repparent(parentp, how_maybe);
2334 again:
2336 if (--maxloops == 0)
2337 panic("hammer2_chain_lookup: maxloops");
2339 * Locate the blockref array. Currently we do a fully associative
2340 * search through the array.
2342 switch(parent->bref.type) {
2343 case HAMMER2_BREF_TYPE_INODE:
2345 * Special shortcut for embedded data returns the inode
2346 * itself. Callers must detect this condition and access
2347 * the embedded data (the strategy code does this for us).
2349 * This is only applicable to regular files and softlinks.
2351 * We need a second lock on parent. Since we already have
2352 * a lock we must pass LOCKAGAIN to prevent unexpected
2353 * blocking (we don't want to block on a second shared
2354 * ref if an exclusive lock is pending)
2356 if (parent->data->ipdata.meta.op_flags &
2357 HAMMER2_OPFLAG_DIRECTDATA) {
2358 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2359 chain = NULL;
2360 *key_nextp = key_end + 1;
2361 goto done;
2363 hammer2_chain_ref(parent);
2364 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2365 hammer2_chain_lock(parent,
2366 how_always |
2367 HAMMER2_RESOLVE_LOCKAGAIN);
2368 *key_nextp = key_end + 1;
2369 return (parent);
2371 base = &parent->data->ipdata.u.blockset.blockref[0];
2372 count = HAMMER2_SET_COUNT;
2373 break;
2374 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2375 case HAMMER2_BREF_TYPE_INDIRECT:
2377 * Handle MATCHIND on the parent
2379 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2380 scan_beg = parent->bref.key;
2381 scan_end = scan_beg +
2382 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2383 if (key_beg == scan_beg && key_end == scan_end) {
2384 chain = parent;
2385 hammer2_chain_ref(chain);
2386 hammer2_chain_lock(chain, how_maybe);
2387 *key_nextp = scan_end + 1;
2388 goto done;
2393 * Optimize indirect blocks in the INITIAL state to avoid
2394 * I/O.
2396 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2397 base = NULL;
2398 } else {
2399 if (parent->data == NULL) {
2400 kprintf("parent->data is NULL %p\n", parent);
2401 while (1)
2402 tsleep(parent, 0, "xxx", 0);
2404 base = &parent->data->npdata[0];
2406 count = parent->bytes / sizeof(hammer2_blockref_t);
2407 break;
2408 case HAMMER2_BREF_TYPE_VOLUME:
2409 base = &parent->data->voldata.sroot_blockset.blockref[0];
2410 count = HAMMER2_SET_COUNT;
2411 break;
2412 case HAMMER2_BREF_TYPE_FREEMAP:
2413 base = &parent->data->blkset.blockref[0];
2414 count = HAMMER2_SET_COUNT;
2415 break;
2416 default:
2417 kprintf("hammer2_chain_lookup: unrecognized "
2418 "blockref(B) type: %d",
2419 parent->bref.type);
2420 while (1)
2421 tsleep(&base, 0, "dead", 0);
2422 panic("hammer2_chain_lookup: unrecognized "
2423 "blockref(B) type: %d",
2424 parent->bref.type);
2425 base = NULL; /* safety */
2426 count = 0; /* safety */
2430 * No lookup is possible if the parent is errored. We delayed
2431 * this check as long as we could to ensure that the parent backup,
2432 * embedded data, and MATCHIND code could still execute.
2434 if (parent->error) {
2435 *errorp = parent->error;
2436 return NULL;
2440 * Merged scan to find next candidate.
2442 * hammer2_base_*() functions require the parent->core.live_* fields
2443 * to be synchronized.
2445 * We need to hold the spinlock to access the block array and RB tree
2446 * and to interlock chain creation.
2448 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2449 hammer2_chain_countbrefs(parent, base, count);
2452 * Combined search
2454 hammer2_spin_ex(&parent->core.spin);
2455 chain = hammer2_combined_find(parent, base, count,
2456 key_nextp,
2457 key_beg, key_end,
2458 &bref);
2459 generation = parent->core.generation;
2462 * Exhausted parent chain, iterate.
2464 if (bref == NULL) {
2465 hammer2_spin_unex(&parent->core.spin);
2466 if (key_beg == key_end) /* short cut single-key case */
2467 return (NULL);
2470 * Stop if we reached the end of the iteration.
2472 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2473 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2474 return (NULL);
2478 * Calculate next key, stop if we reached the end of the
2479 * iteration, otherwise go up one level and loop.
2481 key_beg = parent->bref.key +
2482 ((hammer2_key_t)1 << parent->bref.keybits);
2483 if (key_beg == 0 || key_beg > key_end)
2484 return (NULL);
2485 parent = hammer2_chain_repparent(parentp, how_maybe);
2486 goto again;
2490 * Selected from blockref or in-memory chain.
2492 if (chain == NULL) {
2493 bcopy = *bref;
2494 hammer2_spin_unex(&parent->core.spin);
2495 chain = hammer2_chain_get(parent, generation,
2496 &bcopy);
2497 if (chain == NULL) {
2499 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2500 parent, key_beg, key_end);
2502 goto again;
2504 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2505 hammer2_chain_drop(chain);
2506 goto again;
2508 } else {
2509 hammer2_chain_ref(chain);
2510 hammer2_spin_unex(&parent->core.spin);
2514 * chain is referenced but not locked. We must lock the chain
2515 * to obtain definitive state.
2517 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2518 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2519 hammer2_chain_lock(chain, how_maybe);
2520 } else {
2521 hammer2_chain_lock(chain, how);
2523 KKASSERT(chain->parent == parent);
2526 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2528 * NOTE: Chain's key range is not relevant as there might be
2529 * one-offs within the range that are not deleted.
2531 * NOTE: Lookups can race delete-duplicate because
2532 * delete-duplicate does not lock the parent's core
2533 * (they just use the spinlock on the core).
2535 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2536 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2537 chain->bref.data_off, chain->bref.type,
2538 chain->bref.key);
2539 hammer2_chain_unlock(chain);
2540 hammer2_chain_drop(chain);
2541 key_beg = *key_nextp;
2542 if (key_beg == 0 || key_beg > key_end)
2543 return(NULL);
2544 goto again;
2548 * If the chain element is an indirect block it becomes the new
2549 * parent and we loop on it. We must maintain our top-down locks
2550 * to prevent the flusher from interfering (i.e. doing a
2551 * delete-duplicate and leaving us recursing down a deleted chain).
2553 * The parent always has to be locked with at least RESOLVE_MAYBE
2554 * so we can access its data. It might need a fixup if the caller
2555 * passed incompatible flags. Be careful not to cause a deadlock
2556 * as a data-load requires an exclusive lock.
2558 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2559 * range is within the requested key range we return the indirect
2560 * block and do NOT loop. This is usually only used to acquire
2561 * freemap nodes.
2563 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2564 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2565 hammer2_chain_unlock(parent);
2566 hammer2_chain_drop(parent);
2567 *parentp = parent = chain;
2568 goto again;
2570 done:
2572 * All done, return the chain.
2574 * If the caller does not want a locked chain, replace the lock with
2575 * a ref. Perhaps this can eventually be optimized to not obtain the
2576 * lock in the first place for situations where the data does not
2577 * need to be resolved.
2579 * NOTE! A chain->error must be tested by the caller upon return.
2580 * *errorp is only set based on issues which occur while
2581 * trying to reach the chain.
2583 if (chain) {
2584 if (flags & HAMMER2_LOOKUP_NOLOCK)
2585 hammer2_chain_unlock(chain);
2587 return (chain);
2591 * After having issued a lookup we can iterate all matching keys.
2593 * If chain is non-NULL we continue the iteration from just after it's index.
2595 * If chain is NULL we assume the parent was exhausted and continue the
2596 * iteration at the next parent.
2598 * If a fatal error occurs (typically an I/O error), a dummy chain is
2599 * returned with chain->error and error-identifying information set. This
2600 * chain will assert if you try to do anything fancy with it.
2602 * XXX Depending on where the error occurs we should allow continued iteration.
2604 * parent must be locked on entry and remains locked throughout. chain's
2605 * lock status must match flags. Chain is always at least referenced.
2607 * WARNING! The MATCHIND flag does not apply to this function.
2609 hammer2_chain_t *
2610 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2611 hammer2_key_t *key_nextp,
2612 hammer2_key_t key_beg, hammer2_key_t key_end,
2613 int *errorp, int flags)
2615 hammer2_chain_t *parent;
2616 int how_maybe;
2619 * Calculate locking flags for upward recursion.
2621 how_maybe = HAMMER2_RESOLVE_MAYBE;
2622 if (flags & HAMMER2_LOOKUP_SHARED)
2623 how_maybe |= HAMMER2_RESOLVE_SHARED;
2625 parent = *parentp;
2626 *errorp = 0;
2629 * Calculate the next index and recalculate the parent if necessary.
2631 if (chain) {
2632 key_beg = chain->bref.key +
2633 ((hammer2_key_t)1 << chain->bref.keybits);
2634 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2635 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2636 hammer2_chain_unlock(chain);
2638 hammer2_chain_drop(chain);
2641 * chain invalid past this point, but we can still do a
2642 * pointer comparison w/parent.
2644 * Any scan where the lookup returned degenerate data embedded
2645 * in the inode has an invalid index and must terminate.
2647 if (chain == parent)
2648 return(NULL);
2649 if (key_beg == 0 || key_beg > key_end)
2650 return(NULL);
2651 chain = NULL;
2652 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2653 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2655 * We reached the end of the iteration.
2657 return (NULL);
2658 } else {
2660 * Continue iteration with next parent unless the current
2661 * parent covers the range.
2663 * (This also handles the case of a deleted, empty indirect
2664 * node).
2666 key_beg = parent->bref.key +
2667 ((hammer2_key_t)1 << parent->bref.keybits);
2668 if (key_beg == 0 || key_beg > key_end)
2669 return (NULL);
2670 parent = hammer2_chain_repparent(parentp, how_maybe);
2674 * And execute
2676 return (hammer2_chain_lookup(parentp, key_nextp,
2677 key_beg, key_end,
2678 errorp, flags));
2682 * Caller wishes to iterate chains under parent, loading new chains into
2683 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
2684 * then call hammer2_chain_scan() repeatedly until a non-zero return.
2685 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
2686 * with the returned chain for the scan. The returned *chainp will be
2687 * locked and referenced. Any prior contents will be unlocked and dropped.
2689 * Caller should check the return value. A normal scan EOF will return
2690 * exactly HAMMER2_ERRORF_EOF. Any other non-zero value indicates an
2691 * error trying to access parent data. Any error in the returned chain
2692 * must be tested separately by the caller.
2694 * (*chainp) is dropped on each scan, but will only be set if the returned
2695 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
2696 * returned via *chainp. The caller will get their bref only.
2698 * The raw scan function is similar to lookup/next but does not seek to a key.
2699 * Blockrefs are iterated via first_bref = (parent, NULL) and
2700 * next_chain = (parent, bref).
2702 * The passed-in parent must be locked and its data resolved. The function
2703 * nominally returns a locked and referenced *chainp != NULL for chains
2704 * the caller might need to recurse on (and will dipose of any *chainp passed
2705 * in). The caller must check the chain->bref.type either way.
2708 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2709 hammer2_blockref_t *bref, int *firstp,
2710 int flags)
2712 hammer2_dev_t *hmp;
2713 hammer2_blockref_t *base;
2714 hammer2_blockref_t *bref_ptr;
2715 hammer2_key_t key;
2716 hammer2_key_t next_key;
2717 hammer2_chain_t *chain = NULL;
2718 int count = 0;
2719 int how_always = HAMMER2_RESOLVE_ALWAYS;
2720 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2721 int how;
2722 int generation;
2723 int maxloops = 300000;
2724 int error;
2726 hmp = parent->hmp;
2727 error = 0;
2730 * Scan flags borrowed from lookup.
2732 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2733 how_maybe = how_always;
2734 how = HAMMER2_RESOLVE_ALWAYS;
2735 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2736 how = HAMMER2_RESOLVE_NEVER;
2737 } else {
2738 how = HAMMER2_RESOLVE_MAYBE;
2740 if (flags & HAMMER2_LOOKUP_SHARED) {
2741 how_maybe |= HAMMER2_RESOLVE_SHARED;
2742 how_always |= HAMMER2_RESOLVE_SHARED;
2743 how |= HAMMER2_RESOLVE_SHARED;
2747 * Calculate key to locate first/next element, unlocking the previous
2748 * element as we go. Be careful, the key calculation can overflow.
2750 * (also reset bref to NULL)
2752 if (*firstp) {
2753 key = 0;
2754 *firstp = 0;
2755 } else {
2756 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2757 if ((chain = *chainp) != NULL) {
2758 *chainp = NULL;
2759 hammer2_chain_unlock(chain);
2760 hammer2_chain_drop(chain);
2761 chain = NULL;
2763 if (key == 0) {
2764 error |= HAMMER2_ERROR_EOF;
2765 goto done;
2769 again:
2770 if (parent->error) {
2771 error = parent->error;
2772 goto done;
2774 if (--maxloops == 0)
2775 panic("hammer2_chain_scan: maxloops");
2778 * Locate the blockref array. Currently we do a fully associative
2779 * search through the array.
2781 switch(parent->bref.type) {
2782 case HAMMER2_BREF_TYPE_INODE:
2784 * An inode with embedded data has no sub-chains.
2786 * WARNING! Bulk scan code may pass a static chain marked
2787 * as BREF_TYPE_INODE with a copy of the volume
2788 * root blockset to snapshot the volume.
2790 if (parent->data->ipdata.meta.op_flags &
2791 HAMMER2_OPFLAG_DIRECTDATA) {
2792 error |= HAMMER2_ERROR_EOF;
2793 goto done;
2795 base = &parent->data->ipdata.u.blockset.blockref[0];
2796 count = HAMMER2_SET_COUNT;
2797 break;
2798 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2799 case HAMMER2_BREF_TYPE_INDIRECT:
2801 * Optimize indirect blocks in the INITIAL state to avoid
2802 * I/O.
2804 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2805 base = NULL;
2806 } else {
2807 if (parent->data == NULL)
2808 panic("parent->data is NULL");
2809 base = &parent->data->npdata[0];
2811 count = parent->bytes / sizeof(hammer2_blockref_t);
2812 break;
2813 case HAMMER2_BREF_TYPE_VOLUME:
2814 base = &parent->data->voldata.sroot_blockset.blockref[0];
2815 count = HAMMER2_SET_COUNT;
2816 break;
2817 case HAMMER2_BREF_TYPE_FREEMAP:
2818 base = &parent->data->blkset.blockref[0];
2819 count = HAMMER2_SET_COUNT;
2820 break;
2821 default:
2822 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2823 parent->bref.type);
2824 base = NULL; /* safety */
2825 count = 0; /* safety */
2829 * Merged scan to find next candidate.
2831 * hammer2_base_*() functions require the parent->core.live_* fields
2832 * to be synchronized.
2834 * We need to hold the spinlock to access the block array and RB tree
2835 * and to interlock chain creation.
2837 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2838 hammer2_chain_countbrefs(parent, base, count);
2840 next_key = 0;
2841 bref_ptr = NULL;
2842 hammer2_spin_ex(&parent->core.spin);
2843 chain = hammer2_combined_find(parent, base, count,
2844 &next_key,
2845 key, HAMMER2_KEY_MAX,
2846 &bref_ptr);
2847 generation = parent->core.generation;
2850 * Exhausted parent chain, we're done.
2852 if (bref_ptr == NULL) {
2853 hammer2_spin_unex(&parent->core.spin);
2854 KKASSERT(chain == NULL);
2855 error |= HAMMER2_ERROR_EOF;
2856 goto done;
2860 * Copy into the supplied stack-based blockref.
2862 *bref = *bref_ptr;
2865 * Selected from blockref or in-memory chain.
2867 if (chain == NULL) {
2868 switch(bref->type) {
2869 case HAMMER2_BREF_TYPE_INODE:
2870 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2871 case HAMMER2_BREF_TYPE_INDIRECT:
2872 case HAMMER2_BREF_TYPE_VOLUME:
2873 case HAMMER2_BREF_TYPE_FREEMAP:
2875 * Recursion, always get the chain
2877 hammer2_spin_unex(&parent->core.spin);
2878 chain = hammer2_chain_get(parent, generation, bref);
2879 if (chain == NULL) {
2880 kprintf("retry scan parent %p keys %016jx\n",
2881 parent, key);
2882 goto again;
2884 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2885 hammer2_chain_drop(chain);
2886 chain = NULL;
2887 goto again;
2889 break;
2890 default:
2892 * No recursion, do not waste time instantiating
2893 * a chain, just iterate using the bref.
2895 hammer2_spin_unex(&parent->core.spin);
2896 break;
2898 } else {
2900 * Recursion or not we need the chain in order to supply
2901 * the bref.
2903 hammer2_chain_ref(chain);
2904 hammer2_spin_unex(&parent->core.spin);
2908 * chain is referenced but not locked. We must lock the chain
2909 * to obtain definitive state.
2911 if (chain)
2912 hammer2_chain_lock(chain, how);
2915 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2917 * NOTE: chain's key range is not relevant as there might be
2918 * one-offs within the range that are not deleted.
2920 * NOTE: XXX this could create problems with scans used in
2921 * situations other than mount-time recovery.
2923 * NOTE: Lookups can race delete-duplicate because
2924 * delete-duplicate does not lock the parent's core
2925 * (they just use the spinlock on the core).
2927 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2928 hammer2_chain_unlock(chain);
2929 hammer2_chain_drop(chain);
2930 chain = NULL;
2932 key = next_key;
2933 if (key == 0) {
2934 error |= HAMMER2_ERROR_EOF;
2935 goto done;
2937 goto again;
2940 done:
2942 * All done, return the bref or NULL, supply chain if necessary.
2944 if (chain)
2945 *chainp = chain;
2946 return (error);
2950 * Create and return a new hammer2 system memory structure of the specified
2951 * key, type and size and insert it under (*parentp). This is a full
2952 * insertion, based on the supplied key/keybits, and may involve creating
2953 * indirect blocks and moving other chains around via delete/duplicate.
2955 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2956 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2957 * FULL. This typically means that the caller is creating the chain after
2958 * doing a hammer2_chain_lookup().
2960 * (*parentp) must be exclusive locked and may be replaced on return
2961 * depending on how much work the function had to do.
2963 * (*parentp) must not be errored or this function will assert.
2965 * (*chainp) usually starts out NULL and returns the newly created chain,
2966 * but if the caller desires the caller may allocate a disconnected chain
2967 * and pass it in instead.
2969 * This function should NOT be used to insert INDIRECT blocks. It is
2970 * typically used to create/insert inodes and data blocks.
2972 * Caller must pass-in an exclusively locked parent the new chain is to
2973 * be inserted under, and optionally pass-in a disconnected, exclusively
2974 * locked chain to insert (else we create a new chain). The function will
2975 * adjust (*parentp) as necessary, create or connect the chain, and
2976 * return an exclusively locked chain in *chainp.
2978 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2979 * and will be reassigned.
2981 * NOTE: returns HAMMER_ERROR_* flags
2984 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2985 hammer2_pfs_t *pmp, int methods,
2986 hammer2_key_t key, int keybits, int type, size_t bytes,
2987 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2989 hammer2_dev_t *hmp;
2990 hammer2_chain_t *chain;
2991 hammer2_chain_t *parent;
2992 hammer2_blockref_t *base;
2993 hammer2_blockref_t dummy;
2994 int allocated = 0;
2995 int error = 0;
2996 int count;
2997 int maxloops = 300000;
3000 * Topology may be crossing a PFS boundary.
3002 parent = *parentp;
3003 KKASSERT(hammer2_mtx_owned(&parent->lock));
3004 KKASSERT(parent->error == 0);
3005 hmp = parent->hmp;
3006 chain = *chainp;
3008 if (chain == NULL) {
3010 * First allocate media space and construct the dummy bref,
3011 * then allocate the in-memory chain structure. Set the
3012 * INITIAL flag for fresh chains which do not have embedded
3013 * data.
3015 * XXX for now set the check mode of the child based on
3016 * the parent or, if the parent is an inode, the
3017 * specification in the inode.
3019 bzero(&dummy, sizeof(dummy));
3020 dummy.type = type;
3021 dummy.key = key;
3022 dummy.keybits = keybits;
3023 dummy.data_off = hammer2_getradix(bytes);
3026 * Inherit methods from parent by default. Primarily used
3027 * for BREF_TYPE_DATA. Non-data types *must* be set to
3028 * a non-NONE check algorithm.
3030 if (methods == -1)
3031 dummy.methods = parent->bref.methods;
3032 else
3033 dummy.methods = (uint8_t)methods;
3035 if (type != HAMMER2_BREF_TYPE_DATA &&
3036 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3037 dummy.methods |=
3038 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3041 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3044 * Lock the chain manually, chain_lock will load the chain
3045 * which we do NOT want to do. (note: chain->refs is set
3046 * to 1 by chain_alloc() for us, but lockcnt is not).
3048 chain->lockcnt = 1;
3049 hammer2_mtx_ex(&chain->lock);
3050 allocated = 1;
3051 ++curthread->td_tracker;
3054 * Set INITIAL to optimize I/O. The flag will generally be
3055 * processed when we call hammer2_chain_modify().
3057 * Recalculate bytes to reflect the actual media block
3058 * allocation. Handle special case radix 0 == 0 bytes.
3060 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3061 if (bytes)
3062 bytes = (hammer2_off_t)1 << bytes;
3063 chain->bytes = bytes;
3065 switch(type) {
3066 case HAMMER2_BREF_TYPE_VOLUME:
3067 case HAMMER2_BREF_TYPE_FREEMAP:
3068 panic("hammer2_chain_create: called with volume type");
3069 break;
3070 case HAMMER2_BREF_TYPE_INDIRECT:
3071 panic("hammer2_chain_create: cannot be used to"
3072 "create indirect block");
3073 break;
3074 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3075 panic("hammer2_chain_create: cannot be used to"
3076 "create freemap root or node");
3077 break;
3078 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3079 KKASSERT(bytes == sizeof(chain->data->bmdata));
3080 /* fall through */
3081 case HAMMER2_BREF_TYPE_DIRENT:
3082 case HAMMER2_BREF_TYPE_INODE:
3083 case HAMMER2_BREF_TYPE_DATA:
3084 default:
3086 * leave chain->data NULL, set INITIAL
3088 KKASSERT(chain->data == NULL);
3089 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3090 break;
3092 } else {
3094 * We are reattaching a previously deleted chain, possibly
3095 * under a new parent and possibly with a new key/keybits.
3096 * The chain does not have to be in a modified state. The
3097 * UPDATE flag will be set later on in this routine.
3099 * Do NOT mess with the current state of the INITIAL flag.
3101 chain->bref.key = key;
3102 chain->bref.keybits = keybits;
3103 if (chain->flags & HAMMER2_CHAIN_DELETED)
3104 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3105 KKASSERT(chain->parent == NULL);
3107 if (flags & HAMMER2_INSERT_PFSROOT)
3108 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3109 else
3110 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3113 * Calculate how many entries we have in the blockref array and
3114 * determine if an indirect block is required.
3116 again:
3117 if (--maxloops == 0)
3118 panic("hammer2_chain_create: maxloops");
3120 switch(parent->bref.type) {
3121 case HAMMER2_BREF_TYPE_INODE:
3122 if ((parent->data->ipdata.meta.op_flags &
3123 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3124 kprintf("hammer2: parent set for direct-data! "
3125 "pkey=%016jx ckey=%016jx\n",
3126 parent->bref.key,
3127 chain->bref.key);
3129 KKASSERT((parent->data->ipdata.meta.op_flags &
3130 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3131 KKASSERT(parent->data != NULL);
3132 base = &parent->data->ipdata.u.blockset.blockref[0];
3133 count = HAMMER2_SET_COUNT;
3134 break;
3135 case HAMMER2_BREF_TYPE_INDIRECT:
3136 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3137 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3138 base = NULL;
3139 else
3140 base = &parent->data->npdata[0];
3141 count = parent->bytes / sizeof(hammer2_blockref_t);
3142 break;
3143 case HAMMER2_BREF_TYPE_VOLUME:
3144 KKASSERT(parent->data != NULL);
3145 base = &parent->data->voldata.sroot_blockset.blockref[0];
3146 count = HAMMER2_SET_COUNT;
3147 break;
3148 case HAMMER2_BREF_TYPE_FREEMAP:
3149 KKASSERT(parent->data != NULL);
3150 base = &parent->data->blkset.blockref[0];
3151 count = HAMMER2_SET_COUNT;
3152 break;
3153 default:
3154 panic("hammer2_chain_create: unrecognized blockref type: %d",
3155 parent->bref.type);
3156 base = NULL;
3157 count = 0;
3158 break;
3162 * Make sure we've counted the brefs
3164 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3165 hammer2_chain_countbrefs(parent, base, count);
3167 KASSERT(parent->core.live_count >= 0 &&
3168 parent->core.live_count <= count,
3169 ("bad live_count %d/%d (%02x, %d)",
3170 parent->core.live_count, count,
3171 parent->bref.type, parent->bytes));
3174 * If no free blockref could be found we must create an indirect
3175 * block and move a number of blockrefs into it. With the parent
3176 * locked we can safely lock each child in order to delete+duplicate
3177 * it without causing a deadlock.
3179 * This may return the new indirect block or the old parent depending
3180 * on where the key falls. NULL is returned on error.
3182 if (parent->core.live_count == count) {
3183 hammer2_chain_t *nparent;
3185 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3186 mtid, type, &error);
3187 if (nparent == NULL) {
3188 if (allocated)
3189 hammer2_chain_drop(chain);
3190 chain = NULL;
3191 goto done;
3193 if (parent != nparent) {
3194 hammer2_chain_unlock(parent);
3195 hammer2_chain_drop(parent);
3196 parent = *parentp = nparent;
3198 goto again;
3201 if (chain->flags & HAMMER2_CHAIN_DELETED)
3202 kprintf("Inserting deleted chain @%016jx\n",
3203 chain->bref.key);
3206 * Link the chain into its parent.
3208 if (chain->parent != NULL)
3209 panic("hammer2: hammer2_chain_create: chain already connected");
3210 KKASSERT(chain->parent == NULL);
3211 hammer2_chain_insert(parent, chain,
3212 HAMMER2_CHAIN_INSERT_SPIN |
3213 HAMMER2_CHAIN_INSERT_LIVE,
3216 if (allocated) {
3218 * Mark the newly created chain modified. This will cause
3219 * UPDATE to be set and process the INITIAL flag.
3221 * Device buffers are not instantiated for DATA elements
3222 * as these are handled by logical buffers.
3224 * Indirect and freemap node indirect blocks are handled
3225 * by hammer2_chain_create_indirect() and not by this
3226 * function.
3228 * Data for all other bref types is expected to be
3229 * instantiated (INODE, LEAF).
3231 switch(chain->bref.type) {
3232 case HAMMER2_BREF_TYPE_DATA:
3233 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3234 case HAMMER2_BREF_TYPE_DIRENT:
3235 case HAMMER2_BREF_TYPE_INODE:
3236 hammer2_chain_modify(chain, mtid, dedup_off,
3237 HAMMER2_MODIFY_OPTDATA);
3238 break;
3239 default:
3241 * Remaining types are not supported by this function.
3242 * In particular, INDIRECT and LEAF_NODE types are
3243 * handled by create_indirect().
3245 panic("hammer2_chain_create: bad type: %d",
3246 chain->bref.type);
3247 /* NOT REACHED */
3248 break;
3250 } else {
3252 * When reconnecting a chain we must set UPDATE and
3253 * setflush so the flush recognizes that it must update
3254 * the bref in the parent.
3256 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3257 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3261 * We must setflush(parent) to ensure that it recurses through to
3262 * chain. setflush(chain) might not work because ONFLUSH is possibly
3263 * already set in the chain (so it won't recurse up to set it in the
3264 * parent).
3266 hammer2_chain_setflush(parent);
3268 done:
3269 *chainp = chain;
3271 return (error);
3275 * Move the chain from its old parent to a new parent. The chain must have
3276 * already been deleted or already disconnected (or never associated) with
3277 * a parent. The chain is reassociated with the new parent and the deleted
3278 * flag will be cleared (no longer deleted). The chain's modification state
3279 * is not altered.
3281 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3282 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3283 * FULL. This typically means that the caller is creating the chain after
3284 * doing a hammer2_chain_lookup().
3286 * A non-NULL bref is typically passed when key and keybits must be overridden.
3287 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3288 * from a passed-in bref and uses the old chain's bref for everything else.
3290 * Neither (parent) or (chain) can be errored.
3292 * If (parent) is non-NULL then the chain is inserted under the parent.
3294 * If (parent) is NULL then the newly duplicated chain is not inserted
3295 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3296 * passing into hammer2_chain_create() after this function returns).
3298 * WARNING! This function calls create which means it can insert indirect
3299 * blocks. This can cause other unrelated chains in the parent to
3300 * be moved to a newly inserted indirect block in addition to the
3301 * specific chain.
3303 void
3304 hammer2_chain_rename(hammer2_blockref_t *bref,
3305 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3306 hammer2_tid_t mtid, int flags)
3308 hammer2_dev_t *hmp;
3309 hammer2_chain_t *parent;
3310 size_t bytes;
3313 * WARNING! We should never resolve DATA to device buffers
3314 * (XXX allow it if the caller did?), and since
3315 * we currently do not have the logical buffer cache
3316 * buffer in-hand to fix its cached physical offset
3317 * we also force the modify code to not COW it. XXX
3319 hmp = chain->hmp;
3320 KKASSERT(chain->parent == NULL);
3321 KKASSERT(chain->error == 0);
3324 * Now create a duplicate of the chain structure, associating
3325 * it with the same core, making it the same size, pointing it
3326 * to the same bref (the same media block).
3328 * NOTE: Handle special radix == 0 case (means 0 bytes).
3330 if (bref == NULL)
3331 bref = &chain->bref;
3332 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3333 if (bytes)
3334 bytes = (hammer2_off_t)1 << bytes;
3337 * If parent is not NULL the duplicated chain will be entered under
3338 * the parent and the UPDATE bit set to tell flush to update
3339 * the blockref.
3341 * We must setflush(parent) to ensure that it recurses through to
3342 * chain. setflush(chain) might not work because ONFLUSH is possibly
3343 * already set in the chain (so it won't recurse up to set it in the
3344 * parent).
3346 * Having both chains locked is extremely important for atomicy.
3348 if (parentp && (parent = *parentp) != NULL) {
3349 KKASSERT(hammer2_mtx_owned(&parent->lock));
3350 KKASSERT(parent->refs > 0);
3351 KKASSERT(parent->error == 0);
3353 hammer2_chain_create(parentp, &chain,
3354 chain->pmp, HAMMER2_METH_DEFAULT,
3355 bref->key, bref->keybits, bref->type,
3356 chain->bytes, mtid, 0, flags);
3357 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3358 hammer2_chain_setflush(*parentp);
3363 * Helper function for deleting chains.
3365 * The chain is removed from the live view (the RBTREE) as well as the parent's
3366 * blockmap. Both chain and its parent must be locked.
3368 * parent may not be errored. chain can be errored.
3370 static void
3371 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3372 hammer2_tid_t mtid, int flags)
3374 hammer2_dev_t *hmp;
3376 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3377 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3378 KKASSERT(chain->parent == parent);
3379 hmp = chain->hmp;
3381 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3383 * Chain is blockmapped, so there must be a parent.
3384 * Atomically remove the chain from the parent and remove
3385 * the blockmap entry. The parent must be set modified
3386 * to remove the blockmap entry.
3388 hammer2_blockref_t *base;
3389 int count;
3391 KKASSERT(parent != NULL);
3392 KKASSERT(parent->error == 0);
3393 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3394 hammer2_chain_modify(parent, mtid, 0, 0);
3397 * Calculate blockmap pointer
3399 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3400 hammer2_spin_ex(&chain->core.spin);
3401 hammer2_spin_ex(&parent->core.spin);
3403 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3404 atomic_add_int(&parent->core.live_count, -1);
3405 ++parent->core.generation;
3406 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3407 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3408 --parent->core.chain_count;
3409 chain->parent = NULL;
3411 switch(parent->bref.type) {
3412 case HAMMER2_BREF_TYPE_INODE:
3414 * Access the inode's block array. However, there
3415 * is no block array if the inode is flagged
3416 * DIRECTDATA.
3418 if (parent->data &&
3419 (parent->data->ipdata.meta.op_flags &
3420 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3421 base =
3422 &parent->data->ipdata.u.blockset.blockref[0];
3423 } else {
3424 base = NULL;
3426 count = HAMMER2_SET_COUNT;
3427 break;
3428 case HAMMER2_BREF_TYPE_INDIRECT:
3429 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3430 if (parent->data)
3431 base = &parent->data->npdata[0];
3432 else
3433 base = NULL;
3434 count = parent->bytes / sizeof(hammer2_blockref_t);
3435 break;
3436 case HAMMER2_BREF_TYPE_VOLUME:
3437 base = &parent->data->voldata.
3438 sroot_blockset.blockref[0];
3439 count = HAMMER2_SET_COUNT;
3440 break;
3441 case HAMMER2_BREF_TYPE_FREEMAP:
3442 base = &parent->data->blkset.blockref[0];
3443 count = HAMMER2_SET_COUNT;
3444 break;
3445 default:
3446 base = NULL;
3447 count = 0;
3448 panic("hammer2_flush_pass2: "
3449 "unrecognized blockref type: %d",
3450 parent->bref.type);
3454 * delete blockmapped chain from its parent.
3456 * The parent is not affected by any statistics in chain
3457 * which are pending synchronization. That is, there is
3458 * nothing to undo in the parent since they have not yet
3459 * been incorporated into the parent.
3461 * The parent is affected by statistics stored in inodes.
3462 * Those have already been synchronized, so they must be
3463 * undone. XXX split update possible w/delete in middle?
3465 if (base) {
3466 hammer2_base_delete(parent, base, count, chain);
3468 hammer2_spin_unex(&parent->core.spin);
3469 hammer2_spin_unex(&chain->core.spin);
3470 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3472 * Chain is not blockmapped but a parent is present.
3473 * Atomically remove the chain from the parent. There is
3474 * no blockmap entry to remove.
3476 * Because chain was associated with a parent but not
3477 * synchronized, the chain's *_count_up fields contain
3478 * inode adjustment statistics which must be undone.
3480 hammer2_spin_ex(&chain->core.spin);
3481 hammer2_spin_ex(&parent->core.spin);
3482 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3483 atomic_add_int(&parent->core.live_count, -1);
3484 ++parent->core.generation;
3485 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3486 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3487 --parent->core.chain_count;
3488 chain->parent = NULL;
3489 hammer2_spin_unex(&parent->core.spin);
3490 hammer2_spin_unex(&chain->core.spin);
3491 } else {
3493 * Chain is not blockmapped and has no parent. This
3494 * is a degenerate case.
3496 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3501 * Create an indirect block that covers one or more of the elements in the
3502 * current parent. Either returns the existing parent with no locking or
3503 * ref changes or returns the new indirect block locked and referenced
3504 * and leaving the original parent lock/ref intact as well.
3506 * If an error occurs, NULL is returned and *errorp is set to the error.
3508 * The returned chain depends on where the specified key falls.
3510 * The key/keybits for the indirect mode only needs to follow three rules:
3512 * (1) That all elements underneath it fit within its key space and
3514 * (2) That all elements outside it are outside its key space.
3516 * (3) When creating the new indirect block any elements in the current
3517 * parent that fit within the new indirect block's keyspace must be
3518 * moved into the new indirect block.
3520 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3521 * keyspace the the current parent, but lookup/iteration rules will
3522 * ensure (and must ensure) that rule (2) for all parents leading up
3523 * to the nearest inode or the root volume header is adhered to. This
3524 * is accomplished by always recursing through matching keyspaces in
3525 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3527 * The current implementation calculates the current worst-case keyspace by
3528 * iterating the current parent and then divides it into two halves, choosing
3529 * whichever half has the most elements (not necessarily the half containing
3530 * the requested key).
3532 * We can also opt to use the half with the least number of elements. This
3533 * causes lower-numbered keys (aka logical file offsets) to recurse through
3534 * fewer indirect blocks and higher-numbered keys to recurse through more.
3535 * This also has the risk of not moving enough elements to the new indirect
3536 * block and being forced to create several indirect blocks before the element
3537 * can be inserted.
3539 * Must be called with an exclusively locked parent.
3541 * NOTE: *errorp set to HAMMER_ERROR_* flags
3543 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3544 hammer2_key_t *keyp, int keybits,
3545 hammer2_blockref_t *base, int count);
3546 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3547 hammer2_key_t *keyp, int keybits,
3548 hammer2_blockref_t *base, int count,
3549 int ncount);
3550 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3551 hammer2_key_t *keyp, int keybits,
3552 hammer2_blockref_t *base, int count,
3553 int ncount);
3554 static
3555 hammer2_chain_t *
3556 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3557 hammer2_key_t create_key, int create_bits,
3558 hammer2_tid_t mtid, int for_type, int *errorp)
3560 hammer2_dev_t *hmp;
3561 hammer2_blockref_t *base;
3562 hammer2_blockref_t *bref;
3563 hammer2_blockref_t bcopy;
3564 hammer2_chain_t *chain;
3565 hammer2_chain_t *ichain;
3566 hammer2_chain_t dummy;
3567 hammer2_key_t key = create_key;
3568 hammer2_key_t key_beg;
3569 hammer2_key_t key_end;
3570 hammer2_key_t key_next;
3571 int keybits = create_bits;
3572 int count;
3573 int ncount;
3574 int nbytes;
3575 int loops;
3576 int reason;
3577 int generation;
3578 int maxloops = 300000;
3581 * Calculate the base blockref pointer or NULL if the chain
3582 * is known to be empty. We need to calculate the array count
3583 * for RB lookups either way.
3585 hmp = parent->hmp;
3586 *errorp = 0;
3587 KKASSERT(hammer2_mtx_owned(&parent->lock));
3589 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3590 base = hammer2_chain_base_and_count(parent, &count);
3593 * dummy used in later chain allocation (no longer used for lookups).
3595 bzero(&dummy, sizeof(dummy));
3598 * How big should our new indirect block be? It has to be at least
3599 * as large as its parent for splits to work properly.
3601 * The freemap uses a specific indirect block size. The number of
3602 * levels are built dynamically and ultimately depend on the size
3603 * volume. Because freemap blocks are taken from the reserved areas
3604 * of the volume our goal is efficiency (fewer levels) and not so
3605 * much to save disk space.
3607 * The first indirect block level for a directory usually uses
3608 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3609 * the hash mechanism, this typically gives us a nominal
3610 * 32 * 4 entries with one level of indirection.
3612 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3613 * indirect blocks. The initial 4 entries in the inode gives us
3614 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3615 * of indirection gives us 137GB, and so forth. H2 can support
3616 * huge file sizes but they are not typical, so we try to stick
3617 * with compactness and do not use a larger indirect block size.
3619 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3620 * due to the way indirect blocks are created this usually winds
3621 * up being extremely inefficient for small files. Even though
3622 * 16KB requires more levels of indirection for very large files,
3623 * the 16KB records can be ganged together into 64KB DIOs.
3625 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3626 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3627 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3628 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3629 if (parent->data->ipdata.meta.type ==
3630 HAMMER2_OBJTYPE_DIRECTORY)
3631 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3632 else
3633 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3635 } else {
3636 nbytes = HAMMER2_IND_BYTES_NOM;
3638 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3639 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3640 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3641 nbytes = count * sizeof(hammer2_blockref_t);
3643 ncount = nbytes / sizeof(hammer2_blockref_t);
3646 * When creating an indirect block for a freemap node or leaf
3647 * the key/keybits must be fitted to static radix levels because
3648 * particular radix levels use particular reserved blocks in the
3649 * related zone.
3651 * This routine calculates the key/radix of the indirect block
3652 * we need to create, and whether it is on the high-side or the
3653 * low-side.
3655 switch(for_type) {
3656 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3657 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3658 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3659 base, count);
3660 break;
3661 case HAMMER2_BREF_TYPE_DATA:
3662 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3663 base, count, ncount);
3664 break;
3665 case HAMMER2_BREF_TYPE_DIRENT:
3666 case HAMMER2_BREF_TYPE_INODE:
3667 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3668 base, count, ncount);
3669 break;
3670 default:
3671 panic("illegal indirect block for bref type %d", for_type);
3672 break;
3676 * Normalize the key for the radix being represented, keeping the
3677 * high bits and throwing away the low bits.
3679 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3682 * Ok, create our new indirect block
3684 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3685 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3686 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3687 } else {
3688 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3690 dummy.bref.key = key;
3691 dummy.bref.keybits = keybits;
3692 dummy.bref.data_off = hammer2_getradix(nbytes);
3693 dummy.bref.methods =
3694 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3695 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3697 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3698 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3699 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3700 /* ichain has one ref at this point */
3703 * We have to mark it modified to allocate its block, but use
3704 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3705 * it won't be acted upon by the flush code.
3707 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3710 * Iterate the original parent and move the matching brefs into
3711 * the new indirect block.
3713 * XXX handle flushes.
3715 key_beg = 0;
3716 key_end = HAMMER2_KEY_MAX;
3717 key_next = 0; /* avoid gcc warnings */
3718 hammer2_spin_ex(&parent->core.spin);
3719 loops = 0;
3720 reason = 0;
3722 for (;;) {
3724 * Parent may have been modified, relocating its block array.
3725 * Reload the base pointer.
3727 base = hammer2_chain_base_and_count(parent, &count);
3729 if (++loops > 100000) {
3730 hammer2_spin_unex(&parent->core.spin);
3731 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3732 reason, parent, base, count, key_next);
3736 * NOTE: spinlock stays intact, returned chain (if not NULL)
3737 * is not referenced or locked which means that we
3738 * cannot safely check its flagged / deletion status
3739 * until we lock it.
3741 chain = hammer2_combined_find(parent, base, count,
3742 &key_next,
3743 key_beg, key_end,
3744 &bref);
3745 generation = parent->core.generation;
3746 if (bref == NULL)
3747 break;
3748 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3751 * Skip keys that are not within the key/radix of the new
3752 * indirect block. They stay in the parent.
3754 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3755 (key ^ bref->key)) != 0) {
3756 goto next_key_spinlocked;
3760 * Load the new indirect block by acquiring the related
3761 * chains (potentially from media as it might not be
3762 * in-memory). Then move it to the new parent (ichain).
3764 * chain is referenced but not locked. We must lock the
3765 * chain to obtain definitive state.
3767 if (chain) {
3769 * Use chain already present in the RBTREE
3771 hammer2_chain_ref(chain);
3772 hammer2_spin_unex(&parent->core.spin);
3773 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3774 } else {
3776 * Get chain for blockref element. _get returns NULL
3777 * on insertion race.
3779 bcopy = *bref;
3780 hammer2_spin_unex(&parent->core.spin);
3781 chain = hammer2_chain_get(parent, generation, &bcopy);
3782 if (chain == NULL) {
3783 reason = 1;
3784 hammer2_spin_ex(&parent->core.spin);
3785 continue;
3787 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3788 kprintf("REASON 2\n");
3789 reason = 2;
3790 hammer2_chain_drop(chain);
3791 hammer2_spin_ex(&parent->core.spin);
3792 continue;
3794 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3798 * This is always live so if the chain has been deleted
3799 * we raced someone and we have to retry.
3801 * NOTE: Lookups can race delete-duplicate because
3802 * delete-duplicate does not lock the parent's core
3803 * (they just use the spinlock on the core).
3805 * (note reversed logic for this one)
3807 if (chain->parent != parent ||
3808 (chain->flags & HAMMER2_CHAIN_DELETED)) {
3809 hammer2_chain_unlock(chain);
3810 hammer2_chain_drop(chain);
3811 kprintf("hammer2_chain_create_indirect "
3812 "RETRY (%p,%p)->%p %08x\n",
3813 parent, chain->parent, chain, chain->flags);
3814 hammer2_spin_ex(&parent->core.spin);
3815 continue;
3819 * Shift the chain to the indirect block.
3821 * WARNING! No reason for us to load chain data, pass NOSTATS
3822 * to prevent delete/insert from trying to access
3823 * inode stats (and thus asserting if there is no
3824 * chain->data loaded).
3826 * WARNING! The (parent, chain) deletion may modify the parent
3827 * and invalidate the base pointer.
3829 hammer2_chain_delete(parent, chain, mtid, 0);
3830 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3831 hammer2_chain_unlock(chain);
3832 hammer2_chain_drop(chain);
3833 KKASSERT(parent->refs > 0);
3834 chain = NULL;
3835 base = NULL; /* safety */
3836 hammer2_spin_ex(&parent->core.spin);
3837 next_key_spinlocked:
3838 if (--maxloops == 0)
3839 panic("hammer2_chain_create_indirect: maxloops");
3840 reason = 4;
3841 if (key_next == 0 || key_next > key_end)
3842 break;
3843 key_beg = key_next;
3844 /* loop */
3846 hammer2_spin_unex(&parent->core.spin);
3849 * Insert the new indirect block into the parent now that we've
3850 * cleared out some entries in the parent. We calculated a good
3851 * insertion index in the loop above (ichain->index).
3853 * We don't have to set UPDATE here because we mark ichain
3854 * modified down below (so the normal modified -> flush -> set-moved
3855 * sequence applies).
3857 * The insertion shouldn't race as this is a completely new block
3858 * and the parent is locked.
3860 base = NULL; /* safety, parent modify may change address */
3861 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3862 hammer2_chain_insert(parent, ichain,
3863 HAMMER2_CHAIN_INSERT_SPIN |
3864 HAMMER2_CHAIN_INSERT_LIVE,
3868 * Make sure flushes propogate after our manual insertion.
3870 hammer2_chain_setflush(ichain);
3871 hammer2_chain_setflush(parent);
3874 * Figure out what to return.
3876 if (~(((hammer2_key_t)1 << keybits) - 1) &
3877 (create_key ^ key)) {
3879 * Key being created is outside the key range,
3880 * return the original parent.
3882 hammer2_chain_unlock(ichain);
3883 hammer2_chain_drop(ichain);
3884 } else {
3886 * Otherwise its in the range, return the new parent.
3887 * (leave both the new and old parent locked).
3889 parent = ichain;
3892 return(parent);
3896 * Freemap indirect blocks
3898 * Calculate the keybits and highside/lowside of the freemap node the
3899 * caller is creating.
3901 * This routine will specify the next higher-level freemap key/radix
3902 * representing the lowest-ordered set. By doing so, eventually all
3903 * low-ordered sets will be moved one level down.
3905 * We have to be careful here because the freemap reserves a limited
3906 * number of blocks for a limited number of levels. So we can't just
3907 * push indiscriminately.
3910 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3911 int keybits, hammer2_blockref_t *base, int count)
3913 hammer2_chain_t *chain;
3914 hammer2_blockref_t *bref;
3915 hammer2_key_t key;
3916 hammer2_key_t key_beg;
3917 hammer2_key_t key_end;
3918 hammer2_key_t key_next;
3919 int locount;
3920 int hicount;
3921 int maxloops = 300000;
3923 key = *keyp;
3924 locount = 0;
3925 hicount = 0;
3926 keybits = 64;
3929 * Calculate the range of keys in the array being careful to skip
3930 * slots which are overridden with a deletion.
3932 key_beg = 0;
3933 key_end = HAMMER2_KEY_MAX;
3934 hammer2_spin_ex(&parent->core.spin);
3936 for (;;) {
3937 if (--maxloops == 0) {
3938 panic("indkey_freemap shit %p %p:%d\n",
3939 parent, base, count);
3941 chain = hammer2_combined_find(parent, base, count,
3942 &key_next,
3943 key_beg, key_end,
3944 &bref);
3947 * Exhausted search
3949 if (bref == NULL)
3950 break;
3953 * Skip deleted chains.
3955 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3956 if (key_next == 0 || key_next > key_end)
3957 break;
3958 key_beg = key_next;
3959 continue;
3963 * Use the full live (not deleted) element for the scan
3964 * iteration. HAMMER2 does not allow partial replacements.
3966 * XXX should be built into hammer2_combined_find().
3968 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3970 if (keybits > bref->keybits) {
3971 key = bref->key;
3972 keybits = bref->keybits;
3973 } else if (keybits == bref->keybits && bref->key < key) {
3974 key = bref->key;
3976 if (key_next == 0)
3977 break;
3978 key_beg = key_next;
3980 hammer2_spin_unex(&parent->core.spin);
3983 * Return the keybits for a higher-level FREEMAP_NODE covering
3984 * this node.
3986 switch(keybits) {
3987 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3988 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3989 break;
3990 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3991 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3992 break;
3993 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3994 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3995 break;
3996 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3997 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3998 break;
3999 case HAMMER2_FREEMAP_LEVEL4_RADIX:
4000 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
4001 break;
4002 case HAMMER2_FREEMAP_LEVEL5_RADIX:
4003 panic("hammer2_chain_indkey_freemap: level too high");
4004 break;
4005 default:
4006 panic("hammer2_chain_indkey_freemap: bad radix");
4007 break;
4009 *keyp = key;
4011 return (keybits);
4015 * File indirect blocks
4017 * Calculate the key/keybits for the indirect block to create by scanning
4018 * existing keys. The key being created is also passed in *keyp and can be
4019 * inside or outside the indirect block. Regardless, the indirect block
4020 * must hold at least two keys in order to guarantee sufficient space.
4022 * We use a modified version of the freemap's fixed radix tree, but taylored
4023 * for file data. Basically we configure an indirect block encompassing the
4024 * smallest key.
4026 static int
4027 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4028 int keybits, hammer2_blockref_t *base, int count,
4029 int ncount)
4031 hammer2_chain_t *chain;
4032 hammer2_blockref_t *bref;
4033 hammer2_key_t key;
4034 hammer2_key_t key_beg;
4035 hammer2_key_t key_end;
4036 hammer2_key_t key_next;
4037 int nradix;
4038 int locount;
4039 int hicount;
4040 int maxloops = 300000;
4042 key = *keyp;
4043 locount = 0;
4044 hicount = 0;
4045 keybits = 64;
4048 * Calculate the range of keys in the array being careful to skip
4049 * slots which are overridden with a deletion.
4051 * Locate the smallest key.
4053 key_beg = 0;
4054 key_end = HAMMER2_KEY_MAX;
4055 hammer2_spin_ex(&parent->core.spin);
4057 for (;;) {
4058 if (--maxloops == 0) {
4059 panic("indkey_freemap shit %p %p:%d\n",
4060 parent, base, count);
4062 chain = hammer2_combined_find(parent, base, count,
4063 &key_next,
4064 key_beg, key_end,
4065 &bref);
4068 * Exhausted search
4070 if (bref == NULL)
4071 break;
4074 * Skip deleted chains.
4076 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4077 if (key_next == 0 || key_next > key_end)
4078 break;
4079 key_beg = key_next;
4080 continue;
4084 * Use the full live (not deleted) element for the scan
4085 * iteration. HAMMER2 does not allow partial replacements.
4087 * XXX should be built into hammer2_combined_find().
4089 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4091 if (keybits > bref->keybits) {
4092 key = bref->key;
4093 keybits = bref->keybits;
4094 } else if (keybits == bref->keybits && bref->key < key) {
4095 key = bref->key;
4097 if (key_next == 0)
4098 break;
4099 key_beg = key_next;
4101 hammer2_spin_unex(&parent->core.spin);
4104 * Calculate the static keybits for a higher-level indirect block
4105 * that contains the key.
4107 *keyp = key;
4109 switch(ncount) {
4110 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4111 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4112 break;
4113 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4114 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4115 break;
4116 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4117 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4118 break;
4119 default:
4120 panic("bad ncount %d\n", ncount);
4121 nradix = 0;
4122 break;
4126 * The largest radix that can be returned for an indirect block is
4127 * 63 bits. (The largest practical indirect block radix is actually
4128 * 62 bits because the top-level inode or volume root contains four
4129 * entries, but allow 63 to be returned).
4131 if (nradix >= 64)
4132 nradix = 63;
4134 return keybits + nradix;
4137 #if 1
4140 * Directory indirect blocks.
4142 * Covers both the inode index (directory of inodes), and directory contents
4143 * (filenames hardlinked to inodes).
4145 * Because directory keys are hashed we generally try to cut the space in
4146 * half. We accomodate the inode index (which tends to have linearly
4147 * increasing inode numbers) by ensuring that the keyspace is at least large
4148 * enough to fill up the indirect block being created.
4150 static int
4151 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4152 int keybits, hammer2_blockref_t *base, int count,
4153 int ncount)
4155 hammer2_blockref_t *bref;
4156 hammer2_chain_t *chain;
4157 hammer2_key_t key_beg;
4158 hammer2_key_t key_end;
4159 hammer2_key_t key_next;
4160 hammer2_key_t key;
4161 int nkeybits;
4162 int locount;
4163 int hicount;
4164 int maxloops = 300000;
4167 * Shortcut if the parent is the inode. In this situation the
4168 * parent has 4+1 directory entries and we are creating an indirect
4169 * block capable of holding many more.
4171 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4172 return 63;
4175 key = *keyp;
4176 locount = 0;
4177 hicount = 0;
4180 * Calculate the range of keys in the array being careful to skip
4181 * slots which are overridden with a deletion.
4183 key_beg = 0;
4184 key_end = HAMMER2_KEY_MAX;
4185 hammer2_spin_ex(&parent->core.spin);
4187 for (;;) {
4188 if (--maxloops == 0) {
4189 panic("indkey_freemap shit %p %p:%d\n",
4190 parent, base, count);
4192 chain = hammer2_combined_find(parent, base, count,
4193 &key_next,
4194 key_beg, key_end,
4195 &bref);
4198 * Exhausted search
4200 if (bref == NULL)
4201 break;
4204 * Deleted object
4206 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4207 if (key_next == 0 || key_next > key_end)
4208 break;
4209 key_beg = key_next;
4210 continue;
4214 * Use the full live (not deleted) element for the scan
4215 * iteration. HAMMER2 does not allow partial replacements.
4217 * XXX should be built into hammer2_combined_find().
4219 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4222 * Expand our calculated key range (key, keybits) to fit
4223 * the scanned key. nkeybits represents the full range
4224 * that we will later cut in half (two halves @ nkeybits - 1).
4226 nkeybits = keybits;
4227 if (nkeybits < bref->keybits) {
4228 if (bref->keybits > 64) {
4229 kprintf("bad bref chain %p bref %p\n",
4230 chain, bref);
4231 Debugger("fubar");
4233 nkeybits = bref->keybits;
4235 while (nkeybits < 64 &&
4236 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4237 (key ^ bref->key)) != 0) {
4238 ++nkeybits;
4242 * If the new key range is larger we have to determine
4243 * which side of the new key range the existing keys fall
4244 * under by checking the high bit, then collapsing the
4245 * locount into the hicount or vise-versa.
4247 if (keybits != nkeybits) {
4248 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4249 hicount += locount;
4250 locount = 0;
4251 } else {
4252 locount += hicount;
4253 hicount = 0;
4255 keybits = nkeybits;
4259 * The newly scanned key will be in the lower half or the
4260 * upper half of the (new) key range.
4262 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4263 ++hicount;
4264 else
4265 ++locount;
4267 if (key_next == 0)
4268 break;
4269 key_beg = key_next;
4271 hammer2_spin_unex(&parent->core.spin);
4272 bref = NULL; /* now invalid (safety) */
4275 * Adjust keybits to represent half of the full range calculated
4276 * above (radix 63 max) for our new indirect block.
4278 --keybits;
4281 * Expand keybits to hold at least ncount elements. ncount will be
4282 * a power of 2. This is to try to completely fill leaf nodes (at
4283 * least for keys which are not hashes).
4285 * We aren't counting 'in' or 'out', we are counting 'high side'
4286 * and 'low side' based on the bit at (1LL << keybits). We want
4287 * everything to be inside in these cases so shift it all to
4288 * the low or high side depending on the new high bit.
4290 while (((hammer2_key_t)1 << keybits) < ncount) {
4291 ++keybits;
4292 if (key & ((hammer2_key_t)1 << keybits)) {
4293 hicount += locount;
4294 locount = 0;
4295 } else {
4296 locount += hicount;
4297 hicount = 0;
4301 if (hicount > locount)
4302 key |= (hammer2_key_t)1 << keybits;
4303 else
4304 key &= ~(hammer2_key_t)1 << keybits;
4306 *keyp = key;
4308 return (keybits);
4311 #else
4314 * Directory indirect blocks.
4316 * Covers both the inode index (directory of inodes), and directory contents
4317 * (filenames hardlinked to inodes).
4319 * Because directory keys are hashed we generally try to cut the space in
4320 * half. We accomodate the inode index (which tends to have linearly
4321 * increasing inode numbers) by ensuring that the keyspace is at least large
4322 * enough to fill up the indirect block being created.
4324 static int
4325 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4326 int keybits, hammer2_blockref_t *base, int count,
4327 int ncount)
4329 hammer2_blockref_t *bref;
4330 hammer2_chain_t *chain;
4331 hammer2_key_t key_beg;
4332 hammer2_key_t key_end;
4333 hammer2_key_t key_next;
4334 hammer2_key_t key;
4335 int nkeybits;
4336 int locount;
4337 int hicount;
4338 int maxloops = 300000;
4341 * Shortcut if the parent is the inode. In this situation the
4342 * parent has 4+1 directory entries and we are creating an indirect
4343 * block capable of holding many more.
4345 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4346 return 63;
4349 key = *keyp;
4350 locount = 0;
4351 hicount = 0;
4354 * Calculate the range of keys in the array being careful to skip
4355 * slots which are overridden with a deletion.
4357 key_beg = 0;
4358 key_end = HAMMER2_KEY_MAX;
4359 hammer2_spin_ex(&parent->core.spin);
4361 for (;;) {
4362 if (--maxloops == 0) {
4363 panic("indkey_freemap shit %p %p:%d\n",
4364 parent, base, count);
4366 chain = hammer2_combined_find(parent, base, count,
4367 &key_next,
4368 key_beg, key_end,
4369 &bref);
4372 * Exhausted search
4374 if (bref == NULL)
4375 break;
4378 * Deleted object
4380 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4381 if (key_next == 0 || key_next > key_end)
4382 break;
4383 key_beg = key_next;
4384 continue;
4388 * Use the full live (not deleted) element for the scan
4389 * iteration. HAMMER2 does not allow partial replacements.
4391 * XXX should be built into hammer2_combined_find().
4393 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4396 * Expand our calculated key range (key, keybits) to fit
4397 * the scanned key. nkeybits represents the full range
4398 * that we will later cut in half (two halves @ nkeybits - 1).
4400 nkeybits = keybits;
4401 if (nkeybits < bref->keybits) {
4402 if (bref->keybits > 64) {
4403 kprintf("bad bref chain %p bref %p\n",
4404 chain, bref);
4405 Debugger("fubar");
4407 nkeybits = bref->keybits;
4409 while (nkeybits < 64 &&
4410 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4411 (key ^ bref->key)) != 0) {
4412 ++nkeybits;
4416 * If the new key range is larger we have to determine
4417 * which side of the new key range the existing keys fall
4418 * under by checking the high bit, then collapsing the
4419 * locount into the hicount or vise-versa.
4421 if (keybits != nkeybits) {
4422 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4423 hicount += locount;
4424 locount = 0;
4425 } else {
4426 locount += hicount;
4427 hicount = 0;
4429 keybits = nkeybits;
4433 * The newly scanned key will be in the lower half or the
4434 * upper half of the (new) key range.
4436 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4437 ++hicount;
4438 else
4439 ++locount;
4441 if (key_next == 0)
4442 break;
4443 key_beg = key_next;
4445 hammer2_spin_unex(&parent->core.spin);
4446 bref = NULL; /* now invalid (safety) */
4449 * Adjust keybits to represent half of the full range calculated
4450 * above (radix 63 max) for our new indirect block.
4452 --keybits;
4455 * Expand keybits to hold at least ncount elements. ncount will be
4456 * a power of 2. This is to try to completely fill leaf nodes (at
4457 * least for keys which are not hashes).
4459 * We aren't counting 'in' or 'out', we are counting 'high side'
4460 * and 'low side' based on the bit at (1LL << keybits). We want
4461 * everything to be inside in these cases so shift it all to
4462 * the low or high side depending on the new high bit.
4464 while (((hammer2_key_t)1 << keybits) < ncount) {
4465 ++keybits;
4466 if (key & ((hammer2_key_t)1 << keybits)) {
4467 hicount += locount;
4468 locount = 0;
4469 } else {
4470 locount += hicount;
4471 hicount = 0;
4475 if (hicount > locount)
4476 key |= (hammer2_key_t)1 << keybits;
4477 else
4478 key &= ~(hammer2_key_t)1 << keybits;
4480 *keyp = key;
4482 return (keybits);
4485 #endif
4488 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4489 * it exists.
4491 * Both parent and chain must be locked exclusively.
4493 * This function will modify the parent if the blockref requires removal
4494 * from the parent's block table.
4496 * This function is NOT recursive. Any entity already pushed into the
4497 * chain (such as an inode) may still need visibility into its contents,
4498 * as well as the ability to read and modify the contents. For example,
4499 * for an unlinked file which is still open.
4501 * Also note that the flusher is responsible for cleaning up empty
4502 * indirect blocks.
4504 void
4505 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4506 hammer2_tid_t mtid, int flags)
4508 KKASSERT(hammer2_mtx_owned(&chain->lock));
4511 * Nothing to do if already marked.
4513 * We need the spinlock on the core whos RBTREE contains chain
4514 * to protect against races.
4516 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4517 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4518 chain->parent == parent);
4519 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4523 * Permanent deletions mark the chain as destroyed.
4525 if (flags & HAMMER2_DELETE_PERMANENT)
4526 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4527 hammer2_chain_setflush(chain);
4531 * Returns the index of the nearest element in the blockref array >= elm.
4532 * Returns (count) if no element could be found.
4534 * Sets *key_nextp to the next key for loop purposes but does not modify
4535 * it if the next key would be higher than the current value of *key_nextp.
4536 * Note that *key_nexp can overflow to 0, which should be tested by the
4537 * caller.
4539 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4540 * held through the operation.
4542 static int
4543 hammer2_base_find(hammer2_chain_t *parent,
4544 hammer2_blockref_t *base, int count,
4545 hammer2_key_t *key_nextp,
4546 hammer2_key_t key_beg, hammer2_key_t key_end)
4548 hammer2_blockref_t *scan;
4549 hammer2_key_t scan_end;
4550 int i;
4551 int limit;
4554 * Require the live chain's already have their core's counted
4555 * so we can optimize operations.
4557 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4560 * Degenerate case
4562 if (count == 0 || base == NULL)
4563 return(count);
4566 * Sequential optimization using parent->cache_index. This is
4567 * the most likely scenario.
4569 * We can avoid trailing empty entries on live chains, otherwise
4570 * we might have to check the whole block array.
4572 i = parent->cache_index; /* SMP RACE OK */
4573 cpu_ccfence();
4574 limit = parent->core.live_zero;
4575 if (i >= limit)
4576 i = limit - 1;
4577 if (i < 0)
4578 i = 0;
4579 KKASSERT(i < count);
4582 * Search backwards
4584 scan = &base[i];
4585 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4586 --scan;
4587 --i;
4589 parent->cache_index = i;
4592 * Search forwards, stop when we find a scan element which
4593 * encloses the key or until we know that there are no further
4594 * elements.
4596 while (i < count) {
4597 if (scan->type != 0) {
4598 scan_end = scan->key +
4599 ((hammer2_key_t)1 << scan->keybits) - 1;
4600 if (scan->key > key_beg || scan_end >= key_beg)
4601 break;
4603 if (i >= limit)
4604 return (count);
4605 ++scan;
4606 ++i;
4608 if (i != count) {
4609 parent->cache_index = i;
4610 if (i >= limit) {
4611 i = count;
4612 } else {
4613 scan_end = scan->key +
4614 ((hammer2_key_t)1 << scan->keybits);
4615 if (scan_end && (*key_nextp > scan_end ||
4616 *key_nextp == 0)) {
4617 *key_nextp = scan_end;
4621 return (i);
4625 * Do a combined search and return the next match either from the blockref
4626 * array or from the in-memory chain. Sets *bresp to the returned bref in
4627 * both cases, or sets it to NULL if the search exhausted. Only returns
4628 * a non-NULL chain if the search matched from the in-memory chain.
4630 * When no in-memory chain has been found and a non-NULL bref is returned
4631 * in *bresp.
4634 * The returned chain is not locked or referenced. Use the returned bref
4635 * to determine if the search exhausted or not. Iterate if the base find
4636 * is chosen but matches a deleted chain.
4638 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4639 * held through the operation.
4641 static hammer2_chain_t *
4642 hammer2_combined_find(hammer2_chain_t *parent,
4643 hammer2_blockref_t *base, int count,
4644 hammer2_key_t *key_nextp,
4645 hammer2_key_t key_beg, hammer2_key_t key_end,
4646 hammer2_blockref_t **bresp)
4648 hammer2_blockref_t *bref;
4649 hammer2_chain_t *chain;
4650 int i;
4653 * Lookup in block array and in rbtree.
4655 *key_nextp = key_end + 1;
4656 i = hammer2_base_find(parent, base, count, key_nextp,
4657 key_beg, key_end);
4658 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4661 * Neither matched
4663 if (i == count && chain == NULL) {
4664 *bresp = NULL;
4665 return(NULL);
4669 * Only chain matched.
4671 if (i == count) {
4672 bref = &chain->bref;
4673 goto found;
4677 * Only blockref matched.
4679 if (chain == NULL) {
4680 bref = &base[i];
4681 goto found;
4685 * Both in-memory and blockref matched, select the nearer element.
4687 * If both are flush with the left-hand side or both are the
4688 * same distance away, select the chain. In this situation the
4689 * chain must have been loaded from the matching blockmap.
4691 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4692 chain->bref.key == base[i].key) {
4693 KKASSERT(chain->bref.key == base[i].key);
4694 bref = &chain->bref;
4695 goto found;
4699 * Select the nearer key
4701 if (chain->bref.key < base[i].key) {
4702 bref = &chain->bref;
4703 } else {
4704 bref = &base[i];
4705 chain = NULL;
4709 * If the bref is out of bounds we've exhausted our search.
4711 found:
4712 if (bref->key > key_end) {
4713 *bresp = NULL;
4714 chain = NULL;
4715 } else {
4716 *bresp = bref;
4718 return(chain);
4722 * Locate the specified block array element and delete it. The element
4723 * must exist.
4725 * The spin lock on the related chain must be held.
4727 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4728 * need to be adjusted when we commit the media change.
4730 void
4731 hammer2_base_delete(hammer2_chain_t *parent,
4732 hammer2_blockref_t *base, int count,
4733 hammer2_chain_t *chain)
4735 hammer2_blockref_t *elm = &chain->bref;
4736 hammer2_blockref_t *scan;
4737 hammer2_key_t key_next;
4738 int i;
4741 * Delete element. Expect the element to exist.
4743 * XXX see caller, flush code not yet sophisticated enough to prevent
4744 * re-flushed in some cases.
4746 key_next = 0; /* max range */
4747 i = hammer2_base_find(parent, base, count, &key_next,
4748 elm->key, elm->key);
4749 scan = &base[i];
4750 if (i == count || scan->type == 0 ||
4751 scan->key != elm->key ||
4752 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4753 scan->keybits != elm->keybits)) {
4754 hammer2_spin_unex(&parent->core.spin);
4755 panic("delete base %p element not found at %d/%d elm %p\n",
4756 base, i, count, elm);
4757 return;
4761 * Update stats and zero the entry.
4763 * NOTE: Handle radix == 0 (0 bytes) case.
4765 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4766 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4767 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4769 switch(scan->type) {
4770 case HAMMER2_BREF_TYPE_INODE:
4771 parent->bref.embed.stats.inode_count -= 1;
4772 /* fall through */
4773 case HAMMER2_BREF_TYPE_DATA:
4774 case HAMMER2_BREF_TYPE_INDIRECT:
4775 parent->bref.embed.stats.data_count -=
4776 scan->embed.stats.data_count;
4777 parent->bref.embed.stats.inode_count -=
4778 scan->embed.stats.inode_count;
4779 break;
4780 default:
4781 break;
4784 bzero(scan, sizeof(*scan));
4787 * We can only optimize parent->core.live_zero for live chains.
4789 if (parent->core.live_zero == i + 1) {
4790 while (--i >= 0 && base[i].type == 0)
4792 parent->core.live_zero = i + 1;
4796 * Clear appropriate blockmap flags in chain.
4798 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4799 HAMMER2_CHAIN_BMAPUPD);
4803 * Insert the specified element. The block array must not already have the
4804 * element and must have space available for the insertion.
4806 * The spin lock on the related chain must be held.
4808 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4809 * need to be adjusted when we commit the media change.
4811 void
4812 hammer2_base_insert(hammer2_chain_t *parent,
4813 hammer2_blockref_t *base, int count,
4814 hammer2_chain_t *chain)
4816 hammer2_blockref_t *elm = &chain->bref;
4817 hammer2_key_t key_next;
4818 hammer2_key_t xkey;
4819 int i;
4820 int j;
4821 int k;
4822 int l;
4823 int u = 1;
4826 * Insert new element. Expect the element to not already exist
4827 * unless we are replacing it.
4829 * XXX see caller, flush code not yet sophisticated enough to prevent
4830 * re-flushed in some cases.
4832 key_next = 0; /* max range */
4833 i = hammer2_base_find(parent, base, count, &key_next,
4834 elm->key, elm->key);
4837 * Shortcut fill optimization, typical ordered insertion(s) may not
4838 * require a search.
4840 KKASSERT(i >= 0 && i <= count);
4843 * Set appropriate blockmap flags in chain.
4845 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4848 * Update stats and zero the entry
4850 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4851 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4852 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4854 switch(elm->type) {
4855 case HAMMER2_BREF_TYPE_INODE:
4856 parent->bref.embed.stats.inode_count += 1;
4857 /* fall through */
4858 case HAMMER2_BREF_TYPE_DATA:
4859 case HAMMER2_BREF_TYPE_INDIRECT:
4860 parent->bref.embed.stats.data_count +=
4861 elm->embed.stats.data_count;
4862 parent->bref.embed.stats.inode_count +=
4863 elm->embed.stats.inode_count;
4864 break;
4865 default:
4866 break;
4871 * We can only optimize parent->core.live_zero for live chains.
4873 if (i == count && parent->core.live_zero < count) {
4874 i = parent->core.live_zero++;
4875 base[i] = *elm;
4876 return;
4879 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4880 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4881 hammer2_spin_unex(&parent->core.spin);
4882 panic("insert base %p overlapping elements at %d elm %p\n",
4883 base, i, elm);
4887 * Try to find an empty slot before or after.
4889 j = i;
4890 k = i;
4891 while (j > 0 || k < count) {
4892 --j;
4893 if (j >= 0 && base[j].type == 0) {
4894 if (j == i - 1) {
4895 base[j] = *elm;
4896 } else {
4897 bcopy(&base[j+1], &base[j],
4898 (i - j - 1) * sizeof(*base));
4899 base[i - 1] = *elm;
4901 goto validate;
4903 ++k;
4904 if (k < count && base[k].type == 0) {
4905 bcopy(&base[i], &base[i+1],
4906 (k - i) * sizeof(hammer2_blockref_t));
4907 base[i] = *elm;
4910 * We can only update parent->core.live_zero for live
4911 * chains.
4913 if (parent->core.live_zero <= k)
4914 parent->core.live_zero = k + 1;
4915 u = 2;
4916 goto validate;
4919 panic("hammer2_base_insert: no room!");
4922 * Debugging
4924 validate:
4925 key_next = 0;
4926 for (l = 0; l < count; ++l) {
4927 if (base[l].type) {
4928 key_next = base[l].key +
4929 ((hammer2_key_t)1 << base[l].keybits) - 1;
4930 break;
4933 while (++l < count) {
4934 if (base[l].type) {
4935 if (base[l].key <= key_next)
4936 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4937 key_next = base[l].key +
4938 ((hammer2_key_t)1 << base[l].keybits) - 1;
4945 #if 0
4948 * Sort the blockref array for the chain. Used by the flush code to
4949 * sort the blockref[] array.
4951 * The chain must be exclusively locked AND spin-locked.
4953 typedef hammer2_blockref_t *hammer2_blockref_p;
4955 static
4957 hammer2_base_sort_callback(const void *v1, const void *v2)
4959 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4960 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4963 * Make sure empty elements are placed at the end of the array
4965 if (bref1->type == 0) {
4966 if (bref2->type == 0)
4967 return(0);
4968 return(1);
4969 } else if (bref2->type == 0) {
4970 return(-1);
4974 * Sort by key
4976 if (bref1->key < bref2->key)
4977 return(-1);
4978 if (bref1->key > bref2->key)
4979 return(1);
4980 return(0);
4983 void
4984 hammer2_base_sort(hammer2_chain_t *chain)
4986 hammer2_blockref_t *base;
4987 int count;
4989 switch(chain->bref.type) {
4990 case HAMMER2_BREF_TYPE_INODE:
4992 * Special shortcut for embedded data returns the inode
4993 * itself. Callers must detect this condition and access
4994 * the embedded data (the strategy code does this for us).
4996 * This is only applicable to regular files and softlinks.
4998 if (chain->data->ipdata.meta.op_flags &
4999 HAMMER2_OPFLAG_DIRECTDATA) {
5000 return;
5002 base = &chain->data->ipdata.u.blockset.blockref[0];
5003 count = HAMMER2_SET_COUNT;
5004 break;
5005 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5006 case HAMMER2_BREF_TYPE_INDIRECT:
5008 * Optimize indirect blocks in the INITIAL state to avoid
5009 * I/O.
5011 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5012 base = &chain->data->npdata[0];
5013 count = chain->bytes / sizeof(hammer2_blockref_t);
5014 break;
5015 case HAMMER2_BREF_TYPE_VOLUME:
5016 base = &chain->data->voldata.sroot_blockset.blockref[0];
5017 count = HAMMER2_SET_COUNT;
5018 break;
5019 case HAMMER2_BREF_TYPE_FREEMAP:
5020 base = &chain->data->blkset.blockref[0];
5021 count = HAMMER2_SET_COUNT;
5022 break;
5023 default:
5024 kprintf("hammer2_chain_lookup: unrecognized "
5025 "blockref(A) type: %d",
5026 chain->bref.type);
5027 while (1)
5028 tsleep(&base, 0, "dead", 0);
5029 panic("hammer2_chain_lookup: unrecognized "
5030 "blockref(A) type: %d",
5031 chain->bref.type);
5032 base = NULL; /* safety */
5033 count = 0; /* safety */
5035 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5038 #endif
5041 * Chain memory management
5043 void
5044 hammer2_chain_wait(hammer2_chain_t *chain)
5046 tsleep(chain, 0, "chnflw", 1);
5049 const hammer2_media_data_t *
5050 hammer2_chain_rdata(hammer2_chain_t *chain)
5052 KKASSERT(chain->data != NULL);
5053 return (chain->data);
5056 hammer2_media_data_t *
5057 hammer2_chain_wdata(hammer2_chain_t *chain)
5059 KKASSERT(chain->data != NULL);
5060 return (chain->data);
5064 * Set the check data for a chain. This can be a heavy-weight operation
5065 * and typically only runs on-flush. For file data check data is calculated
5066 * when the logical buffers are flushed.
5068 void
5069 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5071 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5073 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5074 case HAMMER2_CHECK_NONE:
5075 break;
5076 case HAMMER2_CHECK_DISABLED:
5077 break;
5078 case HAMMER2_CHECK_ISCSI32:
5079 chain->bref.check.iscsi32.value =
5080 hammer2_icrc32(bdata, chain->bytes);
5081 break;
5082 case HAMMER2_CHECK_XXHASH64:
5083 chain->bref.check.xxhash64.value =
5084 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5085 break;
5086 case HAMMER2_CHECK_SHA192:
5088 SHA256_CTX hash_ctx;
5089 union {
5090 uint8_t digest[SHA256_DIGEST_LENGTH];
5091 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5092 } u;
5094 SHA256_Init(&hash_ctx);
5095 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5096 SHA256_Final(u.digest, &hash_ctx);
5097 u.digest64[2] ^= u.digest64[3];
5098 bcopy(u.digest,
5099 chain->bref.check.sha192.data,
5100 sizeof(chain->bref.check.sha192.data));
5102 break;
5103 case HAMMER2_CHECK_FREEMAP:
5104 chain->bref.check.freemap.icrc32 =
5105 hammer2_icrc32(bdata, chain->bytes);
5106 break;
5107 default:
5108 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5109 chain->bref.methods);
5110 break;
5115 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5117 uint32_t check32;
5118 uint64_t check64;
5119 int r;
5121 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5122 return 1;
5124 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5125 case HAMMER2_CHECK_NONE:
5126 r = 1;
5127 break;
5128 case HAMMER2_CHECK_DISABLED:
5129 r = 1;
5130 break;
5131 case HAMMER2_CHECK_ISCSI32:
5132 check32 = hammer2_icrc32(bdata, chain->bytes);
5133 r = (chain->bref.check.iscsi32.value == check32);
5134 if (r == 0) {
5135 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5136 "(flags=%08x, bref/data %08x/%08x)\n",
5137 chain->bref.data_off,
5138 chain->bref.type,
5139 chain->bref.methods,
5140 chain->flags,
5141 chain->bref.check.iscsi32.value,
5142 check32);
5144 hammer2_check_icrc32 += chain->bytes;
5145 break;
5146 case HAMMER2_CHECK_XXHASH64:
5147 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5148 r = (chain->bref.check.xxhash64.value == check64);
5149 if (r == 0) {
5150 kprintf("chain %016jx.%02x key=%016jx "
5151 "meth=%02x CHECK FAIL "
5152 "(flags=%08x, bref/data %016jx/%016jx)\n",
5153 chain->bref.data_off,
5154 chain->bref.type,
5155 chain->bref.key,
5156 chain->bref.methods,
5157 chain->flags,
5158 chain->bref.check.xxhash64.value,
5159 check64);
5161 hammer2_check_xxhash64 += chain->bytes;
5162 break;
5163 case HAMMER2_CHECK_SHA192:
5165 SHA256_CTX hash_ctx;
5166 union {
5167 uint8_t digest[SHA256_DIGEST_LENGTH];
5168 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5169 } u;
5171 SHA256_Init(&hash_ctx);
5172 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5173 SHA256_Final(u.digest, &hash_ctx);
5174 u.digest64[2] ^= u.digest64[3];
5175 if (bcmp(u.digest,
5176 chain->bref.check.sha192.data,
5177 sizeof(chain->bref.check.sha192.data)) == 0) {
5178 r = 1;
5179 } else {
5180 r = 0;
5181 kprintf("chain %016jx.%02x meth=%02x "
5182 "CHECK FAIL\n",
5183 chain->bref.data_off,
5184 chain->bref.type,
5185 chain->bref.methods);
5188 break;
5189 case HAMMER2_CHECK_FREEMAP:
5190 r = (chain->bref.check.freemap.icrc32 ==
5191 hammer2_icrc32(bdata, chain->bytes));
5192 if (r == 0) {
5193 kprintf("chain %016jx.%02x meth=%02x "
5194 "CHECK FAIL\n",
5195 chain->bref.data_off,
5196 chain->bref.type,
5197 chain->bref.methods);
5198 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5199 chain->bref.check.freemap.icrc32,
5200 hammer2_icrc32(bdata, chain->bytes),
5201 chain->bytes);
5202 if (chain->dio)
5203 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5204 chain->dio, chain->dio->bp->b_loffset,
5205 chain->dio->bp->b_bufsize, bdata,
5206 chain->dio->bp->b_data);
5209 break;
5210 default:
5211 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5212 chain->bref.methods);
5213 r = 1;
5214 break;
5216 return r;
5220 * Acquire the chain and parent representing the specified inode for the
5221 * device at the specified cluster index.
5223 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5225 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5226 * will be NULL. *parentp may still be set error or not, or NULL if the
5227 * parent itself could not be resolved.
5229 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5230 * *parentp and *chainp will be unlocked if not NULL.
5233 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5234 int clindex, int flags,
5235 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5237 hammer2_chain_t *parent;
5238 hammer2_chain_t *rchain;
5239 hammer2_key_t key_dummy;
5240 int resolve_flags;
5241 int error;
5243 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5244 HAMMER2_RESOLVE_SHARED : 0;
5247 * Caller expects us to replace these.
5249 if (*chainp) {
5250 hammer2_chain_unlock(*chainp);
5251 hammer2_chain_drop(*chainp);
5252 *chainp = NULL;
5254 if (*parentp) {
5255 hammer2_chain_unlock(*parentp);
5256 hammer2_chain_drop(*parentp);
5257 *parentp = NULL;
5261 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5262 * inodes from root directory entries in the key lookup).
5264 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5265 rchain = NULL;
5266 if (parent) {
5267 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5268 inum, inum,
5269 &error, flags);
5270 } else {
5271 error = HAMMER2_ERROR_IO;
5273 *parentp = parent;
5274 *chainp = rchain;
5276 return error;
5280 * Used by the bulkscan code to snapshot the synchronized storage for
5281 * a volume, allowing it to be scanned concurrently against normal
5282 * operation.
5284 hammer2_chain_t *
5285 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5287 hammer2_chain_t *copy;
5289 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5290 copy->data = kmalloc(sizeof(copy->data->voldata),
5291 hmp->mchain,
5292 M_WAITOK | M_ZERO);
5293 hammer2_voldata_lock(hmp);
5294 copy->data->voldata = hmp->volsync;
5295 hammer2_voldata_unlock(hmp);
5297 return copy;
5300 void
5301 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5303 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5304 KKASSERT(copy->data);
5305 kfree(copy->data, copy->hmp->mchain);
5306 copy->data = NULL;
5307 atomic_add_long(&hammer2_chain_allocs, -1);
5308 hammer2_chain_drop(copy);
5312 * Create a snapshot of the specified (chain) with the specified label.
5313 * The originating hammer2_inode must be exclusively locked for
5314 * safety. The device's bulklk should be held by the caller. The caller
5315 * is responsible for synchronizing the filesystem to storage before
5316 * taking the snapshot.
5319 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5320 hammer2_tid_t mtid)
5322 hammer2_dev_t *hmp;
5323 const hammer2_inode_data_t *ripdata;
5324 hammer2_inode_data_t *wipdata;
5325 hammer2_chain_t *nchain;
5326 hammer2_inode_t *nip;
5327 size_t name_len;
5328 hammer2_key_t lhc;
5329 struct vattr vat;
5330 #if 0
5331 uuid_t opfs_clid;
5332 #endif
5333 int error;
5335 kprintf("snapshot %s\n", pmp->name);
5337 name_len = strlen(pmp->name);
5338 lhc = hammer2_dirhash(pmp->name, name_len);
5341 * Get the clid
5343 ripdata = &chain->data->ipdata;
5344 #if 0
5345 opfs_clid = ripdata->meta.pfs_clid;
5346 #endif
5347 hmp = chain->hmp;
5350 * Create the snapshot directory under the super-root
5352 * Set PFS type, generate a unique filesystem id, and generate
5353 * a cluster id. Use the same clid when snapshotting a PFS root,
5354 * which theoretically allows the snapshot to be used as part of
5355 * the same cluster (perhaps as a cache).
5357 * Copy the (flushed) blockref array. Theoretically we could use
5358 * chain_duplicate() but it becomes difficult to disentangle
5359 * the shared core so for now just brute-force it.
5361 VATTR_NULL(&vat);
5362 vat.va_type = VDIR;
5363 vat.va_mode = 0755;
5364 hammer2_chain_unlock(chain);
5365 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5366 &vat, proc0.p_ucred,
5367 pmp->name, name_len, 0,
5368 1, 0, 0,
5369 HAMMER2_INSERT_PFSROOT, &error);
5370 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5372 if (nip) {
5373 hammer2_inode_modify(nip);
5374 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5375 hammer2_chain_modify(nchain, mtid, 0, 0);
5376 wipdata = &nchain->data->ipdata;
5378 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5379 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5380 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5381 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5384 * Give the snapshot its own private cluster id. As a
5385 * snapshot no further synchronization with the original
5386 * cluster will be done.
5388 #if 0
5389 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5390 nip->meta.pfs_clid = opfs_clid;
5391 else
5392 kern_uuidgen(&nip->meta.pfs_clid, 1);
5393 #endif
5394 kern_uuidgen(&nip->meta.pfs_clid, 1);
5395 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5397 /* XXX hack blockset copy */
5398 /* XXX doesn't work with real cluster */
5399 wipdata->meta = nip->meta;
5400 wipdata->u.blockset = ripdata->u.blockset;
5402 hammer2_flush(nchain, 1);
5403 KKASSERT(wipdata == &nchain->data->ipdata);
5404 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5406 hammer2_chain_unlock(nchain);
5407 hammer2_chain_drop(nchain);
5408 hammer2_inode_chain_sync(nip);
5409 hammer2_inode_unlock(nip);
5410 hammer2_inode_run_sideq(hmp->spmp);
5412 return (error);
5416 * Returns non-zero if the chain (INODE or DIRENT) matches the
5417 * filename.
5420 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5421 size_t name_len)
5423 const hammer2_inode_data_t *ripdata;
5424 const hammer2_dirent_head_t *den;
5426 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5427 ripdata = &chain->data->ipdata;
5428 if (ripdata->meta.name_len == name_len &&
5429 bcmp(ripdata->filename, name, name_len) == 0) {
5430 return 1;
5433 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5434 chain->bref.embed.dirent.namlen == name_len) {
5435 den = &chain->bref.embed.dirent;
5436 if (name_len > sizeof(chain->bref.check.buf) &&
5437 bcmp(chain->data->buf, name, name_len) == 0) {
5438 return 1;
5440 if (name_len <= sizeof(chain->bref.check.buf) &&
5441 bcmp(chain->bref.check.buf, name, name_len) == 0) {
5442 return 1;
5445 return 0;