hammer2 - error handling 1/N (chain_scan)
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
blobaef1c247673a8a0093387b2bfdadbb83064025af
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 int *cache_indexp, 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.
2039 * To handle insertion races pass the INSERT_RACE flag along with the
2040 * generation number of the core. NULL will be returned if the generation
2041 * number changes before we have a chance to insert the chain. Insert
2042 * races can occur because the parent might be held shared.
2044 * Caller must hold the parent locked shared or exclusive since we may
2045 * need the parent's bref array to find our block.
2047 * WARNING! chain->pmp is always set to NULL for any chain representing
2048 * part of the super-root topology.
2050 hammer2_chain_t *
2051 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2052 hammer2_blockref_t *bref)
2054 hammer2_dev_t *hmp = parent->hmp;
2055 hammer2_chain_t *chain;
2056 int error;
2059 * Allocate a chain structure representing the existing media
2060 * entry. Resulting chain has one ref and is not locked.
2062 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2063 chain = hammer2_chain_alloc(hmp, NULL, bref);
2064 else
2065 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2066 /* ref'd chain returned */
2069 * Flag that the chain is in the parent's blockmap so delete/flush
2070 * knows what to do with it.
2072 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2075 * Link the chain into its parent. A spinlock is required to safely
2076 * access the RBTREE, and it is possible to collide with another
2077 * hammer2_chain_get() operation because the caller might only hold
2078 * a shared lock on the parent.
2080 * NOTE: Get races can occur quite often when we distribute
2081 * asynchronous read-aheads across multiple threads.
2083 KKASSERT(parent->refs > 0);
2084 error = hammer2_chain_insert(parent, chain,
2085 HAMMER2_CHAIN_INSERT_SPIN |
2086 HAMMER2_CHAIN_INSERT_RACE,
2087 generation);
2088 if (error) {
2089 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2090 /*kprintf("chain %p get race\n", chain);*/
2091 hammer2_chain_drop(chain);
2092 chain = NULL;
2093 } else {
2094 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2098 * Return our new chain referenced but not locked, or NULL if
2099 * a race occurred.
2101 return (chain);
2105 * Lookup initialization/completion API
2107 hammer2_chain_t *
2108 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2110 hammer2_chain_ref(parent);
2111 if (flags & HAMMER2_LOOKUP_SHARED) {
2112 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2113 HAMMER2_RESOLVE_SHARED);
2114 } else {
2115 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2117 return (parent);
2120 void
2121 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2123 if (parent) {
2124 hammer2_chain_unlock(parent);
2125 hammer2_chain_drop(parent);
2130 * Take the locked chain and return a locked parent. The chain remains
2131 * locked on return.
2133 * This function handles the lock order reversal.
2135 hammer2_chain_t *
2136 hammer2_chain_getparent(hammer2_chain_t *chain, int how)
2138 hammer2_chain_t *parent;
2141 * Be careful of order, chain must be unlocked before parent
2142 * is locked below to avoid a deadlock.
2144 * Safe access to fu->parent requires fu's core spinlock.
2146 again:
2147 hammer2_spin_ex(&chain->core.spin);
2148 parent = chain->parent;
2149 if (parent == NULL) {
2150 hammer2_spin_unex(&chain->core.spin);
2151 panic("hammer2_chain_getparent: no parent");
2153 hammer2_chain_ref(parent);
2154 hammer2_spin_unex(&chain->core.spin);
2156 hammer2_chain_unlock(chain);
2157 hammer2_chain_lock(parent, how);
2158 hammer2_chain_lock(chain, how);
2161 * Parent relinking races are quite common. We have to get it right
2162 * or we will blow up the block table.
2164 if (chain->parent != parent) {
2165 hammer2_chain_unlock(parent);
2166 hammer2_chain_drop(parent);
2167 goto again;
2169 return parent;
2173 * Take the locked chain and return a locked parent. The chain is unlocked
2174 * and dropped. *chainp is set to the returned parent as a convenience.
2176 * This function handles the lock order reversal.
2178 hammer2_chain_t *
2179 hammer2_chain_repparent(hammer2_chain_t **chainp, int how)
2181 hammer2_chain_t *chain;
2182 hammer2_chain_t *parent;
2185 * Be careful of order, chain must be unlocked before parent
2186 * is locked below to avoid a deadlock.
2188 * Safe access to fu->parent requires fu's core spinlock.
2190 chain = *chainp;
2191 again:
2192 hammer2_spin_ex(&chain->core.spin);
2193 parent = chain->parent;
2194 if (parent == NULL) {
2195 hammer2_spin_unex(&chain->core.spin);
2196 panic("hammer2_chain_getparent: no parent");
2198 hammer2_chain_ref(parent);
2199 hammer2_spin_unex(&chain->core.spin);
2201 hammer2_chain_unlock(chain);
2202 hammer2_chain_lock(parent, how);
2205 * Parent relinking races are quite common. We have to get it right
2206 * or we will blow up the block table.
2208 if (chain->parent != parent) {
2209 hammer2_chain_lock(chain, how);
2210 hammer2_chain_unlock(parent);
2211 hammer2_chain_drop(parent);
2212 goto again;
2214 hammer2_chain_drop(chain);
2215 *chainp = parent;
2217 return parent;
2221 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2222 * (*parentp) typically points to an inode but can also point to a related
2223 * indirect block and this function will recurse upwards and find the inode
2224 * again.
2226 * (*parentp) must be exclusively locked and referenced and can be an inode
2227 * or an existing indirect block within the inode.
2229 * On return (*parentp) will be modified to point at the deepest parent chain
2230 * element encountered during the search, as a helper for an insertion or
2231 * deletion. The new (*parentp) will be locked and referenced and the old
2232 * will be unlocked and dereferenced (no change if they are both the same).
2234 * The matching chain will be returned exclusively locked. If NOLOCK is
2235 * requested the chain will be returned only referenced. Note that the
2236 * parent chain must always be locked shared or exclusive, matching the
2237 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2238 * when NOLOCK is specified but that complicates matters if *parentp must
2239 * inherit the chain.
2241 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2242 * data pointer or can otherwise be in flux.
2244 * NULL is returned if no match was found, but (*parentp) will still
2245 * potentially be adjusted.
2247 * If a fatal error occurs (typically an I/O error), a dummy chain is
2248 * returned with chain->error and error-identifying information set. This
2249 * chain will assert if you try to do anything fancy with it.
2251 * XXX Depending on where the error occurs we should allow continued iteration.
2253 * On return (*key_nextp) will point to an iterative value for key_beg.
2254 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2256 * This function will also recurse up the chain if the key is not within the
2257 * current parent's range. (*parentp) can never be set to NULL. An iteration
2258 * can simply allow (*parentp) to float inside the loop.
2260 * NOTE! chain->data is not always resolved. By default it will not be
2261 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2262 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2263 * BREF_TYPE_DATA as the device buffer can alias the logical file
2264 * buffer).
2267 hammer2_chain_t *
2268 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2269 hammer2_key_t key_beg, hammer2_key_t key_end,
2270 int *cache_indexp, int flags)
2272 hammer2_dev_t *hmp;
2273 hammer2_chain_t *parent;
2274 hammer2_chain_t *chain;
2275 hammer2_blockref_t *base;
2276 hammer2_blockref_t *bref;
2277 hammer2_blockref_t bcopy;
2278 hammer2_key_t scan_beg;
2279 hammer2_key_t scan_end;
2280 int count = 0;
2281 int how_always = HAMMER2_RESOLVE_ALWAYS;
2282 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2283 int how;
2284 int generation;
2285 int maxloops = 300000;
2287 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2288 how_maybe = how_always;
2289 how = HAMMER2_RESOLVE_ALWAYS;
2290 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2291 how = HAMMER2_RESOLVE_NEVER;
2292 } else {
2293 how = HAMMER2_RESOLVE_MAYBE;
2295 if (flags & HAMMER2_LOOKUP_SHARED) {
2296 how_maybe |= HAMMER2_RESOLVE_SHARED;
2297 how_always |= HAMMER2_RESOLVE_SHARED;
2298 how |= HAMMER2_RESOLVE_SHARED;
2302 * Recurse (*parentp) upward if necessary until the parent completely
2303 * encloses the key range or we hit the inode.
2305 * Handle races against the flusher deleting indirect nodes on its
2306 * way back up by continuing to recurse upward past the deletion.
2308 parent = *parentp;
2309 hmp = parent->hmp;
2311 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2312 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2313 scan_beg = parent->bref.key;
2314 scan_end = scan_beg +
2315 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2316 if ((parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2317 if (key_beg >= scan_beg && key_end <= scan_end)
2318 break;
2320 parent = hammer2_chain_repparent(parentp, how_maybe);
2322 again:
2324 if (--maxloops == 0)
2325 panic("hammer2_chain_lookup: maxloops");
2327 * Locate the blockref array. Currently we do a fully associative
2328 * search through the array.
2330 switch(parent->bref.type) {
2331 case HAMMER2_BREF_TYPE_INODE:
2333 * Special shortcut for embedded data returns the inode
2334 * itself. Callers must detect this condition and access
2335 * the embedded data (the strategy code does this for us).
2337 * This is only applicable to regular files and softlinks.
2339 * We need a second lock on parent. Since we already have
2340 * a lock we must pass LOCKAGAIN to prevent unexpected
2341 * blocking (we don't want to block on a second shared
2342 * ref if an exclusive lock is pending)
2344 if (parent->data->ipdata.meta.op_flags &
2345 HAMMER2_OPFLAG_DIRECTDATA) {
2346 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2347 chain = NULL;
2348 *key_nextp = key_end + 1;
2349 goto done;
2351 hammer2_chain_ref(parent);
2352 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2353 hammer2_chain_lock(parent,
2354 how_always |
2355 HAMMER2_RESOLVE_LOCKAGAIN);
2356 *key_nextp = key_end + 1;
2357 return (parent);
2359 base = &parent->data->ipdata.u.blockset.blockref[0];
2360 count = HAMMER2_SET_COUNT;
2361 break;
2362 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2363 case HAMMER2_BREF_TYPE_INDIRECT:
2365 * Handle MATCHIND on the parent
2367 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2368 scan_beg = parent->bref.key;
2369 scan_end = scan_beg +
2370 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2371 if (key_beg == scan_beg && key_end == scan_end) {
2372 chain = parent;
2373 hammer2_chain_ref(chain);
2374 hammer2_chain_lock(chain, how_maybe);
2375 *key_nextp = scan_end + 1;
2376 goto done;
2381 * Optimize indirect blocks in the INITIAL state to avoid
2382 * I/O.
2384 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2385 base = NULL;
2386 } else {
2387 if (parent->data == NULL) {
2388 kprintf("parent->data is NULL %p\n", parent);
2389 while (1)
2390 tsleep(parent, 0, "xxx", 0);
2392 base = &parent->data->npdata[0];
2394 count = parent->bytes / sizeof(hammer2_blockref_t);
2395 break;
2396 case HAMMER2_BREF_TYPE_VOLUME:
2397 base = &parent->data->voldata.sroot_blockset.blockref[0];
2398 count = HAMMER2_SET_COUNT;
2399 break;
2400 case HAMMER2_BREF_TYPE_FREEMAP:
2401 base = &parent->data->blkset.blockref[0];
2402 count = HAMMER2_SET_COUNT;
2403 break;
2404 default:
2405 kprintf("hammer2_chain_lookup: unrecognized "
2406 "blockref(B) type: %d",
2407 parent->bref.type);
2408 while (1)
2409 tsleep(&base, 0, "dead", 0);
2410 panic("hammer2_chain_lookup: unrecognized "
2411 "blockref(B) type: %d",
2412 parent->bref.type);
2413 base = NULL; /* safety */
2414 count = 0; /* safety */
2418 * Merged scan to find next candidate.
2420 * hammer2_base_*() functions require the parent->core.live_* fields
2421 * to be synchronized.
2423 * We need to hold the spinlock to access the block array and RB tree
2424 * and to interlock chain creation.
2426 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2427 hammer2_chain_countbrefs(parent, base, count);
2430 * Combined search
2432 hammer2_spin_ex(&parent->core.spin);
2433 chain = hammer2_combined_find(parent, base, count,
2434 cache_indexp, key_nextp,
2435 key_beg, key_end,
2436 &bref);
2437 generation = parent->core.generation;
2440 * Exhausted parent chain, iterate.
2442 if (bref == NULL) {
2443 hammer2_spin_unex(&parent->core.spin);
2444 if (key_beg == key_end) /* short cut single-key case */
2445 return (NULL);
2448 * Stop if we reached the end of the iteration.
2450 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2451 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2452 return (NULL);
2456 * Calculate next key, stop if we reached the end of the
2457 * iteration, otherwise go up one level and loop.
2459 key_beg = parent->bref.key +
2460 ((hammer2_key_t)1 << parent->bref.keybits);
2461 if (key_beg == 0 || key_beg > key_end)
2462 return (NULL);
2463 parent = hammer2_chain_repparent(parentp, how_maybe);
2464 goto again;
2468 * Selected from blockref or in-memory chain.
2470 if (chain == NULL) {
2471 bcopy = *bref;
2472 hammer2_spin_unex(&parent->core.spin);
2473 chain = hammer2_chain_get(parent, generation,
2474 &bcopy);
2475 if (chain == NULL) {
2477 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2478 parent, key_beg, key_end);
2480 goto again;
2482 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2483 hammer2_chain_drop(chain);
2484 goto again;
2486 } else {
2487 hammer2_chain_ref(chain);
2488 hammer2_spin_unex(&parent->core.spin);
2492 * chain is referenced but not locked. We must lock the chain
2493 * to obtain definitive state.
2495 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2496 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2497 hammer2_chain_lock(chain, how_maybe);
2498 } else {
2499 hammer2_chain_lock(chain, how);
2501 KKASSERT(chain->parent == parent);
2504 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2506 * NOTE: Chain's key range is not relevant as there might be
2507 * one-offs within the range that are not deleted.
2509 * NOTE: Lookups can race delete-duplicate because
2510 * delete-duplicate does not lock the parent's core
2511 * (they just use the spinlock on the core).
2513 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2514 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2515 chain->bref.data_off, chain->bref.type,
2516 chain->bref.key);
2517 hammer2_chain_unlock(chain);
2518 hammer2_chain_drop(chain);
2519 key_beg = *key_nextp;
2520 if (key_beg == 0 || key_beg > key_end)
2521 return(NULL);
2522 goto again;
2526 * If the chain element is an indirect block it becomes the new
2527 * parent and we loop on it. We must maintain our top-down locks
2528 * to prevent the flusher from interfering (i.e. doing a
2529 * delete-duplicate and leaving us recursing down a deleted chain).
2531 * The parent always has to be locked with at least RESOLVE_MAYBE
2532 * so we can access its data. It might need a fixup if the caller
2533 * passed incompatible flags. Be careful not to cause a deadlock
2534 * as a data-load requires an exclusive lock.
2536 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2537 * range is within the requested key range we return the indirect
2538 * block and do NOT loop. This is usually only used to acquire
2539 * freemap nodes.
2541 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2542 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2543 hammer2_chain_unlock(parent);
2544 hammer2_chain_drop(parent);
2545 *parentp = parent = chain;
2546 goto again;
2548 done:
2550 * All done, return the chain.
2552 * If the caller does not want a locked chain, replace the lock with
2553 * a ref. Perhaps this can eventually be optimized to not obtain the
2554 * lock in the first place for situations where the data does not
2555 * need to be resolved.
2557 if (chain) {
2558 if (flags & HAMMER2_LOOKUP_NOLOCK)
2559 hammer2_chain_unlock(chain);
2561 return (chain);
2565 * After having issued a lookup we can iterate all matching keys.
2567 * If chain is non-NULL we continue the iteration from just after it's index.
2569 * If chain is NULL we assume the parent was exhausted and continue the
2570 * iteration at the next parent.
2572 * If a fatal error occurs (typically an I/O error), a dummy chain is
2573 * returned with chain->error and error-identifying information set. This
2574 * chain will assert if you try to do anything fancy with it.
2576 * XXX Depending on where the error occurs we should allow continued iteration.
2578 * parent must be locked on entry and remains locked throughout. chain's
2579 * lock status must match flags. Chain is always at least referenced.
2581 * WARNING! The MATCHIND flag does not apply to this function.
2583 hammer2_chain_t *
2584 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2585 hammer2_key_t *key_nextp,
2586 hammer2_key_t key_beg, hammer2_key_t key_end,
2587 int *cache_indexp, int flags)
2589 hammer2_chain_t *parent;
2590 int how_maybe;
2593 * Calculate locking flags for upward recursion.
2595 how_maybe = HAMMER2_RESOLVE_MAYBE;
2596 if (flags & HAMMER2_LOOKUP_SHARED)
2597 how_maybe |= HAMMER2_RESOLVE_SHARED;
2599 parent = *parentp;
2602 * Calculate the next index and recalculate the parent if necessary.
2604 if (chain) {
2605 key_beg = chain->bref.key +
2606 ((hammer2_key_t)1 << chain->bref.keybits);
2607 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2608 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2609 hammer2_chain_unlock(chain);
2611 hammer2_chain_drop(chain);
2614 * chain invalid past this point, but we can still do a
2615 * pointer comparison w/parent.
2617 * Any scan where the lookup returned degenerate data embedded
2618 * in the inode has an invalid index and must terminate.
2620 if (chain == parent)
2621 return(NULL);
2622 if (key_beg == 0 || key_beg > key_end)
2623 return(NULL);
2624 chain = NULL;
2625 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2626 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2628 * We reached the end of the iteration.
2630 return (NULL);
2631 } else {
2633 * Continue iteration with next parent unless the current
2634 * parent covers the range.
2636 * (This also handles the case of a deleted, empty indirect
2637 * node).
2639 key_beg = parent->bref.key +
2640 ((hammer2_key_t)1 << parent->bref.keybits);
2641 if (key_beg == 0 || key_beg > key_end)
2642 return (NULL);
2643 parent = hammer2_chain_repparent(parentp, how_maybe);
2647 * And execute
2649 return (hammer2_chain_lookup(parentp, key_nextp,
2650 key_beg, key_end,
2651 cache_indexp, flags));
2655 * Caller wishes to iterate chains under parent, loading new chains into
2656 * chainp. Caller must initialize *chainp to NULL and *firstp to 1, and
2657 * then call hammer2_chain_scan() repeatedly until a non-zero return.
2658 * During the scan, *firstp will be set to 0 and (*chainp) will be replaced
2659 * with the returned chain for the scan. The returned *chainp will be
2660 * locked and referenced. Any prior contents will be unlocked and dropped.
2662 * Caller should check the return value. A normal scan EOF will return
2663 * exactly HAMMER2_ERRORF_EOF. Any other non-zero value indicates an
2664 * error trying to access parent data. Any error in the returned chain
2665 * must be tested separately by the caller.
2667 * (*chainp) is dropped on each scan, but will only be set if the returned
2668 * element itself can recurse. Leaf elements are NOT resolved, loaded, or
2669 * returned via *chainp. The caller will get their bref only.
2671 * The raw scan function is similar to lookup/next but does not seek to a key.
2672 * Blockrefs are iterated via first_bref = (parent, NULL) and
2673 * next_chain = (parent, bref).
2675 * The passed-in parent must be locked and its data resolved. The function
2676 * nominally returns a locked and referenced *chainp != NULL for chains
2677 * the caller might need to recurse on (and will dipose of any *chainp passed
2678 * in). The caller must check the chain->bref.type either way.
2681 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2682 hammer2_blockref_t *bref, int *firstp,
2683 int *cache_indexp, int flags)
2685 hammer2_dev_t *hmp;
2686 hammer2_blockref_t *base;
2687 hammer2_blockref_t *bref_ptr;
2688 hammer2_key_t key;
2689 hammer2_key_t next_key;
2690 hammer2_chain_t *chain = NULL;
2691 int count = 0;
2692 int how_always = HAMMER2_RESOLVE_ALWAYS;
2693 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2694 int how;
2695 int generation;
2696 int maxloops = 300000;
2697 int error;
2699 hmp = parent->hmp;
2700 error = 0;
2703 * Scan flags borrowed from lookup.
2705 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2706 how_maybe = how_always;
2707 how = HAMMER2_RESOLVE_ALWAYS;
2708 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2709 how = HAMMER2_RESOLVE_NEVER;
2710 } else {
2711 how = HAMMER2_RESOLVE_MAYBE;
2713 if (flags & HAMMER2_LOOKUP_SHARED) {
2714 how_maybe |= HAMMER2_RESOLVE_SHARED;
2715 how_always |= HAMMER2_RESOLVE_SHARED;
2716 how |= HAMMER2_RESOLVE_SHARED;
2720 * Calculate key to locate first/next element, unlocking the previous
2721 * element as we go. Be careful, the key calculation can overflow.
2723 * (also reset bref to NULL)
2725 if (*firstp) {
2726 key = 0;
2727 *firstp = 0;
2728 } else {
2729 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2730 if ((chain = *chainp) != NULL) {
2731 *chainp = NULL;
2732 hammer2_chain_unlock(chain);
2733 hammer2_chain_drop(chain);
2734 chain = NULL;
2736 if (key == 0) {
2737 error |= HAMMER2_ERROR_EOF;
2738 goto done;
2742 again:
2743 if (parent->error) {
2744 error = parent->error;
2745 goto done;
2747 if (--maxloops == 0)
2748 panic("hammer2_chain_scan: maxloops");
2751 * Locate the blockref array. Currently we do a fully associative
2752 * search through the array.
2754 switch(parent->bref.type) {
2755 case HAMMER2_BREF_TYPE_INODE:
2757 * An inode with embedded data has no sub-chains.
2759 * WARNING! Bulk scan code may pass a static chain marked
2760 * as BREF_TYPE_INODE with a copy of the volume
2761 * root blockset to snapshot the volume.
2763 if (parent->data->ipdata.meta.op_flags &
2764 HAMMER2_OPFLAG_DIRECTDATA) {
2765 error |= HAMMER2_ERROR_EOF;
2766 goto done;
2768 base = &parent->data->ipdata.u.blockset.blockref[0];
2769 count = HAMMER2_SET_COUNT;
2770 break;
2771 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2772 case HAMMER2_BREF_TYPE_INDIRECT:
2774 * Optimize indirect blocks in the INITIAL state to avoid
2775 * I/O.
2777 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2778 base = NULL;
2779 } else {
2780 if (parent->data == NULL)
2781 panic("parent->data is NULL");
2782 base = &parent->data->npdata[0];
2784 count = parent->bytes / sizeof(hammer2_blockref_t);
2785 break;
2786 case HAMMER2_BREF_TYPE_VOLUME:
2787 base = &parent->data->voldata.sroot_blockset.blockref[0];
2788 count = HAMMER2_SET_COUNT;
2789 break;
2790 case HAMMER2_BREF_TYPE_FREEMAP:
2791 base = &parent->data->blkset.blockref[0];
2792 count = HAMMER2_SET_COUNT;
2793 break;
2794 default:
2795 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2796 parent->bref.type);
2797 base = NULL; /* safety */
2798 count = 0; /* safety */
2802 * Merged scan to find next candidate.
2804 * hammer2_base_*() functions require the parent->core.live_* fields
2805 * to be synchronized.
2807 * We need to hold the spinlock to access the block array and RB tree
2808 * and to interlock chain creation.
2810 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2811 hammer2_chain_countbrefs(parent, base, count);
2813 next_key = 0;
2814 bref_ptr = NULL;
2815 hammer2_spin_ex(&parent->core.spin);
2816 chain = hammer2_combined_find(parent, base, count,
2817 cache_indexp, &next_key,
2818 key, HAMMER2_KEY_MAX,
2819 &bref_ptr);
2820 generation = parent->core.generation;
2823 * Exhausted parent chain, we're done.
2825 if (bref_ptr == NULL) {
2826 hammer2_spin_unex(&parent->core.spin);
2827 KKASSERT(chain == NULL);
2828 error |= HAMMER2_ERROR_EOF;
2829 goto done;
2833 * Copy into the supplied stack-based blockref.
2835 *bref = *bref_ptr;
2838 * Selected from blockref or in-memory chain.
2840 if (chain == NULL) {
2841 switch(bref->type) {
2842 case HAMMER2_BREF_TYPE_INODE:
2843 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2844 case HAMMER2_BREF_TYPE_INDIRECT:
2845 case HAMMER2_BREF_TYPE_VOLUME:
2846 case HAMMER2_BREF_TYPE_FREEMAP:
2848 * Recursion, always get the chain
2850 hammer2_spin_unex(&parent->core.spin);
2851 chain = hammer2_chain_get(parent, generation, bref);
2852 if (chain == NULL) {
2853 kprintf("retry scan parent %p keys %016jx\n",
2854 parent, key);
2855 goto again;
2857 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2858 hammer2_chain_drop(chain);
2859 chain = NULL;
2860 goto again;
2862 break;
2863 default:
2865 * No recursion, do not waste time instantiating
2866 * a chain, just iterate using the bref.
2868 hammer2_spin_unex(&parent->core.spin);
2869 break;
2871 } else {
2873 * Recursion or not we need the chain in order to supply
2874 * the bref.
2876 hammer2_chain_ref(chain);
2877 hammer2_spin_unex(&parent->core.spin);
2881 * chain is referenced but not locked. We must lock the chain
2882 * to obtain definitive state.
2884 if (chain)
2885 hammer2_chain_lock(chain, how);
2888 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2890 * NOTE: chain's key range is not relevant as there might be
2891 * one-offs within the range that are not deleted.
2893 * NOTE: XXX this could create problems with scans used in
2894 * situations other than mount-time recovery.
2896 * NOTE: Lookups can race delete-duplicate because
2897 * delete-duplicate does not lock the parent's core
2898 * (they just use the spinlock on the core).
2900 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2901 hammer2_chain_unlock(chain);
2902 hammer2_chain_drop(chain);
2903 chain = NULL;
2905 key = next_key;
2906 if (key == 0) {
2907 error |= HAMMER2_ERROR_EOF;
2908 goto done;
2910 goto again;
2913 done:
2915 * All done, return the bref or NULL, supply chain if necessary.
2917 if (chain)
2918 *chainp = chain;
2919 return (error);
2923 * Create and return a new hammer2 system memory structure of the specified
2924 * key, type and size and insert it under (*parentp). This is a full
2925 * insertion, based on the supplied key/keybits, and may involve creating
2926 * indirect blocks and moving other chains around via delete/duplicate.
2928 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2929 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2930 * FULL. This typically means that the caller is creating the chain after
2931 * doing a hammer2_chain_lookup().
2933 * (*parentp) must be exclusive locked and may be replaced on return
2934 * depending on how much work the function had to do.
2936 * (*parentp) must not be errored or this function will assert.
2938 * (*chainp) usually starts out NULL and returns the newly created chain,
2939 * but if the caller desires the caller may allocate a disconnected chain
2940 * and pass it in instead.
2942 * This function should NOT be used to insert INDIRECT blocks. It is
2943 * typically used to create/insert inodes and data blocks.
2945 * Caller must pass-in an exclusively locked parent the new chain is to
2946 * be inserted under, and optionally pass-in a disconnected, exclusively
2947 * locked chain to insert (else we create a new chain). The function will
2948 * adjust (*parentp) as necessary, create or connect the chain, and
2949 * return an exclusively locked chain in *chainp.
2951 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2952 * and will be reassigned.
2955 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2956 hammer2_pfs_t *pmp, int methods,
2957 hammer2_key_t key, int keybits, int type, size_t bytes,
2958 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2960 hammer2_dev_t *hmp;
2961 hammer2_chain_t *chain;
2962 hammer2_chain_t *parent;
2963 hammer2_blockref_t *base;
2964 hammer2_blockref_t dummy;
2965 int allocated = 0;
2966 int error = 0;
2967 int count;
2968 int maxloops = 300000;
2971 * Topology may be crossing a PFS boundary.
2973 parent = *parentp;
2974 KKASSERT(hammer2_mtx_owned(&parent->lock));
2975 KKASSERT(parent->error == 0);
2976 hmp = parent->hmp;
2977 chain = *chainp;
2979 if (chain == NULL) {
2981 * First allocate media space and construct the dummy bref,
2982 * then allocate the in-memory chain structure. Set the
2983 * INITIAL flag for fresh chains which do not have embedded
2984 * data.
2986 * XXX for now set the check mode of the child based on
2987 * the parent or, if the parent is an inode, the
2988 * specification in the inode.
2990 bzero(&dummy, sizeof(dummy));
2991 dummy.type = type;
2992 dummy.key = key;
2993 dummy.keybits = keybits;
2994 dummy.data_off = hammer2_getradix(bytes);
2997 * Inherit methods from parent by default. Primarily used
2998 * for BREF_TYPE_DATA. Non-data types *must* be set to
2999 * a non-NONE check algorithm.
3001 if (methods == -1)
3002 dummy.methods = parent->bref.methods;
3003 else
3004 dummy.methods = (uint8_t)methods;
3006 if (type != HAMMER2_BREF_TYPE_DATA &&
3007 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3008 dummy.methods |=
3009 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3012 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3015 * Lock the chain manually, chain_lock will load the chain
3016 * which we do NOT want to do. (note: chain->refs is set
3017 * to 1 by chain_alloc() for us, but lockcnt is not).
3019 chain->lockcnt = 1;
3020 hammer2_mtx_ex(&chain->lock);
3021 allocated = 1;
3022 ++curthread->td_tracker;
3025 * Set INITIAL to optimize I/O. The flag will generally be
3026 * processed when we call hammer2_chain_modify().
3028 * Recalculate bytes to reflect the actual media block
3029 * allocation. Handle special case radix 0 == 0 bytes.
3031 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3032 if (bytes)
3033 bytes = (hammer2_off_t)1 << bytes;
3034 chain->bytes = bytes;
3036 switch(type) {
3037 case HAMMER2_BREF_TYPE_VOLUME:
3038 case HAMMER2_BREF_TYPE_FREEMAP:
3039 panic("hammer2_chain_create: called with volume type");
3040 break;
3041 case HAMMER2_BREF_TYPE_INDIRECT:
3042 panic("hammer2_chain_create: cannot be used to"
3043 "create indirect block");
3044 break;
3045 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3046 panic("hammer2_chain_create: cannot be used to"
3047 "create freemap root or node");
3048 break;
3049 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3050 KKASSERT(bytes == sizeof(chain->data->bmdata));
3051 /* fall through */
3052 case HAMMER2_BREF_TYPE_DIRENT:
3053 case HAMMER2_BREF_TYPE_INODE:
3054 case HAMMER2_BREF_TYPE_DATA:
3055 default:
3057 * leave chain->data NULL, set INITIAL
3059 KKASSERT(chain->data == NULL);
3060 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3061 break;
3063 } else {
3065 * We are reattaching a previously deleted chain, possibly
3066 * under a new parent and possibly with a new key/keybits.
3067 * The chain does not have to be in a modified state. The
3068 * UPDATE flag will be set later on in this routine.
3070 * Do NOT mess with the current state of the INITIAL flag.
3072 chain->bref.key = key;
3073 chain->bref.keybits = keybits;
3074 if (chain->flags & HAMMER2_CHAIN_DELETED)
3075 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3076 KKASSERT(chain->parent == NULL);
3078 if (flags & HAMMER2_INSERT_PFSROOT)
3079 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3080 else
3081 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3084 * Calculate how many entries we have in the blockref array and
3085 * determine if an indirect block is required.
3087 again:
3088 if (--maxloops == 0)
3089 panic("hammer2_chain_create: maxloops");
3091 switch(parent->bref.type) {
3092 case HAMMER2_BREF_TYPE_INODE:
3093 if ((parent->data->ipdata.meta.op_flags &
3094 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3095 kprintf("hammer2: parent set for direct-data! "
3096 "pkey=%016jx ckey=%016jx\n",
3097 parent->bref.key,
3098 chain->bref.key);
3100 KKASSERT((parent->data->ipdata.meta.op_flags &
3101 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3102 KKASSERT(parent->data != NULL);
3103 base = &parent->data->ipdata.u.blockset.blockref[0];
3104 count = HAMMER2_SET_COUNT;
3105 break;
3106 case HAMMER2_BREF_TYPE_INDIRECT:
3107 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3108 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3109 base = NULL;
3110 else
3111 base = &parent->data->npdata[0];
3112 count = parent->bytes / sizeof(hammer2_blockref_t);
3113 break;
3114 case HAMMER2_BREF_TYPE_VOLUME:
3115 KKASSERT(parent->data != NULL);
3116 base = &parent->data->voldata.sroot_blockset.blockref[0];
3117 count = HAMMER2_SET_COUNT;
3118 break;
3119 case HAMMER2_BREF_TYPE_FREEMAP:
3120 KKASSERT(parent->data != NULL);
3121 base = &parent->data->blkset.blockref[0];
3122 count = HAMMER2_SET_COUNT;
3123 break;
3124 default:
3125 panic("hammer2_chain_create: unrecognized blockref type: %d",
3126 parent->bref.type);
3127 base = NULL;
3128 count = 0;
3129 break;
3133 * Make sure we've counted the brefs
3135 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3136 hammer2_chain_countbrefs(parent, base, count);
3138 KASSERT(parent->core.live_count >= 0 &&
3139 parent->core.live_count <= count,
3140 ("bad live_count %d/%d (%02x, %d)",
3141 parent->core.live_count, count,
3142 parent->bref.type, parent->bytes));
3145 * If no free blockref could be found we must create an indirect
3146 * block and move a number of blockrefs into it. With the parent
3147 * locked we can safely lock each child in order to delete+duplicate
3148 * it without causing a deadlock.
3150 * This may return the new indirect block or the old parent depending
3151 * on where the key falls. NULL is returned on error.
3153 if (parent->core.live_count == count) {
3154 hammer2_chain_t *nparent;
3156 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3157 mtid, type, &error);
3158 if (nparent == NULL) {
3159 if (allocated)
3160 hammer2_chain_drop(chain);
3161 chain = NULL;
3162 goto done;
3164 if (parent != nparent) {
3165 hammer2_chain_unlock(parent);
3166 hammer2_chain_drop(parent);
3167 parent = *parentp = nparent;
3169 goto again;
3172 if (chain->flags & HAMMER2_CHAIN_DELETED)
3173 kprintf("Inserting deleted chain @%016jx\n",
3174 chain->bref.key);
3177 * Link the chain into its parent.
3179 if (chain->parent != NULL)
3180 panic("hammer2: hammer2_chain_create: chain already connected");
3181 KKASSERT(chain->parent == NULL);
3182 hammer2_chain_insert(parent, chain,
3183 HAMMER2_CHAIN_INSERT_SPIN |
3184 HAMMER2_CHAIN_INSERT_LIVE,
3187 if (allocated) {
3189 * Mark the newly created chain modified. This will cause
3190 * UPDATE to be set and process the INITIAL flag.
3192 * Device buffers are not instantiated for DATA elements
3193 * as these are handled by logical buffers.
3195 * Indirect and freemap node indirect blocks are handled
3196 * by hammer2_chain_create_indirect() and not by this
3197 * function.
3199 * Data for all other bref types is expected to be
3200 * instantiated (INODE, LEAF).
3202 switch(chain->bref.type) {
3203 case HAMMER2_BREF_TYPE_DATA:
3204 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3205 case HAMMER2_BREF_TYPE_DIRENT:
3206 case HAMMER2_BREF_TYPE_INODE:
3207 hammer2_chain_modify(chain, mtid, dedup_off,
3208 HAMMER2_MODIFY_OPTDATA);
3209 break;
3210 default:
3212 * Remaining types are not supported by this function.
3213 * In particular, INDIRECT and LEAF_NODE types are
3214 * handled by create_indirect().
3216 panic("hammer2_chain_create: bad type: %d",
3217 chain->bref.type);
3218 /* NOT REACHED */
3219 break;
3221 } else {
3223 * When reconnecting a chain we must set UPDATE and
3224 * setflush so the flush recognizes that it must update
3225 * the bref in the parent.
3227 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3228 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3232 * We must setflush(parent) to ensure that it recurses through to
3233 * chain. setflush(chain) might not work because ONFLUSH is possibly
3234 * already set in the chain (so it won't recurse up to set it in the
3235 * parent).
3237 hammer2_chain_setflush(parent);
3239 done:
3240 *chainp = chain;
3242 return (error);
3246 * Move the chain from its old parent to a new parent. The chain must have
3247 * already been deleted or already disconnected (or never associated) with
3248 * a parent. The chain is reassociated with the new parent and the deleted
3249 * flag will be cleared (no longer deleted). The chain's modification state
3250 * is not altered.
3252 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3253 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3254 * FULL. This typically means that the caller is creating the chain after
3255 * doing a hammer2_chain_lookup().
3257 * A non-NULL bref is typically passed when key and keybits must be overridden.
3258 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3259 * from a passed-in bref and uses the old chain's bref for everything else.
3261 * Neither (parent) or (chain) can be errored.
3263 * If (parent) is non-NULL then the chain is inserted under the parent.
3265 * If (parent) is NULL then the newly duplicated chain is not inserted
3266 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3267 * passing into hammer2_chain_create() after this function returns).
3269 * WARNING! This function calls create which means it can insert indirect
3270 * blocks. This can cause other unrelated chains in the parent to
3271 * be moved to a newly inserted indirect block in addition to the
3272 * specific chain.
3274 void
3275 hammer2_chain_rename(hammer2_blockref_t *bref,
3276 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3277 hammer2_tid_t mtid, int flags)
3279 hammer2_dev_t *hmp;
3280 hammer2_chain_t *parent;
3281 size_t bytes;
3284 * WARNING! We should never resolve DATA to device buffers
3285 * (XXX allow it if the caller did?), and since
3286 * we currently do not have the logical buffer cache
3287 * buffer in-hand to fix its cached physical offset
3288 * we also force the modify code to not COW it. XXX
3290 hmp = chain->hmp;
3291 KKASSERT(chain->parent == NULL);
3292 KKASSERT(chain->error == 0);
3295 * Now create a duplicate of the chain structure, associating
3296 * it with the same core, making it the same size, pointing it
3297 * to the same bref (the same media block).
3299 * NOTE: Handle special radix == 0 case (means 0 bytes).
3301 if (bref == NULL)
3302 bref = &chain->bref;
3303 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3304 if (bytes)
3305 bytes = (hammer2_off_t)1 << bytes;
3308 * If parent is not NULL the duplicated chain will be entered under
3309 * the parent and the UPDATE bit set to tell flush to update
3310 * the blockref.
3312 * We must setflush(parent) to ensure that it recurses through to
3313 * chain. setflush(chain) might not work because ONFLUSH is possibly
3314 * already set in the chain (so it won't recurse up to set it in the
3315 * parent).
3317 * Having both chains locked is extremely important for atomicy.
3319 if (parentp && (parent = *parentp) != NULL) {
3320 KKASSERT(hammer2_mtx_owned(&parent->lock));
3321 KKASSERT(parent->refs > 0);
3322 KKASSERT(parent->error == 0);
3324 hammer2_chain_create(parentp, &chain,
3325 chain->pmp, HAMMER2_METH_DEFAULT,
3326 bref->key, bref->keybits, bref->type,
3327 chain->bytes, mtid, 0, flags);
3328 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3329 hammer2_chain_setflush(*parentp);
3334 * Helper function for deleting chains.
3336 * The chain is removed from the live view (the RBTREE) as well as the parent's
3337 * blockmap. Both chain and its parent must be locked.
3339 * parent may not be errored. chain can be errored.
3341 static void
3342 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3343 hammer2_tid_t mtid, int flags)
3345 hammer2_dev_t *hmp;
3347 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3348 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3349 KKASSERT(chain->parent == parent);
3350 hmp = chain->hmp;
3352 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3354 * Chain is blockmapped, so there must be a parent.
3355 * Atomically remove the chain from the parent and remove
3356 * the blockmap entry. The parent must be set modified
3357 * to remove the blockmap entry.
3359 hammer2_blockref_t *base;
3360 int count;
3362 KKASSERT(parent != NULL);
3363 KKASSERT(parent->error == 0);
3364 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3365 hammer2_chain_modify(parent, mtid, 0, 0);
3368 * Calculate blockmap pointer
3370 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3371 hammer2_spin_ex(&chain->core.spin);
3372 hammer2_spin_ex(&parent->core.spin);
3374 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3375 atomic_add_int(&parent->core.live_count, -1);
3376 ++parent->core.generation;
3377 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3378 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3379 --parent->core.chain_count;
3380 chain->parent = NULL;
3382 switch(parent->bref.type) {
3383 case HAMMER2_BREF_TYPE_INODE:
3385 * Access the inode's block array. However, there
3386 * is no block array if the inode is flagged
3387 * DIRECTDATA.
3389 if (parent->data &&
3390 (parent->data->ipdata.meta.op_flags &
3391 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3392 base =
3393 &parent->data->ipdata.u.blockset.blockref[0];
3394 } else {
3395 base = NULL;
3397 count = HAMMER2_SET_COUNT;
3398 break;
3399 case HAMMER2_BREF_TYPE_INDIRECT:
3400 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3401 if (parent->data)
3402 base = &parent->data->npdata[0];
3403 else
3404 base = NULL;
3405 count = parent->bytes / sizeof(hammer2_blockref_t);
3406 break;
3407 case HAMMER2_BREF_TYPE_VOLUME:
3408 base = &parent->data->voldata.
3409 sroot_blockset.blockref[0];
3410 count = HAMMER2_SET_COUNT;
3411 break;
3412 case HAMMER2_BREF_TYPE_FREEMAP:
3413 base = &parent->data->blkset.blockref[0];
3414 count = HAMMER2_SET_COUNT;
3415 break;
3416 default:
3417 base = NULL;
3418 count = 0;
3419 panic("hammer2_flush_pass2: "
3420 "unrecognized blockref type: %d",
3421 parent->bref.type);
3425 * delete blockmapped chain from its parent.
3427 * The parent is not affected by any statistics in chain
3428 * which are pending synchronization. That is, there is
3429 * nothing to undo in the parent since they have not yet
3430 * been incorporated into the parent.
3432 * The parent is affected by statistics stored in inodes.
3433 * Those have already been synchronized, so they must be
3434 * undone. XXX split update possible w/delete in middle?
3436 if (base) {
3437 int cache_index = -1;
3438 hammer2_base_delete(parent, base, count,
3439 &cache_index, chain);
3441 hammer2_spin_unex(&parent->core.spin);
3442 hammer2_spin_unex(&chain->core.spin);
3443 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3445 * Chain is not blockmapped but a parent is present.
3446 * Atomically remove the chain from the parent. There is
3447 * no blockmap entry to remove.
3449 * Because chain was associated with a parent but not
3450 * synchronized, the chain's *_count_up fields contain
3451 * inode adjustment statistics which must be undone.
3453 hammer2_spin_ex(&chain->core.spin);
3454 hammer2_spin_ex(&parent->core.spin);
3455 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3456 atomic_add_int(&parent->core.live_count, -1);
3457 ++parent->core.generation;
3458 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3459 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3460 --parent->core.chain_count;
3461 chain->parent = NULL;
3462 hammer2_spin_unex(&parent->core.spin);
3463 hammer2_spin_unex(&chain->core.spin);
3464 } else {
3466 * Chain is not blockmapped and has no parent. This
3467 * is a degenerate case.
3469 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3474 * Create an indirect block that covers one or more of the elements in the
3475 * current parent. Either returns the existing parent with no locking or
3476 * ref changes or returns the new indirect block locked and referenced
3477 * and leaving the original parent lock/ref intact as well.
3479 * If an error occurs, NULL is returned and *errorp is set to the error.
3481 * The returned chain depends on where the specified key falls.
3483 * The key/keybits for the indirect mode only needs to follow three rules:
3485 * (1) That all elements underneath it fit within its key space and
3487 * (2) That all elements outside it are outside its key space.
3489 * (3) When creating the new indirect block any elements in the current
3490 * parent that fit within the new indirect block's keyspace must be
3491 * moved into the new indirect block.
3493 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3494 * keyspace the the current parent, but lookup/iteration rules will
3495 * ensure (and must ensure) that rule (2) for all parents leading up
3496 * to the nearest inode or the root volume header is adhered to. This
3497 * is accomplished by always recursing through matching keyspaces in
3498 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3500 * The current implementation calculates the current worst-case keyspace by
3501 * iterating the current parent and then divides it into two halves, choosing
3502 * whichever half has the most elements (not necessarily the half containing
3503 * the requested key).
3505 * We can also opt to use the half with the least number of elements. This
3506 * causes lower-numbered keys (aka logical file offsets) to recurse through
3507 * fewer indirect blocks and higher-numbered keys to recurse through more.
3508 * This also has the risk of not moving enough elements to the new indirect
3509 * block and being forced to create several indirect blocks before the element
3510 * can be inserted.
3512 * Must be called with an exclusively locked parent.
3514 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3515 hammer2_key_t *keyp, int keybits,
3516 hammer2_blockref_t *base, int count);
3517 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3518 hammer2_key_t *keyp, int keybits,
3519 hammer2_blockref_t *base, int count,
3520 int ncount);
3521 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3522 hammer2_key_t *keyp, int keybits,
3523 hammer2_blockref_t *base, int count,
3524 int ncount);
3525 static
3526 hammer2_chain_t *
3527 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3528 hammer2_key_t create_key, int create_bits,
3529 hammer2_tid_t mtid, int for_type, int *errorp)
3531 hammer2_dev_t *hmp;
3532 hammer2_blockref_t *base;
3533 hammer2_blockref_t *bref;
3534 hammer2_blockref_t bcopy;
3535 hammer2_chain_t *chain;
3536 hammer2_chain_t *ichain;
3537 hammer2_chain_t dummy;
3538 hammer2_key_t key = create_key;
3539 hammer2_key_t key_beg;
3540 hammer2_key_t key_end;
3541 hammer2_key_t key_next;
3542 int keybits = create_bits;
3543 int count;
3544 int ncount;
3545 int nbytes;
3546 int cache_index;
3547 int loops;
3548 int reason;
3549 int generation;
3550 int maxloops = 300000;
3553 * Calculate the base blockref pointer or NULL if the chain
3554 * is known to be empty. We need to calculate the array count
3555 * for RB lookups either way.
3557 hmp = parent->hmp;
3558 *errorp = 0;
3559 KKASSERT(hammer2_mtx_owned(&parent->lock));
3561 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3562 base = hammer2_chain_base_and_count(parent, &count);
3565 * dummy used in later chain allocation (no longer used for lookups).
3567 bzero(&dummy, sizeof(dummy));
3570 * How big should our new indirect block be? It has to be at least
3571 * as large as its parent for splits to work properly.
3573 * The freemap uses a specific indirect block size. The number of
3574 * levels are built dynamically and ultimately depend on the size
3575 * volume. Because freemap blocks are taken from the reserved areas
3576 * of the volume our goal is efficiency (fewer levels) and not so
3577 * much to save disk space.
3579 * The first indirect block level for a directory usually uses
3580 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3581 * the hash mechanism, this typically gives us a nominal
3582 * 32 * 4 entries with one level of indirection.
3584 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3585 * indirect blocks. The initial 4 entries in the inode gives us
3586 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3587 * of indirection gives us 137GB, and so forth. H2 can support
3588 * huge file sizes but they are not typical, so we try to stick
3589 * with compactness and do not use a larger indirect block size.
3591 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3592 * due to the way indirect blocks are created this usually winds
3593 * up being extremely inefficient for small files. Even though
3594 * 16KB requires more levels of indirection for very large files,
3595 * the 16KB records can be ganged together into 64KB DIOs.
3597 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3598 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3599 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3600 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3601 if (parent->data->ipdata.meta.type ==
3602 HAMMER2_OBJTYPE_DIRECTORY)
3603 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3604 else
3605 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3607 } else {
3608 nbytes = HAMMER2_IND_BYTES_NOM;
3610 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3611 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3612 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3613 nbytes = count * sizeof(hammer2_blockref_t);
3615 ncount = nbytes / sizeof(hammer2_blockref_t);
3618 * When creating an indirect block for a freemap node or leaf
3619 * the key/keybits must be fitted to static radix levels because
3620 * particular radix levels use particular reserved blocks in the
3621 * related zone.
3623 * This routine calculates the key/radix of the indirect block
3624 * we need to create, and whether it is on the high-side or the
3625 * low-side.
3627 switch(for_type) {
3628 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3629 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3630 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3631 base, count);
3632 break;
3633 case HAMMER2_BREF_TYPE_DATA:
3634 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3635 base, count, ncount);
3636 break;
3637 case HAMMER2_BREF_TYPE_DIRENT:
3638 case HAMMER2_BREF_TYPE_INODE:
3639 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3640 base, count, ncount);
3641 break;
3642 default:
3643 panic("illegal indirect block for bref type %d", for_type);
3644 break;
3648 * Normalize the key for the radix being represented, keeping the
3649 * high bits and throwing away the low bits.
3651 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3654 * Ok, create our new indirect block
3656 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3657 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3658 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3659 } else {
3660 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3662 dummy.bref.key = key;
3663 dummy.bref.keybits = keybits;
3664 dummy.bref.data_off = hammer2_getradix(nbytes);
3665 dummy.bref.methods =
3666 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3667 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3669 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3670 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3671 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3672 /* ichain has one ref at this point */
3675 * We have to mark it modified to allocate its block, but use
3676 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3677 * it won't be acted upon by the flush code.
3679 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3682 * Iterate the original parent and move the matching brefs into
3683 * the new indirect block.
3685 * XXX handle flushes.
3687 key_beg = 0;
3688 key_end = HAMMER2_KEY_MAX;
3689 key_next = 0; /* avoid gcc warnings */
3690 cache_index = 0;
3691 hammer2_spin_ex(&parent->core.spin);
3692 loops = 0;
3693 reason = 0;
3695 for (;;) {
3697 * Parent may have been modified, relocating its block array.
3698 * Reload the base pointer.
3700 base = hammer2_chain_base_and_count(parent, &count);
3702 if (++loops > 100000) {
3703 hammer2_spin_unex(&parent->core.spin);
3704 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3705 reason, parent, base, count, key_next);
3709 * NOTE: spinlock stays intact, returned chain (if not NULL)
3710 * is not referenced or locked which means that we
3711 * cannot safely check its flagged / deletion status
3712 * until we lock it.
3714 chain = hammer2_combined_find(parent, base, count,
3715 &cache_index, &key_next,
3716 key_beg, key_end,
3717 &bref);
3718 generation = parent->core.generation;
3719 if (bref == NULL)
3720 break;
3721 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3724 * Skip keys that are not within the key/radix of the new
3725 * indirect block. They stay in the parent.
3727 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3728 (key ^ bref->key)) != 0) {
3729 goto next_key_spinlocked;
3733 * Load the new indirect block by acquiring the related
3734 * chains (potentially from media as it might not be
3735 * in-memory). Then move it to the new parent (ichain).
3737 * chain is referenced but not locked. We must lock the
3738 * chain to obtain definitive state.
3740 if (chain) {
3742 * Use chain already present in the RBTREE
3744 hammer2_chain_ref(chain);
3745 hammer2_spin_unex(&parent->core.spin);
3746 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3747 } else {
3749 * Get chain for blockref element. _get returns NULL
3750 * on insertion race.
3752 bcopy = *bref;
3753 hammer2_spin_unex(&parent->core.spin);
3754 chain = hammer2_chain_get(parent, generation, &bcopy);
3755 if (chain == NULL) {
3756 reason = 1;
3757 hammer2_spin_ex(&parent->core.spin);
3758 continue;
3760 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3761 kprintf("REASON 2\n");
3762 reason = 2;
3763 hammer2_chain_drop(chain);
3764 hammer2_spin_ex(&parent->core.spin);
3765 continue;
3767 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3771 * This is always live so if the chain has been deleted
3772 * we raced someone and we have to retry.
3774 * NOTE: Lookups can race delete-duplicate because
3775 * delete-duplicate does not lock the parent's core
3776 * (they just use the spinlock on the core).
3778 * (note reversed logic for this one)
3780 if (chain->parent != parent ||
3781 (chain->flags & HAMMER2_CHAIN_DELETED)) {
3782 hammer2_chain_unlock(chain);
3783 hammer2_chain_drop(chain);
3784 kprintf("hammer2_chain_create_indirect "
3785 "RETRY (%p,%p)->%p %08x\n",
3786 parent, chain->parent, chain, chain->flags);
3787 hammer2_spin_ex(&parent->core.spin);
3788 continue;
3792 * Shift the chain to the indirect block.
3794 * WARNING! No reason for us to load chain data, pass NOSTATS
3795 * to prevent delete/insert from trying to access
3796 * inode stats (and thus asserting if there is no
3797 * chain->data loaded).
3799 * WARNING! The (parent, chain) deletion may modify the parent
3800 * and invalidate the base pointer.
3802 hammer2_chain_delete(parent, chain, mtid, 0);
3803 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3804 hammer2_chain_unlock(chain);
3805 hammer2_chain_drop(chain);
3806 KKASSERT(parent->refs > 0);
3807 chain = NULL;
3808 base = NULL; /* safety */
3809 hammer2_spin_ex(&parent->core.spin);
3810 next_key_spinlocked:
3811 if (--maxloops == 0)
3812 panic("hammer2_chain_create_indirect: maxloops");
3813 reason = 4;
3814 if (key_next == 0 || key_next > key_end)
3815 break;
3816 key_beg = key_next;
3817 /* loop */
3819 hammer2_spin_unex(&parent->core.spin);
3822 * Insert the new indirect block into the parent now that we've
3823 * cleared out some entries in the parent. We calculated a good
3824 * insertion index in the loop above (ichain->index).
3826 * We don't have to set UPDATE here because we mark ichain
3827 * modified down below (so the normal modified -> flush -> set-moved
3828 * sequence applies).
3830 * The insertion shouldn't race as this is a completely new block
3831 * and the parent is locked.
3833 base = NULL; /* safety, parent modify may change address */
3834 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3835 hammer2_chain_insert(parent, ichain,
3836 HAMMER2_CHAIN_INSERT_SPIN |
3837 HAMMER2_CHAIN_INSERT_LIVE,
3841 * Make sure flushes propogate after our manual insertion.
3843 hammer2_chain_setflush(ichain);
3844 hammer2_chain_setflush(parent);
3847 * Figure out what to return.
3849 if (~(((hammer2_key_t)1 << keybits) - 1) &
3850 (create_key ^ key)) {
3852 * Key being created is outside the key range,
3853 * return the original parent.
3855 hammer2_chain_unlock(ichain);
3856 hammer2_chain_drop(ichain);
3857 } else {
3859 * Otherwise its in the range, return the new parent.
3860 * (leave both the new and old parent locked).
3862 parent = ichain;
3865 return(parent);
3869 * Freemap indirect blocks
3871 * Calculate the keybits and highside/lowside of the freemap node the
3872 * caller is creating.
3874 * This routine will specify the next higher-level freemap key/radix
3875 * representing the lowest-ordered set. By doing so, eventually all
3876 * low-ordered sets will be moved one level down.
3878 * We have to be careful here because the freemap reserves a limited
3879 * number of blocks for a limited number of levels. So we can't just
3880 * push indiscriminately.
3883 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3884 int keybits, hammer2_blockref_t *base, int count)
3886 hammer2_chain_t *chain;
3887 hammer2_blockref_t *bref;
3888 hammer2_key_t key;
3889 hammer2_key_t key_beg;
3890 hammer2_key_t key_end;
3891 hammer2_key_t key_next;
3892 int cache_index;
3893 int locount;
3894 int hicount;
3895 int maxloops = 300000;
3897 key = *keyp;
3898 locount = 0;
3899 hicount = 0;
3900 keybits = 64;
3903 * Calculate the range of keys in the array being careful to skip
3904 * slots which are overridden with a deletion.
3906 key_beg = 0;
3907 key_end = HAMMER2_KEY_MAX;
3908 cache_index = 0;
3909 hammer2_spin_ex(&parent->core.spin);
3911 for (;;) {
3912 if (--maxloops == 0) {
3913 panic("indkey_freemap shit %p %p:%d\n",
3914 parent, base, count);
3916 chain = hammer2_combined_find(parent, base, count,
3917 &cache_index, &key_next,
3918 key_beg, key_end,
3919 &bref);
3922 * Exhausted search
3924 if (bref == NULL)
3925 break;
3928 * Skip deleted chains.
3930 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3931 if (key_next == 0 || key_next > key_end)
3932 break;
3933 key_beg = key_next;
3934 continue;
3938 * Use the full live (not deleted) element for the scan
3939 * iteration. HAMMER2 does not allow partial replacements.
3941 * XXX should be built into hammer2_combined_find().
3943 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3945 if (keybits > bref->keybits) {
3946 key = bref->key;
3947 keybits = bref->keybits;
3948 } else if (keybits == bref->keybits && bref->key < key) {
3949 key = bref->key;
3951 if (key_next == 0)
3952 break;
3953 key_beg = key_next;
3955 hammer2_spin_unex(&parent->core.spin);
3958 * Return the keybits for a higher-level FREEMAP_NODE covering
3959 * this node.
3961 switch(keybits) {
3962 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3963 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3964 break;
3965 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3966 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3967 break;
3968 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3969 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3970 break;
3971 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3972 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3973 break;
3974 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3975 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3976 break;
3977 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3978 panic("hammer2_chain_indkey_freemap: level too high");
3979 break;
3980 default:
3981 panic("hammer2_chain_indkey_freemap: bad radix");
3982 break;
3984 *keyp = key;
3986 return (keybits);
3990 * File indirect blocks
3992 * Calculate the key/keybits for the indirect block to create by scanning
3993 * existing keys. The key being created is also passed in *keyp and can be
3994 * inside or outside the indirect block. Regardless, the indirect block
3995 * must hold at least two keys in order to guarantee sufficient space.
3997 * We use a modified version of the freemap's fixed radix tree, but taylored
3998 * for file data. Basically we configure an indirect block encompassing the
3999 * smallest key.
4001 static int
4002 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4003 int keybits, hammer2_blockref_t *base, int count,
4004 int ncount)
4006 hammer2_chain_t *chain;
4007 hammer2_blockref_t *bref;
4008 hammer2_key_t key;
4009 hammer2_key_t key_beg;
4010 hammer2_key_t key_end;
4011 hammer2_key_t key_next;
4012 int nradix;
4013 int cache_index;
4014 int locount;
4015 int hicount;
4016 int maxloops = 300000;
4018 key = *keyp;
4019 locount = 0;
4020 hicount = 0;
4021 keybits = 64;
4024 * Calculate the range of keys in the array being careful to skip
4025 * slots which are overridden with a deletion.
4027 * Locate the smallest key.
4029 key_beg = 0;
4030 key_end = HAMMER2_KEY_MAX;
4031 cache_index = 0;
4032 hammer2_spin_ex(&parent->core.spin);
4034 for (;;) {
4035 if (--maxloops == 0) {
4036 panic("indkey_freemap shit %p %p:%d\n",
4037 parent, base, count);
4039 chain = hammer2_combined_find(parent, base, count,
4040 &cache_index, &key_next,
4041 key_beg, key_end,
4042 &bref);
4045 * Exhausted search
4047 if (bref == NULL)
4048 break;
4051 * Skip deleted chains.
4053 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4054 if (key_next == 0 || key_next > key_end)
4055 break;
4056 key_beg = key_next;
4057 continue;
4061 * Use the full live (not deleted) element for the scan
4062 * iteration. HAMMER2 does not allow partial replacements.
4064 * XXX should be built into hammer2_combined_find().
4066 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4068 if (keybits > bref->keybits) {
4069 key = bref->key;
4070 keybits = bref->keybits;
4071 } else if (keybits == bref->keybits && bref->key < key) {
4072 key = bref->key;
4074 if (key_next == 0)
4075 break;
4076 key_beg = key_next;
4078 hammer2_spin_unex(&parent->core.spin);
4081 * Calculate the static keybits for a higher-level indirect block
4082 * that contains the key.
4084 *keyp = key;
4086 switch(ncount) {
4087 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4088 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4089 break;
4090 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4091 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4092 break;
4093 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4094 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4095 break;
4096 default:
4097 panic("bad ncount %d\n", ncount);
4098 nradix = 0;
4099 break;
4103 * The largest radix that can be returned for an indirect block is
4104 * 63 bits. (The largest practical indirect block radix is actually
4105 * 62 bits because the top-level inode or volume root contains four
4106 * entries, but allow 63 to be returned).
4108 if (nradix >= 64)
4109 nradix = 63;
4111 return keybits + nradix;
4114 #if 1
4117 * Directory indirect blocks.
4119 * Covers both the inode index (directory of inodes), and directory contents
4120 * (filenames hardlinked to inodes).
4122 * Because directory keys are hashed we generally try to cut the space in
4123 * half. We accomodate the inode index (which tends to have linearly
4124 * increasing inode numbers) by ensuring that the keyspace is at least large
4125 * enough to fill up the indirect block being created.
4127 static int
4128 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4129 int keybits, hammer2_blockref_t *base, int count,
4130 int ncount)
4132 hammer2_blockref_t *bref;
4133 hammer2_chain_t *chain;
4134 hammer2_key_t key_beg;
4135 hammer2_key_t key_end;
4136 hammer2_key_t key_next;
4137 hammer2_key_t key;
4138 int nkeybits;
4139 int locount;
4140 int hicount;
4141 int cache_index;
4142 int maxloops = 300000;
4145 * Shortcut if the parent is the inode. In this situation the
4146 * parent has 4+1 directory entries and we are creating an indirect
4147 * block capable of holding many more.
4149 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4150 return 63;
4153 key = *keyp;
4154 locount = 0;
4155 hicount = 0;
4158 * Calculate the range of keys in the array being careful to skip
4159 * slots which are overridden with a deletion.
4161 key_beg = 0;
4162 key_end = HAMMER2_KEY_MAX;
4163 cache_index = 0;
4164 hammer2_spin_ex(&parent->core.spin);
4166 for (;;) {
4167 if (--maxloops == 0) {
4168 panic("indkey_freemap shit %p %p:%d\n",
4169 parent, base, count);
4171 chain = hammer2_combined_find(parent, base, count,
4172 &cache_index, &key_next,
4173 key_beg, key_end,
4174 &bref);
4177 * Exhausted search
4179 if (bref == NULL)
4180 break;
4183 * Deleted object
4185 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4186 if (key_next == 0 || key_next > key_end)
4187 break;
4188 key_beg = key_next;
4189 continue;
4193 * Use the full live (not deleted) element for the scan
4194 * iteration. HAMMER2 does not allow partial replacements.
4196 * XXX should be built into hammer2_combined_find().
4198 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4201 * Expand our calculated key range (key, keybits) to fit
4202 * the scanned key. nkeybits represents the full range
4203 * that we will later cut in half (two halves @ nkeybits - 1).
4205 nkeybits = keybits;
4206 if (nkeybits < bref->keybits) {
4207 if (bref->keybits > 64) {
4208 kprintf("bad bref chain %p bref %p\n",
4209 chain, bref);
4210 Debugger("fubar");
4212 nkeybits = bref->keybits;
4214 while (nkeybits < 64 &&
4215 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4216 (key ^ bref->key)) != 0) {
4217 ++nkeybits;
4221 * If the new key range is larger we have to determine
4222 * which side of the new key range the existing keys fall
4223 * under by checking the high bit, then collapsing the
4224 * locount into the hicount or vise-versa.
4226 if (keybits != nkeybits) {
4227 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4228 hicount += locount;
4229 locount = 0;
4230 } else {
4231 locount += hicount;
4232 hicount = 0;
4234 keybits = nkeybits;
4238 * The newly scanned key will be in the lower half or the
4239 * upper half of the (new) key range.
4241 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4242 ++hicount;
4243 else
4244 ++locount;
4246 if (key_next == 0)
4247 break;
4248 key_beg = key_next;
4250 hammer2_spin_unex(&parent->core.spin);
4251 bref = NULL; /* now invalid (safety) */
4254 * Adjust keybits to represent half of the full range calculated
4255 * above (radix 63 max) for our new indirect block.
4257 --keybits;
4260 * Expand keybits to hold at least ncount elements. ncount will be
4261 * a power of 2. This is to try to completely fill leaf nodes (at
4262 * least for keys which are not hashes).
4264 * We aren't counting 'in' or 'out', we are counting 'high side'
4265 * and 'low side' based on the bit at (1LL << keybits). We want
4266 * everything to be inside in these cases so shift it all to
4267 * the low or high side depending on the new high bit.
4269 while (((hammer2_key_t)1 << keybits) < ncount) {
4270 ++keybits;
4271 if (key & ((hammer2_key_t)1 << keybits)) {
4272 hicount += locount;
4273 locount = 0;
4274 } else {
4275 locount += hicount;
4276 hicount = 0;
4280 if (hicount > locount)
4281 key |= (hammer2_key_t)1 << keybits;
4282 else
4283 key &= ~(hammer2_key_t)1 << keybits;
4285 *keyp = key;
4287 return (keybits);
4290 #else
4293 * Directory indirect blocks.
4295 * Covers both the inode index (directory of inodes), and directory contents
4296 * (filenames hardlinked to inodes).
4298 * Because directory keys are hashed we generally try to cut the space in
4299 * half. We accomodate the inode index (which tends to have linearly
4300 * increasing inode numbers) by ensuring that the keyspace is at least large
4301 * enough to fill up the indirect block being created.
4303 static int
4304 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4305 int keybits, hammer2_blockref_t *base, int count,
4306 int ncount)
4308 hammer2_blockref_t *bref;
4309 hammer2_chain_t *chain;
4310 hammer2_key_t key_beg;
4311 hammer2_key_t key_end;
4312 hammer2_key_t key_next;
4313 hammer2_key_t key;
4314 int nkeybits;
4315 int locount;
4316 int hicount;
4317 int cache_index;
4318 int maxloops = 300000;
4321 * Shortcut if the parent is the inode. In this situation the
4322 * parent has 4+1 directory entries and we are creating an indirect
4323 * block capable of holding many more.
4325 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4326 return 63;
4329 key = *keyp;
4330 locount = 0;
4331 hicount = 0;
4334 * Calculate the range of keys in the array being careful to skip
4335 * slots which are overridden with a deletion.
4337 key_beg = 0;
4338 key_end = HAMMER2_KEY_MAX;
4339 cache_index = 0;
4340 hammer2_spin_ex(&parent->core.spin);
4342 for (;;) {
4343 if (--maxloops == 0) {
4344 panic("indkey_freemap shit %p %p:%d\n",
4345 parent, base, count);
4347 chain = hammer2_combined_find(parent, base, count,
4348 &cache_index, &key_next,
4349 key_beg, key_end,
4350 &bref);
4353 * Exhausted search
4355 if (bref == NULL)
4356 break;
4359 * Deleted object
4361 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4362 if (key_next == 0 || key_next > key_end)
4363 break;
4364 key_beg = key_next;
4365 continue;
4369 * Use the full live (not deleted) element for the scan
4370 * iteration. HAMMER2 does not allow partial replacements.
4372 * XXX should be built into hammer2_combined_find().
4374 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4377 * Expand our calculated key range (key, keybits) to fit
4378 * the scanned key. nkeybits represents the full range
4379 * that we will later cut in half (two halves @ nkeybits - 1).
4381 nkeybits = keybits;
4382 if (nkeybits < bref->keybits) {
4383 if (bref->keybits > 64) {
4384 kprintf("bad bref chain %p bref %p\n",
4385 chain, bref);
4386 Debugger("fubar");
4388 nkeybits = bref->keybits;
4390 while (nkeybits < 64 &&
4391 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4392 (key ^ bref->key)) != 0) {
4393 ++nkeybits;
4397 * If the new key range is larger we have to determine
4398 * which side of the new key range the existing keys fall
4399 * under by checking the high bit, then collapsing the
4400 * locount into the hicount or vise-versa.
4402 if (keybits != nkeybits) {
4403 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4404 hicount += locount;
4405 locount = 0;
4406 } else {
4407 locount += hicount;
4408 hicount = 0;
4410 keybits = nkeybits;
4414 * The newly scanned key will be in the lower half or the
4415 * upper half of the (new) key range.
4417 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4418 ++hicount;
4419 else
4420 ++locount;
4422 if (key_next == 0)
4423 break;
4424 key_beg = key_next;
4426 hammer2_spin_unex(&parent->core.spin);
4427 bref = NULL; /* now invalid (safety) */
4430 * Adjust keybits to represent half of the full range calculated
4431 * above (radix 63 max) for our new indirect block.
4433 --keybits;
4436 * Expand keybits to hold at least ncount elements. ncount will be
4437 * a power of 2. This is to try to completely fill leaf nodes (at
4438 * least for keys which are not hashes).
4440 * We aren't counting 'in' or 'out', we are counting 'high side'
4441 * and 'low side' based on the bit at (1LL << keybits). We want
4442 * everything to be inside in these cases so shift it all to
4443 * the low or high side depending on the new high bit.
4445 while (((hammer2_key_t)1 << keybits) < ncount) {
4446 ++keybits;
4447 if (key & ((hammer2_key_t)1 << keybits)) {
4448 hicount += locount;
4449 locount = 0;
4450 } else {
4451 locount += hicount;
4452 hicount = 0;
4456 if (hicount > locount)
4457 key |= (hammer2_key_t)1 << keybits;
4458 else
4459 key &= ~(hammer2_key_t)1 << keybits;
4461 *keyp = key;
4463 return (keybits);
4466 #endif
4469 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4470 * it exists.
4472 * Both parent and chain must be locked exclusively.
4474 * This function will modify the parent if the blockref requires removal
4475 * from the parent's block table.
4477 * This function is NOT recursive. Any entity already pushed into the
4478 * chain (such as an inode) may still need visibility into its contents,
4479 * as well as the ability to read and modify the contents. For example,
4480 * for an unlinked file which is still open.
4482 * Also note that the flusher is responsible for cleaning up empty
4483 * indirect blocks.
4485 void
4486 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4487 hammer2_tid_t mtid, int flags)
4489 KKASSERT(hammer2_mtx_owned(&chain->lock));
4492 * Nothing to do if already marked.
4494 * We need the spinlock on the core whos RBTREE contains chain
4495 * to protect against races.
4497 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4498 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4499 chain->parent == parent);
4500 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4504 * Permanent deletions mark the chain as destroyed.
4506 if (flags & HAMMER2_DELETE_PERMANENT)
4507 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4508 hammer2_chain_setflush(chain);
4512 * Returns the index of the nearest element in the blockref array >= elm.
4513 * Returns (count) if no element could be found.
4515 * Sets *key_nextp to the next key for loop purposes but does not modify
4516 * it if the next key would be higher than the current value of *key_nextp.
4517 * Note that *key_nexp can overflow to 0, which should be tested by the
4518 * caller.
4520 * (*cache_indexp) is a heuristic and can be any value without effecting
4521 * the result.
4523 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4524 * held through the operation.
4526 static int
4527 hammer2_base_find(hammer2_chain_t *parent,
4528 hammer2_blockref_t *base, int count,
4529 int *cache_indexp, hammer2_key_t *key_nextp,
4530 hammer2_key_t key_beg, hammer2_key_t key_end)
4532 hammer2_blockref_t *scan;
4533 hammer2_key_t scan_end;
4534 int i;
4535 int limit;
4538 * Require the live chain's already have their core's counted
4539 * so we can optimize operations.
4541 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4544 * Degenerate case
4546 if (count == 0 || base == NULL)
4547 return(count);
4550 * Sequential optimization using *cache_indexp. This is the most
4551 * likely scenario.
4553 * We can avoid trailing empty entries on live chains, otherwise
4554 * we might have to check the whole block array.
4556 i = *cache_indexp;
4557 cpu_ccfence();
4558 limit = parent->core.live_zero;
4559 if (i >= limit)
4560 i = limit - 1;
4561 if (i < 0)
4562 i = 0;
4563 KKASSERT(i < count);
4566 * Search backwards
4568 scan = &base[i];
4569 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4570 --scan;
4571 --i;
4573 *cache_indexp = i;
4576 * Search forwards, stop when we find a scan element which
4577 * encloses the key or until we know that there are no further
4578 * elements.
4580 while (i < count) {
4581 if (scan->type != 0) {
4582 scan_end = scan->key +
4583 ((hammer2_key_t)1 << scan->keybits) - 1;
4584 if (scan->key > key_beg || scan_end >= key_beg)
4585 break;
4587 if (i >= limit)
4588 return (count);
4589 ++scan;
4590 ++i;
4592 if (i != count) {
4593 *cache_indexp = i;
4594 if (i >= limit) {
4595 i = count;
4596 } else {
4597 scan_end = scan->key +
4598 ((hammer2_key_t)1 << scan->keybits);
4599 if (scan_end && (*key_nextp > scan_end ||
4600 *key_nextp == 0)) {
4601 *key_nextp = scan_end;
4605 return (i);
4609 * Do a combined search and return the next match either from the blockref
4610 * array or from the in-memory chain. Sets *bresp to the returned bref in
4611 * both cases, or sets it to NULL if the search exhausted. Only returns
4612 * a non-NULL chain if the search matched from the in-memory chain.
4614 * When no in-memory chain has been found and a non-NULL bref is returned
4615 * in *bresp.
4618 * The returned chain is not locked or referenced. Use the returned bref
4619 * to determine if the search exhausted or not. Iterate if the base find
4620 * is chosen but matches a deleted chain.
4622 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4623 * held through the operation.
4625 static hammer2_chain_t *
4626 hammer2_combined_find(hammer2_chain_t *parent,
4627 hammer2_blockref_t *base, int count,
4628 int *cache_indexp, hammer2_key_t *key_nextp,
4629 hammer2_key_t key_beg, hammer2_key_t key_end,
4630 hammer2_blockref_t **bresp)
4632 hammer2_blockref_t *bref;
4633 hammer2_chain_t *chain;
4634 int i;
4637 * Lookup in block array and in rbtree.
4639 *key_nextp = key_end + 1;
4640 i = hammer2_base_find(parent, base, count, cache_indexp,
4641 key_nextp, key_beg, key_end);
4642 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4645 * Neither matched
4647 if (i == count && chain == NULL) {
4648 *bresp = NULL;
4649 return(NULL);
4653 * Only chain matched.
4655 if (i == count) {
4656 bref = &chain->bref;
4657 goto found;
4661 * Only blockref matched.
4663 if (chain == NULL) {
4664 bref = &base[i];
4665 goto found;
4669 * Both in-memory and blockref matched, select the nearer element.
4671 * If both are flush with the left-hand side or both are the
4672 * same distance away, select the chain. In this situation the
4673 * chain must have been loaded from the matching blockmap.
4675 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4676 chain->bref.key == base[i].key) {
4677 KKASSERT(chain->bref.key == base[i].key);
4678 bref = &chain->bref;
4679 goto found;
4683 * Select the nearer key
4685 if (chain->bref.key < base[i].key) {
4686 bref = &chain->bref;
4687 } else {
4688 bref = &base[i];
4689 chain = NULL;
4693 * If the bref is out of bounds we've exhausted our search.
4695 found:
4696 if (bref->key > key_end) {
4697 *bresp = NULL;
4698 chain = NULL;
4699 } else {
4700 *bresp = bref;
4702 return(chain);
4706 * Locate the specified block array element and delete it. The element
4707 * must exist.
4709 * The spin lock on the related chain must be held.
4711 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4712 * need to be adjusted when we commit the media change.
4714 void
4715 hammer2_base_delete(hammer2_chain_t *parent,
4716 hammer2_blockref_t *base, int count,
4717 int *cache_indexp, hammer2_chain_t *chain)
4719 hammer2_blockref_t *elm = &chain->bref;
4720 hammer2_blockref_t *scan;
4721 hammer2_key_t key_next;
4722 int i;
4725 * Delete element. Expect the element to exist.
4727 * XXX see caller, flush code not yet sophisticated enough to prevent
4728 * re-flushed in some cases.
4730 key_next = 0; /* max range */
4731 i = hammer2_base_find(parent, base, count, cache_indexp,
4732 &key_next, elm->key, elm->key);
4733 scan = &base[i];
4734 if (i == count || scan->type == 0 ||
4735 scan->key != elm->key ||
4736 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4737 scan->keybits != elm->keybits)) {
4738 hammer2_spin_unex(&parent->core.spin);
4739 panic("delete base %p element not found at %d/%d elm %p\n",
4740 base, i, count, elm);
4741 return;
4745 * Update stats and zero the entry.
4747 * NOTE: Handle radix == 0 (0 bytes) case.
4749 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4750 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4751 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4753 switch(scan->type) {
4754 case HAMMER2_BREF_TYPE_INODE:
4755 parent->bref.embed.stats.inode_count -= 1;
4756 /* fall through */
4757 case HAMMER2_BREF_TYPE_DATA:
4758 case HAMMER2_BREF_TYPE_INDIRECT:
4759 parent->bref.embed.stats.data_count -=
4760 scan->embed.stats.data_count;
4761 parent->bref.embed.stats.inode_count -=
4762 scan->embed.stats.inode_count;
4763 break;
4764 default:
4765 break;
4768 bzero(scan, sizeof(*scan));
4771 * We can only optimize parent->core.live_zero for live chains.
4773 if (parent->core.live_zero == i + 1) {
4774 while (--i >= 0 && base[i].type == 0)
4776 parent->core.live_zero = i + 1;
4780 * Clear appropriate blockmap flags in chain.
4782 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4783 HAMMER2_CHAIN_BMAPUPD);
4787 * Insert the specified element. The block array must not already have the
4788 * element and must have space available for the insertion.
4790 * The spin lock on the related chain must be held.
4792 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4793 * need to be adjusted when we commit the media change.
4795 void
4796 hammer2_base_insert(hammer2_chain_t *parent,
4797 hammer2_blockref_t *base, int count,
4798 int *cache_indexp, hammer2_chain_t *chain)
4800 hammer2_blockref_t *elm = &chain->bref;
4801 hammer2_key_t key_next;
4802 hammer2_key_t xkey;
4803 int i;
4804 int j;
4805 int k;
4806 int l;
4807 int u = 1;
4810 * Insert new element. Expect the element to not already exist
4811 * unless we are replacing it.
4813 * XXX see caller, flush code not yet sophisticated enough to prevent
4814 * re-flushed in some cases.
4816 key_next = 0; /* max range */
4817 i = hammer2_base_find(parent, base, count, cache_indexp,
4818 &key_next, elm->key, elm->key);
4821 * Shortcut fill optimization, typical ordered insertion(s) may not
4822 * require a search.
4824 KKASSERT(i >= 0 && i <= count);
4827 * Set appropriate blockmap flags in chain.
4829 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4832 * Update stats and zero the entry
4834 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4835 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4836 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4838 switch(elm->type) {
4839 case HAMMER2_BREF_TYPE_INODE:
4840 parent->bref.embed.stats.inode_count += 1;
4841 /* fall through */
4842 case HAMMER2_BREF_TYPE_DATA:
4843 case HAMMER2_BREF_TYPE_INDIRECT:
4844 parent->bref.embed.stats.data_count +=
4845 elm->embed.stats.data_count;
4846 parent->bref.embed.stats.inode_count +=
4847 elm->embed.stats.inode_count;
4848 break;
4849 default:
4850 break;
4855 * We can only optimize parent->core.live_zero for live chains.
4857 if (i == count && parent->core.live_zero < count) {
4858 i = parent->core.live_zero++;
4859 base[i] = *elm;
4860 return;
4863 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4864 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4865 hammer2_spin_unex(&parent->core.spin);
4866 panic("insert base %p overlapping elements at %d elm %p\n",
4867 base, i, elm);
4871 * Try to find an empty slot before or after.
4873 j = i;
4874 k = i;
4875 while (j > 0 || k < count) {
4876 --j;
4877 if (j >= 0 && base[j].type == 0) {
4878 if (j == i - 1) {
4879 base[j] = *elm;
4880 } else {
4881 bcopy(&base[j+1], &base[j],
4882 (i - j - 1) * sizeof(*base));
4883 base[i - 1] = *elm;
4885 goto validate;
4887 ++k;
4888 if (k < count && base[k].type == 0) {
4889 bcopy(&base[i], &base[i+1],
4890 (k - i) * sizeof(hammer2_blockref_t));
4891 base[i] = *elm;
4894 * We can only update parent->core.live_zero for live
4895 * chains.
4897 if (parent->core.live_zero <= k)
4898 parent->core.live_zero = k + 1;
4899 u = 2;
4900 goto validate;
4903 panic("hammer2_base_insert: no room!");
4906 * Debugging
4908 validate:
4909 key_next = 0;
4910 for (l = 0; l < count; ++l) {
4911 if (base[l].type) {
4912 key_next = base[l].key +
4913 ((hammer2_key_t)1 << base[l].keybits) - 1;
4914 break;
4917 while (++l < count) {
4918 if (base[l].type) {
4919 if (base[l].key <= key_next)
4920 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4921 key_next = base[l].key +
4922 ((hammer2_key_t)1 << base[l].keybits) - 1;
4929 #if 0
4932 * Sort the blockref array for the chain. Used by the flush code to
4933 * sort the blockref[] array.
4935 * The chain must be exclusively locked AND spin-locked.
4937 typedef hammer2_blockref_t *hammer2_blockref_p;
4939 static
4941 hammer2_base_sort_callback(const void *v1, const void *v2)
4943 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4944 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4947 * Make sure empty elements are placed at the end of the array
4949 if (bref1->type == 0) {
4950 if (bref2->type == 0)
4951 return(0);
4952 return(1);
4953 } else if (bref2->type == 0) {
4954 return(-1);
4958 * Sort by key
4960 if (bref1->key < bref2->key)
4961 return(-1);
4962 if (bref1->key > bref2->key)
4963 return(1);
4964 return(0);
4967 void
4968 hammer2_base_sort(hammer2_chain_t *chain)
4970 hammer2_blockref_t *base;
4971 int count;
4973 switch(chain->bref.type) {
4974 case HAMMER2_BREF_TYPE_INODE:
4976 * Special shortcut for embedded data returns the inode
4977 * itself. Callers must detect this condition and access
4978 * the embedded data (the strategy code does this for us).
4980 * This is only applicable to regular files and softlinks.
4982 if (chain->data->ipdata.meta.op_flags &
4983 HAMMER2_OPFLAG_DIRECTDATA) {
4984 return;
4986 base = &chain->data->ipdata.u.blockset.blockref[0];
4987 count = HAMMER2_SET_COUNT;
4988 break;
4989 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4990 case HAMMER2_BREF_TYPE_INDIRECT:
4992 * Optimize indirect blocks in the INITIAL state to avoid
4993 * I/O.
4995 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4996 base = &chain->data->npdata[0];
4997 count = chain->bytes / sizeof(hammer2_blockref_t);
4998 break;
4999 case HAMMER2_BREF_TYPE_VOLUME:
5000 base = &chain->data->voldata.sroot_blockset.blockref[0];
5001 count = HAMMER2_SET_COUNT;
5002 break;
5003 case HAMMER2_BREF_TYPE_FREEMAP:
5004 base = &chain->data->blkset.blockref[0];
5005 count = HAMMER2_SET_COUNT;
5006 break;
5007 default:
5008 kprintf("hammer2_chain_lookup: unrecognized "
5009 "blockref(A) type: %d",
5010 chain->bref.type);
5011 while (1)
5012 tsleep(&base, 0, "dead", 0);
5013 panic("hammer2_chain_lookup: unrecognized "
5014 "blockref(A) type: %d",
5015 chain->bref.type);
5016 base = NULL; /* safety */
5017 count = 0; /* safety */
5019 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5022 #endif
5025 * Chain memory management
5027 void
5028 hammer2_chain_wait(hammer2_chain_t *chain)
5030 tsleep(chain, 0, "chnflw", 1);
5033 const hammer2_media_data_t *
5034 hammer2_chain_rdata(hammer2_chain_t *chain)
5036 KKASSERT(chain->data != NULL);
5037 return (chain->data);
5040 hammer2_media_data_t *
5041 hammer2_chain_wdata(hammer2_chain_t *chain)
5043 KKASSERT(chain->data != NULL);
5044 return (chain->data);
5048 * Set the check data for a chain. This can be a heavy-weight operation
5049 * and typically only runs on-flush. For file data check data is calculated
5050 * when the logical buffers are flushed.
5052 void
5053 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5055 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5057 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5058 case HAMMER2_CHECK_NONE:
5059 break;
5060 case HAMMER2_CHECK_DISABLED:
5061 break;
5062 case HAMMER2_CHECK_ISCSI32:
5063 chain->bref.check.iscsi32.value =
5064 hammer2_icrc32(bdata, chain->bytes);
5065 break;
5066 case HAMMER2_CHECK_XXHASH64:
5067 chain->bref.check.xxhash64.value =
5068 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5069 break;
5070 case HAMMER2_CHECK_SHA192:
5072 SHA256_CTX hash_ctx;
5073 union {
5074 uint8_t digest[SHA256_DIGEST_LENGTH];
5075 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5076 } u;
5078 SHA256_Init(&hash_ctx);
5079 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5080 SHA256_Final(u.digest, &hash_ctx);
5081 u.digest64[2] ^= u.digest64[3];
5082 bcopy(u.digest,
5083 chain->bref.check.sha192.data,
5084 sizeof(chain->bref.check.sha192.data));
5086 break;
5087 case HAMMER2_CHECK_FREEMAP:
5088 chain->bref.check.freemap.icrc32 =
5089 hammer2_icrc32(bdata, chain->bytes);
5090 break;
5091 default:
5092 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5093 chain->bref.methods);
5094 break;
5099 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5101 uint32_t check32;
5102 uint64_t check64;
5103 int r;
5105 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5106 return 1;
5108 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5109 case HAMMER2_CHECK_NONE:
5110 r = 1;
5111 break;
5112 case HAMMER2_CHECK_DISABLED:
5113 r = 1;
5114 break;
5115 case HAMMER2_CHECK_ISCSI32:
5116 check32 = hammer2_icrc32(bdata, chain->bytes);
5117 r = (chain->bref.check.iscsi32.value == check32);
5118 if (r == 0) {
5119 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5120 "(flags=%08x, bref/data %08x/%08x)\n",
5121 chain->bref.data_off,
5122 chain->bref.type,
5123 chain->bref.methods,
5124 chain->flags,
5125 chain->bref.check.iscsi32.value,
5126 check32);
5128 hammer2_check_icrc32 += chain->bytes;
5129 break;
5130 case HAMMER2_CHECK_XXHASH64:
5131 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5132 r = (chain->bref.check.xxhash64.value == check64);
5133 if (r == 0) {
5134 kprintf("chain %016jx.%02x key=%016jx "
5135 "meth=%02x CHECK FAIL "
5136 "(flags=%08x, bref/data %016jx/%016jx)\n",
5137 chain->bref.data_off,
5138 chain->bref.type,
5139 chain->bref.key,
5140 chain->bref.methods,
5141 chain->flags,
5142 chain->bref.check.xxhash64.value,
5143 check64);
5145 hammer2_check_xxhash64 += chain->bytes;
5146 break;
5147 case HAMMER2_CHECK_SHA192:
5149 SHA256_CTX hash_ctx;
5150 union {
5151 uint8_t digest[SHA256_DIGEST_LENGTH];
5152 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5153 } u;
5155 SHA256_Init(&hash_ctx);
5156 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5157 SHA256_Final(u.digest, &hash_ctx);
5158 u.digest64[2] ^= u.digest64[3];
5159 if (bcmp(u.digest,
5160 chain->bref.check.sha192.data,
5161 sizeof(chain->bref.check.sha192.data)) == 0) {
5162 r = 1;
5163 } else {
5164 r = 0;
5165 kprintf("chain %016jx.%02x meth=%02x "
5166 "CHECK FAIL\n",
5167 chain->bref.data_off,
5168 chain->bref.type,
5169 chain->bref.methods);
5172 break;
5173 case HAMMER2_CHECK_FREEMAP:
5174 r = (chain->bref.check.freemap.icrc32 ==
5175 hammer2_icrc32(bdata, chain->bytes));
5176 if (r == 0) {
5177 kprintf("chain %016jx.%02x meth=%02x "
5178 "CHECK FAIL\n",
5179 chain->bref.data_off,
5180 chain->bref.type,
5181 chain->bref.methods);
5182 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5183 chain->bref.check.freemap.icrc32,
5184 hammer2_icrc32(bdata, chain->bytes),
5185 chain->bytes);
5186 if (chain->dio)
5187 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5188 chain->dio, chain->dio->bp->b_loffset,
5189 chain->dio->bp->b_bufsize, bdata,
5190 chain->dio->bp->b_data);
5193 break;
5194 default:
5195 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5196 chain->bref.methods);
5197 r = 1;
5198 break;
5200 return r;
5204 * Acquire the chain and parent representing the specified inode for the
5205 * device at the specified cluster index.
5207 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5209 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5210 * will be NULL. *parentp may still be set error or not, or NULL if the
5211 * parent itself could not be resolved.
5213 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5214 * *parentp and *chainp will be unlocked if not NULL.
5217 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5218 int clindex, int flags,
5219 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5221 hammer2_chain_t *parent;
5222 hammer2_chain_t *rchain;
5223 hammer2_key_t key_dummy;
5224 int cache_index = -1;
5225 int resolve_flags;
5227 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5228 HAMMER2_RESOLVE_SHARED : 0;
5231 * Caller expects us to replace these.
5233 if (*chainp) {
5234 hammer2_chain_unlock(*chainp);
5235 hammer2_chain_drop(*chainp);
5236 *chainp = NULL;
5238 if (*parentp) {
5239 hammer2_chain_unlock(*parentp);
5240 hammer2_chain_drop(*parentp);
5241 *parentp = NULL;
5245 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5246 * inodes from root directory entries in the key lookup).
5248 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5249 rchain = NULL;
5250 if (parent) {
5251 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5252 inum, inum,
5253 &cache_index, flags);
5255 *parentp = parent;
5256 *chainp = rchain;
5258 return (rchain ? 0 : EINVAL);
5262 * Used by the bulkscan code to snapshot the synchronized storage for
5263 * a volume, allowing it to be scanned concurrently against normal
5264 * operation.
5266 hammer2_chain_t *
5267 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5269 hammer2_chain_t *copy;
5271 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5272 copy->data = kmalloc(sizeof(copy->data->voldata),
5273 hmp->mchain,
5274 M_WAITOK | M_ZERO);
5275 hammer2_voldata_lock(hmp);
5276 copy->data->voldata = hmp->volsync;
5277 hammer2_voldata_unlock(hmp);
5279 return copy;
5282 void
5283 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5285 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5286 KKASSERT(copy->data);
5287 kfree(copy->data, copy->hmp->mchain);
5288 copy->data = NULL;
5289 atomic_add_long(&hammer2_chain_allocs, -1);
5290 hammer2_chain_drop(copy);
5294 * Create a snapshot of the specified (chain) with the specified label.
5295 * The originating hammer2_inode must be exclusively locked for
5296 * safety. The device's bulklk should be held by the caller. The caller
5297 * is responsible for synchronizing the filesystem to storage before
5298 * taking the snapshot.
5301 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5302 hammer2_tid_t mtid)
5304 hammer2_dev_t *hmp;
5305 const hammer2_inode_data_t *ripdata;
5306 hammer2_inode_data_t *wipdata;
5307 hammer2_chain_t *nchain;
5308 hammer2_inode_t *nip;
5309 size_t name_len;
5310 hammer2_key_t lhc;
5311 struct vattr vat;
5312 #if 0
5313 uuid_t opfs_clid;
5314 #endif
5315 int error;
5317 kprintf("snapshot %s\n", pmp->name);
5319 name_len = strlen(pmp->name);
5320 lhc = hammer2_dirhash(pmp->name, name_len);
5323 * Get the clid
5325 ripdata = &chain->data->ipdata;
5326 #if 0
5327 opfs_clid = ripdata->meta.pfs_clid;
5328 #endif
5329 hmp = chain->hmp;
5332 * Create the snapshot directory under the super-root
5334 * Set PFS type, generate a unique filesystem id, and generate
5335 * a cluster id. Use the same clid when snapshotting a PFS root,
5336 * which theoretically allows the snapshot to be used as part of
5337 * the same cluster (perhaps as a cache).
5339 * Copy the (flushed) blockref array. Theoretically we could use
5340 * chain_duplicate() but it becomes difficult to disentangle
5341 * the shared core so for now just brute-force it.
5343 VATTR_NULL(&vat);
5344 vat.va_type = VDIR;
5345 vat.va_mode = 0755;
5346 hammer2_chain_unlock(chain);
5347 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5348 &vat, proc0.p_ucred,
5349 pmp->name, name_len, 0,
5350 1, 0, 0,
5351 HAMMER2_INSERT_PFSROOT, &error);
5352 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5354 if (nip) {
5355 hammer2_inode_modify(nip);
5356 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5357 hammer2_chain_modify(nchain, mtid, 0, 0);
5358 wipdata = &nchain->data->ipdata;
5360 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5361 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5362 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5363 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5366 * Give the snapshot its own private cluster id. As a
5367 * snapshot no further synchronization with the original
5368 * cluster will be done.
5370 #if 0
5371 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5372 nip->meta.pfs_clid = opfs_clid;
5373 else
5374 kern_uuidgen(&nip->meta.pfs_clid, 1);
5375 #endif
5376 kern_uuidgen(&nip->meta.pfs_clid, 1);
5377 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5379 /* XXX hack blockset copy */
5380 /* XXX doesn't work with real cluster */
5381 wipdata->meta = nip->meta;
5382 wipdata->u.blockset = ripdata->u.blockset;
5384 hammer2_flush(nchain, 1);
5385 KKASSERT(wipdata == &nchain->data->ipdata);
5386 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5388 hammer2_chain_unlock(nchain);
5389 hammer2_chain_drop(nchain);
5390 hammer2_inode_chain_sync(nip);
5391 hammer2_inode_unlock(nip);
5392 hammer2_inode_run_sideq(hmp->spmp);
5394 return (error);
5398 * Returns non-zero if the chain (INODE or DIRENT) matches the
5399 * filename.
5402 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5403 size_t name_len)
5405 const hammer2_inode_data_t *ripdata;
5406 const hammer2_dirent_head_t *den;
5408 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5409 ripdata = &chain->data->ipdata;
5410 if (ripdata->meta.name_len == name_len &&
5411 bcmp(ripdata->filename, name, name_len) == 0) {
5412 return 1;
5415 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5416 chain->bref.embed.dirent.namlen == name_len) {
5417 den = &chain->bref.embed.dirent;
5418 if (name_len > sizeof(chain->bref.check.buf) &&
5419 bcmp(chain->data->buf, name, name_len) == 0) {
5420 return 1;
5422 if (name_len <= sizeof(chain->bref.check.buf) &&
5423 bcmp(chain->bref.check.buf, name, name_len) == 0) {
5424 return 1;
5427 return 0;