hammer2 - Fix bulkfree bug, Fix chain->parent bug, refactor dedup a bit
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
blob1c5288fb2786ad05609364bf7ef500360b13bb00
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 #if 1
90 #define TIMER(which)
91 #else
92 extern int h2timer[32];
93 extern int h2last;
94 extern int h2lid;
96 #define TIMER(which) do { \
97 if (h2last) \
98 h2timer[h2lid] += (int)(ticks - h2last);\
99 h2last = ticks; \
100 h2lid = which; \
101 } while(0)
102 #endif
105 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
107 hammer2_key_t c1_beg;
108 hammer2_key_t c1_end;
109 hammer2_key_t c2_beg;
110 hammer2_key_t c2_end;
113 * Compare chains. Overlaps are not supposed to happen and catch
114 * any software issues early we count overlaps as a match.
116 c1_beg = chain1->bref.key;
117 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
118 c2_beg = chain2->bref.key;
119 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
121 if (c1_end < c2_beg) /* fully to the left */
122 return(-1);
123 if (c1_beg > c2_end) /* fully to the right */
124 return(1);
125 return(0); /* overlap (must not cross edge boundary) */
129 * Assert that a chain has no media data associated with it.
131 static __inline void
132 hammer2_chain_assert_no_data(hammer2_chain_t *chain)
134 KKASSERT(chain->dio == NULL);
135 if (chain->bref.type != HAMMER2_BREF_TYPE_VOLUME &&
136 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP &&
137 chain->data) {
138 panic("hammer2_assert_no_data: chain %p still has data", chain);
143 * Make a chain visible to the flusher. The flusher needs to be able to
144 * do flushes of subdirectory chains or single files so it does a top-down
145 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
146 * or UPDATE chains and flushes back up the chain to the volume root.
148 * This routine sets ONFLUSH upward until it hits the volume root. For
149 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
150 * Extra ONFLUSH flagging doesn't hurt the filesystem.
152 void
153 hammer2_chain_setflush(hammer2_chain_t *chain)
155 hammer2_chain_t *parent;
157 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
158 hammer2_spin_sh(&chain->core.spin);
159 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
160 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
161 if ((parent = chain->parent) == NULL)
162 break;
163 hammer2_spin_sh(&parent->core.spin);
164 hammer2_spin_unsh(&chain->core.spin);
165 chain = parent;
167 hammer2_spin_unsh(&chain->core.spin);
172 * Allocate a new disconnected chain element representing the specified
173 * bref. chain->refs is set to 1 and the passed bref is copied to
174 * chain->bref. chain->bytes is derived from the bref.
176 * chain->pmp inherits pmp unless the chain is an inode (other than the
177 * super-root inode).
179 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
181 hammer2_chain_t *
182 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
183 hammer2_blockref_t *bref)
185 hammer2_chain_t *chain;
186 u_int bytes;
189 * Special case - radix of 0 indicates a chain that does not
190 * need a data reference (context is completely embedded in the
191 * bref).
193 if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
194 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
195 else
196 bytes = 0;
198 atomic_add_long(&hammer2_chain_allocs, 1);
201 * Construct the appropriate system structure.
203 switch(bref->type) {
204 case HAMMER2_BREF_TYPE_DIRENT:
205 case HAMMER2_BREF_TYPE_INODE:
206 case HAMMER2_BREF_TYPE_INDIRECT:
207 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
208 case HAMMER2_BREF_TYPE_DATA:
209 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
211 * Chain's are really only associated with the hmp but we
212 * maintain a pmp association for per-mount memory tracking
213 * purposes. The pmp can be NULL.
215 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
216 break;
217 case HAMMER2_BREF_TYPE_VOLUME:
218 case HAMMER2_BREF_TYPE_FREEMAP:
220 * Only hammer2_chain_bulksnap() calls this function with these
221 * types.
223 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
224 break;
225 default:
226 chain = NULL;
227 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
228 bref->type);
232 * Initialize the new chain structure. pmp must be set to NULL for
233 * chains belonging to the super-root topology of a device mount.
235 if (pmp == hmp->spmp)
236 chain->pmp = NULL;
237 else
238 chain->pmp = pmp;
239 chain->hmp = hmp;
240 chain->bref = *bref;
241 chain->bytes = bytes;
242 chain->refs = 1;
243 chain->flags = HAMMER2_CHAIN_ALLOCATED;
246 * Set the PFS boundary flag if this chain represents a PFS root.
248 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
249 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
250 hammer2_chain_core_init(chain);
252 return (chain);
256 * Initialize a chain's core structure. This structure used to be allocated
257 * but is now embedded.
259 * The core is not locked. No additional refs on the chain are made.
260 * (trans) must not be NULL if (core) is not NULL.
262 void
263 hammer2_chain_core_init(hammer2_chain_t *chain)
266 * Fresh core under nchain (no multi-homing of ochain's
267 * sub-tree).
269 RB_INIT(&chain->core.rbtree); /* live chains */
270 hammer2_mtx_init(&chain->lock, "h2chain");
274 * Add a reference to a chain element, preventing its destruction.
276 * (can be called with spinlock held)
278 void
279 hammer2_chain_ref(hammer2_chain_t *chain)
281 if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
283 * 0->non-zero transition must ensure that chain is removed
284 * from the LRU list.
286 * NOTE: Already holding lru_spin here so we cannot call
287 * hammer2_chain_ref() to get it off lru_list, do
288 * it manually.
290 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
291 hammer2_pfs_t *pmp = chain->pmp;
292 hammer2_spin_ex(&pmp->lru_spin);
293 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
294 atomic_add_int(&pmp->lru_count, -1);
295 atomic_clear_int(&chain->flags,
296 HAMMER2_CHAIN_ONLRU);
297 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
299 hammer2_spin_unex(&pmp->lru_spin);
302 #if 0
303 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
304 print_backtrace(8);
305 #endif
309 * Ref a locked chain and force the data to be held across an unlock.
310 * Chain must be currently locked. The user of the chain who desires
311 * to release the hold must call hammer2_chain_lock_unhold() to relock
312 * and unhold the chain, then unlock normally, or may simply call
313 * hammer2_chain_drop_unhold() (which is safer against deadlocks).
315 void
316 hammer2_chain_ref_hold(hammer2_chain_t *chain)
318 atomic_add_int(&chain->lockcnt, 1);
319 hammer2_chain_ref(chain);
323 * Insert the chain in the core rbtree.
325 * Normal insertions are placed in the live rbtree. Insertion of a deleted
326 * chain is a special case used by the flush code that is placed on the
327 * unstaged deleted list to avoid confusing the live view.
329 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
330 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
331 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
333 static
335 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
336 int flags, int generation)
338 hammer2_chain_t *xchain;
339 int error = 0;
341 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
342 hammer2_spin_ex(&parent->core.spin);
345 * Interlocked by spinlock, check for race
347 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
348 parent->core.generation != generation) {
349 error = EAGAIN;
350 goto failed;
354 * Insert chain
356 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
357 KASSERT(xchain == NULL,
358 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
359 chain, xchain, chain->bref.key));
360 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
361 chain->parent = parent;
362 ++parent->core.chain_count;
363 ++parent->core.generation; /* XXX incs for _get() too, XXX */
366 * We have to keep track of the effective live-view blockref count
367 * so the create code knows when to push an indirect block.
369 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
370 atomic_add_int(&parent->core.live_count, 1);
371 failed:
372 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
373 hammer2_spin_unex(&parent->core.spin);
374 return error;
378 * Drop the caller's reference to the chain. When the ref count drops to
379 * zero this function will try to disassociate the chain from its parent and
380 * deallocate it, then recursely drop the parent using the implied ref
381 * from the chain's chain->parent.
383 * Nobody should own chain's mutex on the 1->0 transition, unless this drop
384 * races an acquisition by another cpu. Therefore we can loop if we are
385 * unable to acquire the mutex, and refs is unlikely to be 1 unless we again
386 * race against another drop.
388 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
390 void
391 hammer2_chain_drop(hammer2_chain_t *chain)
393 u_int refs;
395 if (hammer2_debug & 0x200000)
396 Debugger("drop");
397 #if 0
398 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
399 print_backtrace(8);
400 #endif
402 KKASSERT(chain->refs > 0);
404 while (chain) {
405 refs = chain->refs;
406 cpu_ccfence();
407 KKASSERT(refs > 0);
409 if (refs == 1) {
410 if (mtx_lock_ex_try(&chain->lock) == 0)
411 chain = hammer2_chain_lastdrop(chain);
412 /* retry the same chain */
413 } else {
414 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
415 break;
416 /* retry the same chain */
418 cpu_pause();
423 * Unhold a held and probably not-locked chain, ensure that the data is
424 * dropped on the 1->0 transition of lockcnt by obtaining an exclusive
425 * lock and then simply unlocking the chain.
427 void
428 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
430 u_int lockcnt;
431 int iter = 0;
433 for (;;) {
434 lockcnt = chain->lockcnt;
435 cpu_ccfence();
436 if (lockcnt > 1) {
437 if (atomic_cmpset_int(&chain->lockcnt,
438 lockcnt, lockcnt - 1)) {
439 break;
441 } else if (mtx_lock_ex_try(&chain->lock) == 0) {
442 hammer2_chain_unlock(chain);
443 break;
444 } else {
446 * This situation can easily occur on SMP due to
447 * the gap inbetween the 1->0 transition and the
448 * final unlock. We cannot safely block on the
449 * mutex because lockcnt might go above 1.
451 * XXX Sleep for one tick if it takes too long.
453 if (++iter > 1000) {
454 if (iter > 1000 + hz) {
455 kprintf("hammer2: h2race1 %p\n", chain);
456 iter = 1000;
458 tsleep(&iter, 0, "h2race1", 1);
460 cpu_pause();
463 hammer2_chain_drop(chain);
467 * Handles the (potential) last drop of chain->refs from 1->0. Called with
468 * the mutex exclusively locked, refs == 1, and lockcnt 0. SMP races are
469 * possible against refs and lockcnt. We must dispose of the mutex on chain.
471 * This function returns an unlocked chain for recursive drop or NULL. It
472 * can return the same chain if it determines it has raced another ref.
474 * --
476 * When two chains need to be recursively dropped we use the chain we
477 * would otherwise free to placehold the additional chain. It's a bit
478 * convoluted but we can't just recurse without potentially blowing out
479 * the kernel stack.
481 * The chain cannot be freed if it has any children.
482 * The chain cannot be freed if flagged MODIFIED unless we can dispose of it.
483 * The chain cannot be freed if flagged UPDATE unless we can dispose of it.
484 * Any dedup registration can remain intact.
486 * The core spinlock is allowed to nest child-to-parent (not parent-to-child).
488 static
489 hammer2_chain_t *
490 hammer2_chain_lastdrop(hammer2_chain_t *chain)
492 hammer2_pfs_t *pmp;
493 hammer2_dev_t *hmp;
494 hammer2_chain_t *parent;
495 hammer2_chain_t *rdrop;
496 #if 0
497 hammer2_io_t *dio;
498 #endif
500 #if 0
502 * On last drop if there is no parent and data_off is good (at
503 * least does not represent the volume root), the modified chain
504 * is probably going to be destroyed. We have to make sure that
505 * the data area is not registered for dedup.
507 * XXX removed. In fact, we do not have to make sure that the
508 * data area is not registered for dedup. The data area
509 * can, in fact, still be used for dedup because it is
510 * still allocated in the freemap and the underlying I/O
511 * will still be flushed.
513 if (chain->parent == NULL &&
514 (chain->flags & HAMMER2_CHAIN_MODIFIED) &&
515 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
516 hmp = chain->hmp;
517 hammer2_io_dedup_delete(hmp, chain->bref.type,
518 chain->bref.data_off, chain->bytes);
520 #endif
522 * We need chain's spinlock to interlock the sub-tree test.
523 * We already have chain's mutex, protecting chain->parent.
525 * Remember that chain->refs can be in flux.
527 hammer2_spin_ex(&chain->core.spin);
529 if ((parent = chain->parent) != NULL) {
531 * If the chain has a parent the UPDATE bit prevents scrapping
532 * as the chain is needed to properly flush the parent. Try
533 * to complete the 1->0 transition and return NULL. Retry
534 * (return chain) if we are unable to complete the 1->0
535 * transition, else return NULL (nothing more to do).
537 * If the chain has a parent the MODIFIED bit prevents
538 * scrapping.
540 * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
542 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
543 HAMMER2_CHAIN_MODIFIED)) {
544 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
545 hammer2_spin_unex(&chain->core.spin);
546 #if 0
547 dio = hammer2_chain_drop_data(chain, 0);
548 if (dio)
549 hammer2_io_bqrelse(&dio);
550 #endif
551 hammer2_chain_assert_no_data(chain);
552 hammer2_mtx_unlock(&chain->lock);
553 chain = NULL;
554 } else {
555 hammer2_spin_unex(&chain->core.spin);
556 hammer2_mtx_unlock(&chain->lock);
558 return (chain);
560 /* spinlock still held */
561 } else {
563 * The chain has no parent and can be flagged for destruction.
564 * Since it has no parent, UPDATE can also be cleared.
566 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
567 if (chain->flags & HAMMER2_CHAIN_UPDATE)
568 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
571 * If the chain has children we must still flush the chain.
572 * Any dedup is already handled by the underlying DIO, so
573 * we do not have to specifically flush it here.
575 * In the case where it has children, the DESTROY flag test
576 * in the flush code will prevent unnecessary flushes of
577 * MODIFIED chains that are not flagged DEDUP so don't worry
578 * about that here.
580 if (chain->core.chain_count) {
582 * Put on flushq (should ensure refs > 1), retry
583 * the drop.
585 hammer2_spin_unex(&chain->core.spin);
586 hammer2_delayed_flush(chain);
587 hammer2_mtx_unlock(&chain->lock);
589 return(chain); /* retry drop */
593 * Otherwise we can scrap the MODIFIED bit if it is set,
594 * and continue along the freeing path.
596 * Be sure to clean-out any dedup bits. Without a parent
597 * this chain will no longer be visible to the flush code.
598 * Easy check data_off to avoid the volume root.
600 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
601 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
602 atomic_add_long(&hammer2_count_modified_chains, -1);
603 if (chain->pmp)
604 hammer2_pfs_memory_wakeup(chain->pmp);
606 /* spinlock still held */
609 /* spinlock still held */
610 #if 0
611 dio = NULL;
612 #endif
615 * If any children exist we must leave the chain intact with refs == 0.
616 * They exist because chains are retained below us which have refs or
617 * may require flushing.
619 * Retry (return chain) if we fail to transition the refs to 0, else
620 * return NULL indication nothing more to do.
622 * Chains with children are NOT put on the LRU list.
624 if (chain->core.chain_count) {
625 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
626 hammer2_spin_unex(&chain->core.spin);
627 hammer2_chain_assert_no_data(chain);
628 hammer2_mtx_unlock(&chain->lock);
629 chain = NULL;
630 } else {
631 hammer2_spin_unex(&chain->core.spin);
632 hammer2_mtx_unlock(&chain->lock);
634 return (chain);
636 /* spinlock still held */
637 /* no chains left under us */
640 * chain->core has no children left so no accessors can get to our
641 * chain from there. Now we have to lock the parent core to interlock
642 * remaining possible accessors that might bump chain's refs before
643 * we can safely drop chain's refs with intent to free the chain.
645 hmp = chain->hmp;
646 pmp = chain->pmp; /* can be NULL */
647 rdrop = NULL;
649 parent = chain->parent;
652 * WARNING! chain's spin lock is still held here, and other spinlocks
653 * will be acquired and released in the code below. We
654 * cannot be making fancy procedure calls!
658 * We can cache the chain if it is associated with a pmp
659 * and not flagged as being destroyed or requesting a full
660 * release. In this situation the chain is not removed
661 * from its parent, i.e. it can still be looked up.
663 * We intentionally do not cache DATA chains because these
664 * were likely used to load data into the logical buffer cache
665 * and will not be accessed again for some time.
667 if ((chain->flags &
668 (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
669 chain->pmp &&
670 chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
671 if (parent)
672 hammer2_spin_ex(&parent->core.spin);
673 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
675 * 1->0 transition failed, retry. Do not drop
676 * the chain's data yet!
678 if (parent)
679 hammer2_spin_unex(&parent->core.spin);
680 hammer2_spin_unex(&chain->core.spin);
681 hammer2_mtx_unlock(&chain->lock);
683 return(chain);
687 * Success
689 #if 0
690 dio = hammer2_chain_drop_data(chain, 1);
691 #endif
692 hammer2_chain_assert_no_data(chain);
694 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
695 hammer2_spin_ex(&pmp->lru_spin);
696 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
697 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
700 * If we are over the LRU limit we need to drop something.
702 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
703 rdrop = TAILQ_FIRST(&pmp->lru_list);
704 atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
705 TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
706 atomic_add_int(&rdrop->refs, 1);
707 atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
708 } else {
709 atomic_add_int(&pmp->lru_count, 1);
711 hammer2_spin_unex(&pmp->lru_spin);
712 if (parent) {
713 hammer2_spin_unex(&parent->core.spin);
714 parent = NULL; /* safety */
716 hammer2_spin_unex(&chain->core.spin);
717 hammer2_mtx_unlock(&chain->lock);
718 #if 0
719 if (dio)
720 hammer2_io_bqrelse(&dio);
721 #endif
723 return rdrop;
724 /* NOT REACHED */
728 * Spinlock the parent and try to drop the last ref on chain.
729 * On success determine if we should dispose of the chain
730 * (remove the chain from its parent, etc).
732 * (normal core locks are top-down recursive but we define
733 * core spinlocks as bottom-up recursive, so this is safe).
735 if (parent) {
736 hammer2_spin_ex(&parent->core.spin);
737 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
738 #if 0
739 /* XXX remove, don't try to drop data on fail */
740 hammer2_spin_unex(&parent->core.spin);
741 dio = hammer2_chain_drop_data(chain, 0);
742 hammer2_spin_unex(&chain->core.spin);
743 if (dio)
744 hammer2_io_bqrelse(&dio);
745 #endif
747 * 1->0 transition failed, retry.
749 hammer2_spin_unex(&parent->core.spin);
750 hammer2_spin_unex(&chain->core.spin);
751 hammer2_mtx_unlock(&chain->lock);
753 return(chain);
757 * 1->0 transition successful, parent spin held to prevent
758 * new lookups, chain spinlock held to protect parent field.
759 * Remove chain from the parent.
761 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
762 RB_REMOVE(hammer2_chain_tree,
763 &parent->core.rbtree, chain);
764 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
765 --parent->core.chain_count;
766 chain->parent = NULL;
770 * If our chain was the last chain in the parent's core the
771 * core is now empty and its parent might have to be
772 * re-dropped if it has 0 refs.
774 if (parent->core.chain_count == 0) {
775 rdrop = parent;
776 atomic_add_int(&rdrop->refs, 1);
778 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
779 rdrop = NULL;
782 hammer2_spin_unex(&parent->core.spin);
783 parent = NULL; /* safety */
784 /* FALL THROUGH */
785 } else {
787 * No-parent case.
789 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
791 * 1->0 transition failed, retry.
793 hammer2_spin_unex(&parent->core.spin);
794 hammer2_spin_unex(&chain->core.spin);
795 hammer2_mtx_unlock(&chain->lock);
797 return(chain);
802 * Successful 1->0 transition, no parent, no children... no way for
803 * anyone to ref this chain any more. We can clean-up and free it.
805 * We still have the core spinlock, and core's chain_count is 0.
806 * Any parent spinlock is gone.
808 hammer2_spin_unex(&chain->core.spin);
809 hammer2_chain_assert_no_data(chain);
810 hammer2_mtx_unlock(&chain->lock);
811 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
812 chain->core.chain_count == 0);
815 * All locks are gone, no pointers remain to the chain, finish
816 * freeing it.
818 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
819 HAMMER2_CHAIN_MODIFIED)) == 0);
820 #if 0
821 dio = hammer2_chain_drop_data(chain, 1);
822 if (dio)
823 hammer2_io_bqrelse(&dio);
824 #endif
827 * Once chain resources are gone we can use the now dead chain
828 * structure to placehold what might otherwise require a recursive
829 * drop, because we have potentially two things to drop and can only
830 * return one directly.
832 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
833 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
834 chain->hmp = NULL;
835 kfree(chain, hmp->mchain);
839 * Possible chaining loop when parent re-drop needed.
841 return(rdrop);
845 * On last lock release.
847 static hammer2_io_t *
848 hammer2_chain_drop_data(hammer2_chain_t *chain)
850 hammer2_io_t *dio;
852 if ((dio = chain->dio) != NULL) {
853 chain->dio = NULL;
854 chain->data = NULL;
855 } else {
856 switch(chain->bref.type) {
857 case HAMMER2_BREF_TYPE_VOLUME:
858 case HAMMER2_BREF_TYPE_FREEMAP:
859 break;
860 default:
861 if (chain->data != NULL) {
862 hammer2_spin_unex(&chain->core.spin);
863 panic("chain data not null: "
864 "chain %p bref %016jx.%02x "
865 "refs %d parent %p dio %p data %p",
866 chain, chain->bref.data_off,
867 chain->bref.type, chain->refs,
868 chain->parent,
869 chain->dio, chain->data);
871 KKASSERT(chain->data == NULL);
872 break;
875 return dio;
879 * Lock a referenced chain element, acquiring its data with I/O if necessary,
880 * and specify how you would like the data to be resolved.
882 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
884 * The lock is allowed to recurse, multiple locking ops will aggregate
885 * the requested resolve types. Once data is assigned it will not be
886 * removed until the last unlock.
888 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
889 * (typically used to avoid device/logical buffer
890 * aliasing for data)
892 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
893 * the INITIAL-create state (indirect blocks only).
895 * Do not resolve data elements for DATA chains.
896 * (typically used to avoid device/logical buffer
897 * aliasing for data)
899 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
901 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
902 * it will be locked exclusive.
904 * NOTE: Embedded elements (volume header, inodes) are always resolved
905 * regardless.
907 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
908 * element will instantiate and zero its buffer, and flush it on
909 * release.
911 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
912 * so as not to instantiate a device buffer, which could alias against
913 * a logical file buffer. However, if ALWAYS is specified the
914 * device buffer will be instantiated anyway.
916 * WARNING! This function blocks on I/O if data needs to be fetched. This
917 * blocking can run concurrent with other compatible lock holders
918 * who do not need data returning. The lock is not upgraded to
919 * exclusive during a data fetch, a separate bit is used to
920 * interlock I/O. However, an exclusive lock holder can still count
921 * on being interlocked against an I/O fetch managed by a shared
922 * lock holder.
924 void
925 hammer2_chain_lock(hammer2_chain_t *chain, int how)
928 * Ref and lock the element. Recursive locks are allowed.
930 KKASSERT(chain->refs > 0);
931 atomic_add_int(&chain->lockcnt, 1);
933 TIMER(20);
936 * Get the appropriate lock. If LOCKAGAIN is flagged with SHARED
937 * the caller expects a shared lock to already be present and we
938 * are giving it another ref. This case must importantly not block
939 * if there is a pending exclusive lock request.
941 if (how & HAMMER2_RESOLVE_SHARED) {
942 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
943 hammer2_mtx_sh_again(&chain->lock);
944 } else {
945 hammer2_mtx_sh(&chain->lock);
947 } else {
948 hammer2_mtx_ex(&chain->lock);
950 ++curthread->td_tracker;
951 TIMER(21);
954 * If we already have a valid data pointer no further action is
955 * necessary.
957 if (chain->data)
958 return;
959 TIMER(22);
962 * Do we have to resolve the data? This is generally only
963 * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
964 * Other BREF types expects the data to be there.
966 switch(how & HAMMER2_RESOLVE_MASK) {
967 case HAMMER2_RESOLVE_NEVER:
968 return;
969 case HAMMER2_RESOLVE_MAYBE:
970 if (chain->flags & HAMMER2_CHAIN_INITIAL)
971 return;
972 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
973 return;
974 #if 0
975 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
976 return;
977 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
978 return;
979 #endif
980 /* fall through */
981 case HAMMER2_RESOLVE_ALWAYS:
982 default:
983 break;
987 * Caller requires data
989 hammer2_chain_load_data(chain);
993 * Lock the chain, retain the hold, and drop the data persistence count.
994 * The data should remain valid because we never transitioned lockcnt
995 * through 0.
997 void
998 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
1000 hammer2_chain_lock(chain, how);
1001 atomic_add_int(&chain->lockcnt, -1);
1004 #if 0
1006 * Downgrade an exclusive chain lock to a shared chain lock.
1008 * NOTE: There is no upgrade equivalent due to the ease of
1009 * deadlocks in that direction.
1011 void
1012 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
1014 hammer2_mtx_downgrade(&chain->lock);
1016 #endif
1018 #if 0
1020 * Obtains a second shared lock on the chain, does not account the second
1021 * shared lock as being owned by the current thread.
1023 * Caller must already own a shared lock on this chain.
1025 * The lock function is required to obtain the second shared lock without
1026 * blocking on pending exclusive requests.
1028 void
1029 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
1031 hammer2_mtx_sh_again(&chain->lock);
1032 atomic_add_int(&chain->lockcnt, 1);
1033 /* do not count in td_tracker for this thread */
1037 * Accounts for a shared lock that was pushed to us as being owned by our
1038 * thread.
1040 void
1041 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
1043 ++curthread->td_tracker;
1045 #endif
1048 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
1049 * may be of any type.
1051 * Once chain->data is set it cannot be disposed of until all locks are
1052 * released.
1054 void
1055 hammer2_chain_load_data(hammer2_chain_t *chain)
1057 hammer2_blockref_t *bref;
1058 hammer2_dev_t *hmp;
1059 hammer2_io_t *dio;
1060 char *bdata;
1061 int error;
1064 * Degenerate case, data already present, or chain is not expected
1065 * to have any data.
1067 if (chain->data)
1068 return;
1069 if ((chain->bref.data_off & HAMMER2_OFF_MASK_RADIX) == 0)
1070 return;
1071 TIMER(23);
1073 hmp = chain->hmp;
1074 KKASSERT(hmp != NULL);
1077 * Gain the IOINPROG bit, interlocked block.
1079 for (;;) {
1080 u_int oflags;
1081 u_int nflags;
1083 oflags = chain->flags;
1084 cpu_ccfence();
1085 if (oflags & HAMMER2_CHAIN_IOINPROG) {
1086 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
1087 tsleep_interlock(&chain->flags, 0);
1088 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1089 tsleep(&chain->flags, PINTERLOCKED,
1090 "h2iocw", 0);
1092 /* retry */
1093 } else {
1094 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
1095 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1096 break;
1098 /* retry */
1101 TIMER(24);
1104 * We own CHAIN_IOINPROG
1106 * Degenerate case if we raced another load.
1108 if (chain->data)
1109 goto done;
1112 * We must resolve to a device buffer, either by issuing I/O or
1113 * by creating a zero-fill element. We do not mark the buffer
1114 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1115 * API must still be used to do that).
1117 * The device buffer is variable-sized in powers of 2 down
1118 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1119 * chunk always contains buffers of the same size. (XXX)
1121 * The minimum physical IO size may be larger than the variable
1122 * block size.
1124 bref = &chain->bref;
1127 * The getblk() optimization can only be used on newly created
1128 * elements if the physical block size matches the request.
1130 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1131 error = hammer2_io_new(hmp, bref->type,
1132 bref->data_off, chain->bytes,
1133 &chain->dio);
1134 } else {
1135 error = hammer2_io_bread(hmp, bref->type,
1136 bref->data_off, chain->bytes,
1137 &chain->dio);
1138 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1140 TIMER(25);
1141 if (error) {
1142 chain->error = HAMMER2_ERROR_IO;
1143 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1144 (intmax_t)bref->data_off, error);
1145 hammer2_io_bqrelse(&chain->dio);
1146 goto done;
1148 chain->error = 0;
1151 * This isn't perfect and can be ignored on OSs which do not have
1152 * an indication as to whether a buffer is coming from cache or
1153 * if I/O was actually issued for the read. TESTEDGOOD will work
1154 * pretty well without the B_IOISSUED logic because chains are
1155 * cached.
1157 * If the underlying kernel buffer covers the entire chain we can
1158 * use the B_IOISSUED indication to determine if we have to re-run
1159 * the CRC on chain data for chains that managed to stay cached
1160 * across the kernel disposal of the original buffer.
1162 if ((dio = chain->dio) != NULL && dio->bp) {
1163 struct buf *bp = dio->bp;
1165 if (dio->psize == chain->bytes &&
1166 (bp->b_flags & B_IOISSUED)) {
1167 atomic_clear_int(&chain->flags,
1168 HAMMER2_CHAIN_TESTEDGOOD);
1169 bp->b_flags &= ~B_IOISSUED;
1174 * NOTE: A locked chain's data cannot be modified without first
1175 * calling hammer2_chain_modify().
1179 * Clear INITIAL. In this case we used io_new() and the buffer has
1180 * been zero'd and marked dirty.
1182 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1184 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1185 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1186 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1187 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1189 * check data not currently synchronized due to
1190 * modification. XXX assumes data stays in the buffer
1191 * cache, which might not be true (need biodep on flush
1192 * to calculate crc? or simple crc?).
1194 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1195 TIMER(26);
1196 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1197 chain->error = HAMMER2_ERROR_CHECK;
1198 } else {
1199 atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1202 TIMER(27);
1205 * Setup the data pointer, either pointing it to an embedded data
1206 * structure and copying the data from the buffer, or pointing it
1207 * into the buffer.
1209 * The buffer is not retained when copying to an embedded data
1210 * structure in order to avoid potential deadlocks or recursions
1211 * on the same physical buffer.
1213 * WARNING! Other threads can start using the data the instant we
1214 * set chain->data non-NULL.
1216 switch (bref->type) {
1217 case HAMMER2_BREF_TYPE_VOLUME:
1218 case HAMMER2_BREF_TYPE_FREEMAP:
1220 * Copy data from bp to embedded buffer
1222 panic("hammer2_chain_load_data: unresolved volume header");
1223 break;
1224 case HAMMER2_BREF_TYPE_DIRENT:
1225 KKASSERT(chain->bytes != 0);
1226 /* fall through */
1227 case HAMMER2_BREF_TYPE_INODE:
1228 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1229 case HAMMER2_BREF_TYPE_INDIRECT:
1230 case HAMMER2_BREF_TYPE_DATA:
1231 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1232 default:
1234 * Point data at the device buffer and leave dio intact.
1236 chain->data = (void *)bdata;
1237 break;
1241 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1243 done:
1244 for (;;) {
1245 u_int oflags;
1246 u_int nflags;
1248 oflags = chain->flags;
1249 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1250 HAMMER2_CHAIN_IOSIGNAL);
1251 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1252 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1253 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1254 wakeup(&chain->flags);
1255 break;
1258 TIMER(28);
1262 * Unlock and deref a chain element.
1264 * Remember that the presence of children under chain prevent the chain's
1265 * destruction but do not add additional references, so the dio will still
1266 * be dropped.
1268 void
1269 hammer2_chain_unlock(hammer2_chain_t *chain)
1271 hammer2_io_t *dio;
1272 u_int lockcnt;
1273 int iter = 0;
1275 --curthread->td_tracker;
1278 * If multiple locks are present (or being attempted) on this
1279 * particular chain we can just unlock, drop refs, and return.
1281 * Otherwise fall-through on the 1->0 transition.
1283 for (;;) {
1284 lockcnt = chain->lockcnt;
1285 KKASSERT(lockcnt > 0);
1286 cpu_ccfence();
1287 if (lockcnt > 1) {
1288 if (atomic_cmpset_int(&chain->lockcnt,
1289 lockcnt, lockcnt - 1)) {
1290 hammer2_mtx_unlock(&chain->lock);
1291 return;
1293 } else if (hammer2_mtx_upgrade_try(&chain->lock) == 0) {
1294 /* while holding the mutex exclusively */
1295 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1296 break;
1297 } else {
1299 * This situation can easily occur on SMP due to
1300 * the gap inbetween the 1->0 transition and the
1301 * final unlock. We cannot safely block on the
1302 * mutex because lockcnt might go above 1.
1304 * XXX Sleep for one tick if it takes too long.
1306 if (++iter > 1000) {
1307 if (iter > 1000 + hz) {
1308 kprintf("hammer2: h2race2 %p\n", chain);
1309 iter = 1000;
1311 tsleep(&iter, 0, "h2race2", 1);
1313 cpu_pause();
1315 /* retry */
1319 * Last unlock / mutex upgraded to exclusive. Drop the data
1320 * reference.
1322 dio = hammer2_chain_drop_data(chain);
1323 if (dio)
1324 hammer2_io_bqrelse(&dio);
1325 hammer2_mtx_unlock(&chain->lock);
1329 * Unlock and hold chain data intact
1331 void
1332 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1334 atomic_add_int(&chain->lockcnt, 1);
1335 hammer2_chain_unlock(chain);
1339 * Helper to obtain the blockref[] array base and count for a chain.
1341 * XXX Not widely used yet, various use cases need to be validated and
1342 * converted to use this function.
1344 static
1345 hammer2_blockref_t *
1346 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1348 hammer2_blockref_t *base;
1349 int count;
1351 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1352 base = NULL;
1354 switch(parent->bref.type) {
1355 case HAMMER2_BREF_TYPE_INODE:
1356 count = HAMMER2_SET_COUNT;
1357 break;
1358 case HAMMER2_BREF_TYPE_INDIRECT:
1359 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1360 count = parent->bytes / sizeof(hammer2_blockref_t);
1361 break;
1362 case HAMMER2_BREF_TYPE_VOLUME:
1363 count = HAMMER2_SET_COUNT;
1364 break;
1365 case HAMMER2_BREF_TYPE_FREEMAP:
1366 count = HAMMER2_SET_COUNT;
1367 break;
1368 default:
1369 panic("hammer2_chain_create_indirect: "
1370 "unrecognized blockref type: %d",
1371 parent->bref.type);
1372 count = 0;
1373 break;
1375 } else {
1376 switch(parent->bref.type) {
1377 case HAMMER2_BREF_TYPE_INODE:
1378 base = &parent->data->ipdata.u.blockset.blockref[0];
1379 count = HAMMER2_SET_COUNT;
1380 break;
1381 case HAMMER2_BREF_TYPE_INDIRECT:
1382 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1383 base = &parent->data->npdata[0];
1384 count = parent->bytes / sizeof(hammer2_blockref_t);
1385 break;
1386 case HAMMER2_BREF_TYPE_VOLUME:
1387 base = &parent->data->voldata.
1388 sroot_blockset.blockref[0];
1389 count = HAMMER2_SET_COUNT;
1390 break;
1391 case HAMMER2_BREF_TYPE_FREEMAP:
1392 base = &parent->data->blkset.blockref[0];
1393 count = HAMMER2_SET_COUNT;
1394 break;
1395 default:
1396 panic("hammer2_chain_create_indirect: "
1397 "unrecognized blockref type: %d",
1398 parent->bref.type);
1399 count = 0;
1400 break;
1403 *countp = count;
1405 return base;
1409 * This counts the number of live blockrefs in a block array and
1410 * also calculates the point at which all remaining blockrefs are empty.
1411 * This routine can only be called on a live chain.
1413 * NOTE: Flag is not set until after the count is complete, allowing
1414 * callers to test the flag without holding the spinlock.
1416 * NOTE: If base is NULL the related chain is still in the INITIAL
1417 * state and there are no blockrefs to count.
1419 * NOTE: live_count may already have some counts accumulated due to
1420 * creation and deletion and could even be initially negative.
1422 void
1423 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1424 hammer2_blockref_t *base, int count)
1426 hammer2_spin_ex(&chain->core.spin);
1427 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1428 if (base) {
1429 while (--count >= 0) {
1430 if (base[count].type)
1431 break;
1433 chain->core.live_zero = count + 1;
1434 while (count >= 0) {
1435 if (base[count].type)
1436 atomic_add_int(&chain->core.live_count,
1438 --count;
1440 } else {
1441 chain->core.live_zero = 0;
1443 /* else do not modify live_count */
1444 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1446 hammer2_spin_unex(&chain->core.spin);
1450 * Resize the chain's physical storage allocation in-place. This function does
1451 * not usually adjust the data pointer and must be followed by (typically) a
1452 * hammer2_chain_modify() call to copy any old data over and adjust the
1453 * data pointer.
1455 * Chains can be resized smaller without reallocating the storage. Resizing
1456 * larger will reallocate the storage. Excess or prior storage is reclaimed
1457 * asynchronously at a later time.
1459 * An nradix value of 0 is special-cased to mean that the storage should
1460 * be disassociated, that is the chain is being resized to 0 bytes (not 1
1461 * byte).
1463 * Must be passed an exclusively locked parent and chain.
1465 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1466 * to avoid instantiating a device buffer that conflicts with the vnode data
1467 * buffer. However, because H2 can compress or encrypt data, the chain may
1468 * have a dio assigned to it in those situations, and they do not conflict.
1470 * XXX return error if cannot resize.
1472 void
1473 hammer2_chain_resize(hammer2_chain_t *chain,
1474 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1475 int nradix, int flags)
1477 hammer2_dev_t *hmp;
1478 size_t obytes;
1479 size_t nbytes;
1481 hmp = chain->hmp;
1484 * Only data and indirect blocks can be resized for now.
1485 * (The volu root, inodes, and freemap elements use a fixed size).
1487 KKASSERT(chain != &hmp->vchain);
1488 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1489 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1490 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1493 * Nothing to do if the element is already the proper size
1495 obytes = chain->bytes;
1496 nbytes = (nradix) ? (1U << nradix) : 0;
1497 if (obytes == nbytes)
1498 return;
1501 * Make sure the old data is instantiated so we can copy it. If this
1502 * is a data block, the device data may be superfluous since the data
1503 * might be in a logical block, but compressed or encrypted data is
1504 * another matter.
1506 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1508 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1511 * Relocate the block, even if making it smaller (because different
1512 * block sizes may be in different regions).
1514 * NOTE: Operation does not copy the data and may only be used
1515 * to resize data blocks in-place, or directory entry blocks
1516 * which are about to be modified in some manner.
1518 hammer2_freemap_alloc(chain, nbytes);
1519 chain->bytes = nbytes;
1522 * We don't want the followup chain_modify() to try to copy data
1523 * from the old (wrong-sized) buffer. It won't know how much to
1524 * copy. This case should only occur during writes when the
1525 * originator already has the data to write in-hand.
1527 if (chain->dio) {
1528 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1529 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1530 hammer2_io_brelse(&chain->dio);
1531 chain->data = NULL;
1536 * Set the chain modified so its data can be changed by the caller, or
1537 * install deduplicated data. The caller must call this routine for each
1538 * set of modifications it makes, even if the chain is already flagged
1539 * MODIFIED.
1541 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1542 * is a CLC (cluster level change) field and is not updated by parent
1543 * propagation during a flush.
1545 * Dedup Handling
1547 * If the DEDUPABLE flag is set in the chain the storage must be reallocated
1548 * even if the chain is still flagged MODIFIED. In this case the chain's
1549 * DEDUPABLE flag will be cleared once the new storage has been assigned.
1551 * If the caller passes a non-zero dedup_off we will use it to assign the
1552 * new storage. The MODIFIED flag will be *CLEARED* in this case, and
1553 * DEDUPABLE will be set (NOTE: the UPDATE flag is always set). The caller
1554 * must not modify the data content upon return.
1556 void
1557 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1558 hammer2_off_t dedup_off, int flags)
1560 hammer2_blockref_t obref;
1561 hammer2_dev_t *hmp;
1562 hammer2_io_t *dio;
1563 int error;
1564 int wasinitial;
1565 int newmod;
1566 char *bdata;
1568 hmp = chain->hmp;
1569 obref = chain->bref;
1570 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1573 * Data is not optional for freemap chains (we must always be sure
1574 * to copy the data on COW storage allocations).
1576 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1577 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1578 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1579 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1583 * Data must be resolved if already assigned, unless explicitly
1584 * flagged otherwise.
1586 if (chain->data == NULL && chain->bytes != 0 &&
1587 (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1588 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1589 hammer2_chain_load_data(chain);
1593 * Set MODIFIED to indicate that the chain has been modified. A new
1594 * allocation is required when modifying a chain.
1596 * Set UPDATE to ensure that the blockref is updated in the parent.
1599 * If MODIFIED is already set determine if we can reuse the assigned
1600 * data block or if we need a new data block.
1602 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1604 * Must set modified bit.
1606 atomic_add_long(&hammer2_count_modified_chains, 1);
1607 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1608 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1611 * We may be able to avoid a copy-on-write if the chain's
1612 * check mode is set to NONE and the chain's current
1613 * modify_tid is beyond the last explicit snapshot tid.
1615 * This implements HAMMER2's overwrite-in-place feature.
1617 * NOTE! This data-block cannot be used as a de-duplication
1618 * source when the check mode is set to NONE.
1620 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1621 chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1622 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1623 (chain->flags & HAMMER2_CHAIN_DEDUPABLE) == 0 &&
1624 HAMMER2_DEC_CHECK(chain->bref.methods) ==
1625 HAMMER2_CHECK_NONE &&
1626 chain->pmp &&
1627 chain->bref.modify_tid >
1628 chain->pmp->iroot->meta.pfs_lsnap_tid) {
1630 * Sector overwrite allowed.
1632 newmod = 0;
1633 } else {
1635 * Sector overwrite not allowed, must copy-on-write.
1637 newmod = 1;
1639 } else if (chain->flags & HAMMER2_CHAIN_DEDUPABLE) {
1641 * If the modified chain was registered for dedup we need
1642 * a new allocation. This only happens for delayed-flush
1643 * chains (i.e. which run through the front-end buffer
1644 * cache).
1646 newmod = 1;
1647 } else {
1649 * Already flagged modified, no new allocation is needed.
1651 newmod = 0;
1655 * Flag parent update required.
1657 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1658 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1661 * The modification or re-modification requires an allocation and
1662 * possible COW.
1664 * If dedup_off is non-zero, caller already has a data offset
1665 * containing the caller's desired data. The dedup offset is
1666 * allowed to be in a partially free state and we must be sure
1667 * to reset it to a fully allocated state to force two bulkfree
1668 * passes to free it again. The chain will not be marked MODIFIED
1669 * in the dedup case, as the dedup data cannot be changed without
1670 * a new allocation.
1672 * NOTE: Only applicable when chain->bytes != 0.
1674 * XXX can a chain already be marked MODIFIED without a data
1675 * assignment? If not, assert here instead of testing the case.
1677 if (chain != &hmp->vchain && chain != &hmp->fchain &&
1678 chain->bytes) {
1679 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1680 newmod
1683 * NOTE: We do not have to remove the dedup
1684 * registration because the area is still
1685 * allocated and the underlying DIO will
1686 * still be flushed.
1688 if (dedup_off) {
1689 chain->bref.data_off = dedup_off;
1690 chain->bytes = 1 << (dedup_off &
1691 HAMMER2_OFF_MASK_RADIX);
1692 atomic_clear_int(&chain->flags,
1693 HAMMER2_CHAIN_MODIFIED);
1694 atomic_add_long(&hammer2_count_modified_chains,
1695 -1);
1696 if (chain->pmp)
1697 hammer2_pfs_memory_wakeup(chain->pmp);
1698 hammer2_freemap_adjust(hmp, &chain->bref,
1699 HAMMER2_FREEMAP_DORECOVER);
1700 atomic_set_int(&chain->flags,
1701 HAMMER2_CHAIN_DEDUPABLE);
1702 } else {
1703 hammer2_freemap_alloc(chain, chain->bytes);
1704 atomic_clear_int(&chain->flags,
1705 HAMMER2_CHAIN_DEDUPABLE);
1707 /* XXX failed allocation */
1712 * Update mirror_tid and modify_tid. modify_tid is only updated
1713 * if not passed as zero (during flushes, parent propagation passes
1714 * the value 0).
1716 * NOTE: chain->pmp could be the device spmp.
1718 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1719 if (mtid)
1720 chain->bref.modify_tid = mtid;
1723 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1724 * requires updating as well as to tell the delete code that the
1725 * chain's blockref might not exactly match (in terms of physical size
1726 * or block offset) the one in the parent's blocktable. The base key
1727 * of course will still match.
1729 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1730 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1733 * Short-cut data blocks which the caller does not need an actual
1734 * data reference to (aka OPTDATA), as long as the chain does not
1735 * already have a data pointer to the data. This generally means
1736 * that the modifications are being done via the logical buffer cache.
1737 * The INITIAL flag relates only to the device data buffer and thus
1738 * remains unchange in this situation.
1740 * This code also handles bytes == 0 (most dirents).
1742 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1743 (flags & HAMMER2_MODIFY_OPTDATA) &&
1744 chain->data == NULL) {
1745 KKASSERT(chain->dio == NULL);
1746 goto skip2;
1750 * Clearing the INITIAL flag (for indirect blocks) indicates that
1751 * we've processed the uninitialized storage allocation.
1753 * If this flag is already clear we are likely in a copy-on-write
1754 * situation but we have to be sure NOT to bzero the storage if
1755 * no data is present.
1757 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1758 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1759 wasinitial = 1;
1760 } else {
1761 wasinitial = 0;
1765 * Instantiate data buffer and possibly execute COW operation
1767 switch(chain->bref.type) {
1768 case HAMMER2_BREF_TYPE_VOLUME:
1769 case HAMMER2_BREF_TYPE_FREEMAP:
1771 * The data is embedded, no copy-on-write operation is
1772 * needed.
1774 KKASSERT(chain->dio == NULL);
1775 break;
1776 case HAMMER2_BREF_TYPE_DIRENT:
1778 * The data might be fully embedded.
1780 if (chain->bytes == 0) {
1781 KKASSERT(chain->dio == NULL);
1782 break;
1784 /* fall through */
1785 case HAMMER2_BREF_TYPE_INODE:
1786 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1787 case HAMMER2_BREF_TYPE_DATA:
1788 case HAMMER2_BREF_TYPE_INDIRECT:
1789 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1791 * Perform the copy-on-write operation
1793 * zero-fill or copy-on-write depending on whether
1794 * chain->data exists or not and set the dirty state for
1795 * the new buffer. hammer2_io_new() will handle the
1796 * zero-fill.
1798 * If a dedup_off was supplied this is an existing block
1799 * and no COW, copy, or further modification is required.
1801 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1803 if (wasinitial && dedup_off == 0) {
1804 error = hammer2_io_new(hmp, chain->bref.type,
1805 chain->bref.data_off,
1806 chain->bytes, &dio);
1807 } else {
1808 error = hammer2_io_bread(hmp, chain->bref.type,
1809 chain->bref.data_off,
1810 chain->bytes, &dio);
1812 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1815 * If an I/O error occurs make sure callers cannot accidently
1816 * modify the old buffer's contents and corrupt the filesystem.
1818 if (error) {
1819 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1820 hmp);
1821 chain->error = HAMMER2_ERROR_IO;
1822 hammer2_io_brelse(&dio);
1823 hammer2_io_brelse(&chain->dio);
1824 chain->data = NULL;
1825 break;
1827 chain->error = 0;
1828 bdata = hammer2_io_data(dio, chain->bref.data_off);
1830 if (chain->data) {
1832 * COW (unless a dedup).
1834 KKASSERT(chain->dio != NULL);
1835 if (chain->data != (void *)bdata && dedup_off == 0) {
1836 bcopy(chain->data, bdata, chain->bytes);
1838 } else if (wasinitial == 0) {
1840 * We have a problem. We were asked to COW but
1841 * we don't have any data to COW with!
1843 panic("hammer2_chain_modify: having a COW %p\n",
1844 chain);
1848 * Retire the old buffer, replace with the new. Dirty or
1849 * redirty the new buffer.
1851 * WARNING! The system buffer cache may have already flushed
1852 * the buffer, so we must be sure to [re]dirty it
1853 * for further modification.
1855 * If dedup_off was supplied, the caller is not
1856 * expected to make any further modification to the
1857 * buffer.
1859 if (chain->dio)
1860 hammer2_io_bqrelse(&chain->dio);
1861 chain->data = (void *)bdata;
1862 chain->dio = dio;
1863 if (dedup_off == 0)
1864 hammer2_io_setdirty(dio);
1865 break;
1866 default:
1867 panic("hammer2_chain_modify: illegal non-embedded type %d",
1868 chain->bref.type);
1869 break;
1872 skip2:
1874 * setflush on parent indicating that the parent must recurse down
1875 * to us. Do not call on chain itself which might already have it
1876 * set.
1878 if (chain->parent)
1879 hammer2_chain_setflush(chain->parent);
1883 * Modify the chain associated with an inode.
1885 void
1886 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1887 hammer2_tid_t mtid, int flags)
1889 hammer2_inode_modify(ip);
1890 hammer2_chain_modify(chain, mtid, 0, flags);
1894 * Volume header data locks
1896 void
1897 hammer2_voldata_lock(hammer2_dev_t *hmp)
1899 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1902 void
1903 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1905 lockmgr(&hmp->vollk, LK_RELEASE);
1908 void
1909 hammer2_voldata_modify(hammer2_dev_t *hmp)
1911 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1912 atomic_add_long(&hammer2_count_modified_chains, 1);
1913 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1914 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1919 * This function returns the chain at the nearest key within the specified
1920 * range. The returned chain will be referenced but not locked.
1922 * This function will recurse through chain->rbtree as necessary and will
1923 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1924 * the iteration value is less than the current value of *key_nextp.
1926 * The caller should use (*key_nextp) to calculate the actual range of
1927 * the returned element, which will be (key_beg to *key_nextp - 1), because
1928 * there might be another element which is superior to the returned element
1929 * and overlaps it.
1931 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1932 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1933 * it will wind up being (key_end + 1).
1935 * WARNING! Must be called with child's spinlock held. Spinlock remains
1936 * held through the operation.
1938 struct hammer2_chain_find_info {
1939 hammer2_chain_t *best;
1940 hammer2_key_t key_beg;
1941 hammer2_key_t key_end;
1942 hammer2_key_t key_next;
1945 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1946 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1948 static
1949 hammer2_chain_t *
1950 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1951 hammer2_key_t key_beg, hammer2_key_t key_end)
1953 struct hammer2_chain_find_info info;
1955 info.best = NULL;
1956 info.key_beg = key_beg;
1957 info.key_end = key_end;
1958 info.key_next = *key_nextp;
1960 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1961 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1962 &info);
1963 *key_nextp = info.key_next;
1964 #if 0
1965 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1966 parent, key_beg, key_end, *key_nextp);
1967 #endif
1969 return (info.best);
1972 static
1974 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1976 struct hammer2_chain_find_info *info = data;
1977 hammer2_key_t child_beg;
1978 hammer2_key_t child_end;
1980 child_beg = child->bref.key;
1981 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1983 if (child_end < info->key_beg)
1984 return(-1);
1985 if (child_beg > info->key_end)
1986 return(1);
1987 return(0);
1990 static
1992 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1994 struct hammer2_chain_find_info *info = data;
1995 hammer2_chain_t *best;
1996 hammer2_key_t child_end;
1999 * WARNING! Layerq is scanned forwards, exact matches should keep
2000 * the existing info->best.
2002 if ((best = info->best) == NULL) {
2004 * No previous best. Assign best
2006 info->best = child;
2007 } else if (best->bref.key <= info->key_beg &&
2008 child->bref.key <= info->key_beg) {
2010 * Illegal overlap.
2012 KKASSERT(0);
2013 /*info->best = child;*/
2014 } else if (child->bref.key < best->bref.key) {
2016 * Child has a nearer key and best is not flush with key_beg.
2017 * Set best to child. Truncate key_next to the old best key.
2019 info->best = child;
2020 if (info->key_next > best->bref.key || info->key_next == 0)
2021 info->key_next = best->bref.key;
2022 } else if (child->bref.key == best->bref.key) {
2024 * If our current best is flush with the child then this
2025 * is an illegal overlap.
2027 * key_next will automatically be limited to the smaller of
2028 * the two end-points.
2030 KKASSERT(0);
2031 info->best = child;
2032 } else {
2034 * Keep the current best but truncate key_next to the child's
2035 * base.
2037 * key_next will also automatically be limited to the smaller
2038 * of the two end-points (probably not necessary for this case
2039 * but we do it anyway).
2041 if (info->key_next > child->bref.key || info->key_next == 0)
2042 info->key_next = child->bref.key;
2046 * Always truncate key_next based on child's end-of-range.
2048 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
2049 if (child_end && (info->key_next > child_end || info->key_next == 0))
2050 info->key_next = child_end;
2052 return(0);
2056 * Retrieve the specified chain from a media blockref, creating the
2057 * in-memory chain structure which reflects it.
2059 * To handle insertion races pass the INSERT_RACE flag along with the
2060 * generation number of the core. NULL will be returned if the generation
2061 * number changes before we have a chance to insert the chain. Insert
2062 * races can occur because the parent might be held shared.
2064 * Caller must hold the parent locked shared or exclusive since we may
2065 * need the parent's bref array to find our block.
2067 * WARNING! chain->pmp is always set to NULL for any chain representing
2068 * part of the super-root topology.
2070 hammer2_chain_t *
2071 hammer2_chain_get(hammer2_chain_t *parent, int generation,
2072 hammer2_blockref_t *bref)
2074 hammer2_dev_t *hmp = parent->hmp;
2075 hammer2_chain_t *chain;
2076 int error;
2079 * Allocate a chain structure representing the existing media
2080 * entry. Resulting chain has one ref and is not locked.
2082 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
2083 chain = hammer2_chain_alloc(hmp, NULL, bref);
2084 else
2085 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
2086 /* ref'd chain returned */
2089 * Flag that the chain is in the parent's blockmap so delete/flush
2090 * knows what to do with it.
2092 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2095 * Link the chain into its parent. A spinlock is required to safely
2096 * access the RBTREE, and it is possible to collide with another
2097 * hammer2_chain_get() operation because the caller might only hold
2098 * a shared lock on the parent.
2100 * NOTE: Get races can occur quite often when we distribute
2101 * asynchronous read-aheads across multiple threads.
2103 KKASSERT(parent->refs > 0);
2104 error = hammer2_chain_insert(parent, chain,
2105 HAMMER2_CHAIN_INSERT_SPIN |
2106 HAMMER2_CHAIN_INSERT_RACE,
2107 generation);
2108 if (error) {
2109 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2110 /*kprintf("chain %p get race\n", chain);*/
2111 hammer2_chain_drop(chain);
2112 chain = NULL;
2113 } else {
2114 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2118 * Return our new chain referenced but not locked, or NULL if
2119 * a race occurred.
2121 return (chain);
2125 * Lookup initialization/completion API
2127 hammer2_chain_t *
2128 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2130 hammer2_chain_ref(parent);
2131 if (flags & HAMMER2_LOOKUP_SHARED) {
2132 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2133 HAMMER2_RESOLVE_SHARED);
2134 } else {
2135 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2137 return (parent);
2140 void
2141 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2143 if (parent) {
2144 hammer2_chain_unlock(parent);
2145 hammer2_chain_drop(parent);
2150 * Take the locked chain and return a locked parent. The chain remains
2151 * locked on return.
2153 * This function handles the lock order reversal.
2155 hammer2_chain_t *
2156 hammer2_chain_getparent(hammer2_chain_t *chain, int how)
2158 hammer2_chain_t *parent;
2161 * Be careful of order, chain must be unlocked before parent
2162 * is locked below to avoid a deadlock.
2164 * Safe access to fu->parent requires fu's core spinlock.
2166 again:
2167 hammer2_spin_ex(&chain->core.spin);
2168 parent = chain->parent;
2169 if (parent == NULL) {
2170 hammer2_spin_unex(&chain->core.spin);
2171 panic("hammer2_chain_getparent: no parent");
2173 hammer2_chain_ref(parent);
2174 hammer2_spin_unex(&chain->core.spin);
2176 hammer2_chain_unlock(chain);
2177 hammer2_chain_lock(parent, how);
2178 hammer2_chain_lock(chain, how);
2181 * Parent relinking races are quite common. We have to get it right
2182 * or we will blow up the block table.
2184 if (chain->parent != parent) {
2185 hammer2_chain_unlock(parent);
2186 hammer2_chain_drop(parent);
2187 goto again;
2189 return parent;
2193 * Take the locked chain and return a locked parent. The chain is unlocked
2194 * and dropped. *chainp is set to the returned parent as a convenience.
2196 * This function handles the lock order reversal.
2198 hammer2_chain_t *
2199 hammer2_chain_repparent(hammer2_chain_t **chainp, int how)
2201 hammer2_chain_t *chain;
2202 hammer2_chain_t *parent;
2205 * Be careful of order, chain must be unlocked before parent
2206 * is locked below to avoid a deadlock.
2208 * Safe access to fu->parent requires fu's core spinlock.
2210 chain = *chainp;
2211 again:
2212 hammer2_spin_ex(&chain->core.spin);
2213 parent = chain->parent;
2214 if (parent == NULL) {
2215 hammer2_spin_unex(&chain->core.spin);
2216 panic("hammer2_chain_getparent: no parent");
2218 hammer2_chain_ref(parent);
2219 hammer2_spin_unex(&chain->core.spin);
2221 hammer2_chain_unlock(chain);
2222 hammer2_chain_lock(parent, how);
2225 * Parent relinking races are quite common. We have to get it right
2226 * or we will blow up the block table.
2228 if (chain->parent != parent) {
2229 hammer2_chain_lock(chain, how);
2230 hammer2_chain_unlock(parent);
2231 hammer2_chain_drop(parent);
2232 goto again;
2234 hammer2_chain_drop(chain);
2235 *chainp = parent;
2237 return parent;
2241 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2242 * (*parentp) typically points to an inode but can also point to a related
2243 * indirect block and this function will recurse upwards and find the inode
2244 * again.
2246 * (*parentp) must be exclusively locked and referenced and can be an inode
2247 * or an existing indirect block within the inode.
2249 * On return (*parentp) will be modified to point at the deepest parent chain
2250 * element encountered during the search, as a helper for an insertion or
2251 * deletion. The new (*parentp) will be locked and referenced and the old
2252 * will be unlocked and dereferenced (no change if they are both the same).
2254 * The matching chain will be returned exclusively locked. If NOLOCK is
2255 * requested the chain will be returned only referenced. Note that the
2256 * parent chain must always be locked shared or exclusive, matching the
2257 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
2258 * when NOLOCK is specified but that complicates matters if *parentp must
2259 * inherit the chain.
2261 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2262 * data pointer or can otherwise be in flux.
2264 * NULL is returned if no match was found, but (*parentp) will still
2265 * potentially be adjusted.
2267 * If a fatal error occurs (typically an I/O error), a dummy chain is
2268 * returned with chain->error and error-identifying information set. This
2269 * chain will assert if you try to do anything fancy with it.
2271 * XXX Depending on where the error occurs we should allow continued iteration.
2273 * On return (*key_nextp) will point to an iterative value for key_beg.
2274 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2276 * This function will also recurse up the chain if the key is not within the
2277 * current parent's range. (*parentp) can never be set to NULL. An iteration
2278 * can simply allow (*parentp) to float inside the loop.
2280 * NOTE! chain->data is not always resolved. By default it will not be
2281 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2282 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2283 * BREF_TYPE_DATA as the device buffer can alias the logical file
2284 * buffer).
2287 hammer2_chain_t *
2288 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2289 hammer2_key_t key_beg, hammer2_key_t key_end,
2290 int *cache_indexp, int flags)
2292 hammer2_dev_t *hmp;
2293 hammer2_chain_t *parent;
2294 hammer2_chain_t *chain;
2295 hammer2_blockref_t *base;
2296 hammer2_blockref_t *bref;
2297 hammer2_blockref_t bcopy;
2298 hammer2_key_t scan_beg;
2299 hammer2_key_t scan_end;
2300 int count = 0;
2301 int how_always = HAMMER2_RESOLVE_ALWAYS;
2302 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2303 int how;
2304 int generation;
2305 int maxloops = 300000;
2307 TIMER(8);
2309 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2310 how_maybe = how_always;
2311 how = HAMMER2_RESOLVE_ALWAYS;
2312 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2313 how = HAMMER2_RESOLVE_NEVER;
2314 } else {
2315 how = HAMMER2_RESOLVE_MAYBE;
2317 if (flags & HAMMER2_LOOKUP_SHARED) {
2318 how_maybe |= HAMMER2_RESOLVE_SHARED;
2319 how_always |= HAMMER2_RESOLVE_SHARED;
2320 how |= HAMMER2_RESOLVE_SHARED;
2324 * Recurse (*parentp) upward if necessary until the parent completely
2325 * encloses the key range or we hit the inode.
2327 * Handle races against the flusher deleting indirect nodes on its
2328 * way back up by continuing to recurse upward past the deletion.
2330 parent = *parentp;
2331 hmp = parent->hmp;
2333 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2334 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2335 scan_beg = parent->bref.key;
2336 scan_end = scan_beg +
2337 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2338 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT ||
2339 (parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2340 if (key_beg >= scan_beg && key_end <= scan_end)
2341 break;
2343 parent = hammer2_chain_repparent(parentp, how_maybe);
2345 again:
2347 TIMER(9);
2348 if (--maxloops == 0)
2349 panic("hammer2_chain_lookup: maxloops");
2351 * Locate the blockref array. Currently we do a fully associative
2352 * search through the array.
2354 switch(parent->bref.type) {
2355 case HAMMER2_BREF_TYPE_INODE:
2357 * Special shortcut for embedded data returns the inode
2358 * itself. Callers must detect this condition and access
2359 * the embedded data (the strategy code does this for us).
2361 * This is only applicable to regular files and softlinks.
2363 * We need a second lock on parent. Since we already have
2364 * a lock we must pass LOCKAGAIN to prevent unexpected
2365 * blocking (we don't want to block on a second shared
2366 * ref if an exclusive lock is pending)
2368 if (parent->data->ipdata.meta.op_flags &
2369 HAMMER2_OPFLAG_DIRECTDATA) {
2370 if (flags & HAMMER2_LOOKUP_NODIRECT) {
2371 chain = NULL;
2372 *key_nextp = key_end + 1;
2373 goto done;
2375 hammer2_chain_ref(parent);
2376 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2377 hammer2_chain_lock(parent,
2378 how_always |
2379 HAMMER2_RESOLVE_LOCKAGAIN);
2380 *key_nextp = key_end + 1;
2381 return (parent);
2383 base = &parent->data->ipdata.u.blockset.blockref[0];
2384 count = HAMMER2_SET_COUNT;
2385 break;
2386 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2387 case HAMMER2_BREF_TYPE_INDIRECT:
2389 * Handle MATCHIND on the parent
2391 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2392 scan_beg = parent->bref.key;
2393 scan_end = scan_beg +
2394 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2395 if (key_beg == scan_beg && key_end == scan_end) {
2396 chain = parent;
2397 hammer2_chain_ref(chain);
2398 hammer2_chain_lock(chain, how_maybe);
2399 *key_nextp = scan_end + 1;
2400 goto done;
2405 * Optimize indirect blocks in the INITIAL state to avoid
2406 * I/O.
2408 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2409 base = NULL;
2410 } else {
2411 if (parent->data == NULL) {
2412 kprintf("parent->data is NULL %p\n", parent);
2413 while (1)
2414 tsleep(parent, 0, "xxx", 0);
2416 base = &parent->data->npdata[0];
2418 count = parent->bytes / sizeof(hammer2_blockref_t);
2419 break;
2420 case HAMMER2_BREF_TYPE_VOLUME:
2421 base = &parent->data->voldata.sroot_blockset.blockref[0];
2422 count = HAMMER2_SET_COUNT;
2423 break;
2424 case HAMMER2_BREF_TYPE_FREEMAP:
2425 base = &parent->data->blkset.blockref[0];
2426 count = HAMMER2_SET_COUNT;
2427 break;
2428 default:
2429 kprintf("hammer2_chain_lookup: unrecognized "
2430 "blockref(B) type: %d",
2431 parent->bref.type);
2432 while (1)
2433 tsleep(&base, 0, "dead", 0);
2434 panic("hammer2_chain_lookup: unrecognized "
2435 "blockref(B) type: %d",
2436 parent->bref.type);
2437 base = NULL; /* safety */
2438 count = 0; /* safety */
2440 TIMER(10);
2443 * Merged scan to find next candidate.
2445 * hammer2_base_*() functions require the parent->core.live_* fields
2446 * to be synchronized.
2448 * We need to hold the spinlock to access the block array and RB tree
2449 * and to interlock chain creation.
2451 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2452 hammer2_chain_countbrefs(parent, base, count);
2454 TIMER(11);
2457 * Combined search
2459 hammer2_spin_ex(&parent->core.spin);
2460 chain = hammer2_combined_find(parent, base, count,
2461 cache_indexp, key_nextp,
2462 key_beg, key_end,
2463 &bref);
2464 generation = parent->core.generation;
2466 TIMER(12);
2469 * Exhausted parent chain, iterate.
2471 if (bref == NULL) {
2472 TIMER(13);
2473 hammer2_spin_unex(&parent->core.spin);
2474 if (key_beg == key_end) /* short cut single-key case */
2475 return (NULL);
2478 * Stop if we reached the end of the iteration.
2480 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2481 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2482 return (NULL);
2486 * Calculate next key, stop if we reached the end of the
2487 * iteration, otherwise go up one level and loop.
2489 key_beg = parent->bref.key +
2490 ((hammer2_key_t)1 << parent->bref.keybits);
2491 if (key_beg == 0 || key_beg > key_end)
2492 return (NULL);
2493 parent = hammer2_chain_repparent(parentp, how_maybe);
2494 goto again;
2498 * Selected from blockref or in-memory chain.
2500 if (chain == NULL) {
2501 TIMER(14);
2502 bcopy = *bref;
2503 hammer2_spin_unex(&parent->core.spin);
2504 chain = hammer2_chain_get(parent, generation,
2505 &bcopy);
2506 if (chain == NULL) {
2508 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2509 parent, key_beg, key_end);
2511 goto again;
2513 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2514 hammer2_chain_drop(chain);
2515 goto again;
2517 } else {
2518 TIMER(15);
2519 hammer2_chain_ref(chain);
2520 hammer2_spin_unex(&parent->core.spin);
2523 TIMER(16);
2525 * chain is referenced but not locked. We must lock the chain
2526 * to obtain definitive state.
2528 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2529 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2530 hammer2_chain_lock(chain, how_maybe);
2531 } else {
2532 hammer2_chain_lock(chain, how);
2534 KKASSERT(chain->parent == parent);
2535 TIMER(17);
2538 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2540 * NOTE: Chain's key range is not relevant as there might be
2541 * one-offs within the range that are not deleted.
2543 * NOTE: Lookups can race delete-duplicate because
2544 * delete-duplicate does not lock the parent's core
2545 * (they just use the spinlock on the core).
2547 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2548 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2549 chain->bref.data_off, chain->bref.type,
2550 chain->bref.key);
2551 hammer2_chain_unlock(chain);
2552 hammer2_chain_drop(chain);
2553 key_beg = *key_nextp;
2554 if (key_beg == 0 || key_beg > key_end)
2555 return(NULL);
2556 goto again;
2558 TIMER(18);
2561 * If the chain element is an indirect block it becomes the new
2562 * parent and we loop on it. We must maintain our top-down locks
2563 * to prevent the flusher from interfering (i.e. doing a
2564 * delete-duplicate and leaving us recursing down a deleted chain).
2566 * The parent always has to be locked with at least RESOLVE_MAYBE
2567 * so we can access its data. It might need a fixup if the caller
2568 * passed incompatible flags. Be careful not to cause a deadlock
2569 * as a data-load requires an exclusive lock.
2571 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2572 * range is within the requested key range we return the indirect
2573 * block and do NOT loop. This is usually only used to acquire
2574 * freemap nodes.
2576 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2577 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2578 hammer2_chain_unlock(parent);
2579 hammer2_chain_drop(parent);
2580 *parentp = parent = chain;
2581 goto again;
2583 TIMER(19);
2584 done:
2586 * All done, return the chain.
2588 * If the caller does not want a locked chain, replace the lock with
2589 * a ref. Perhaps this can eventually be optimized to not obtain the
2590 * lock in the first place for situations where the data does not
2591 * need to be resolved.
2593 if (chain) {
2594 if (flags & HAMMER2_LOOKUP_NOLOCK)
2595 hammer2_chain_unlock(chain);
2597 TIMER(20);
2599 return (chain);
2603 * After having issued a lookup we can iterate all matching keys.
2605 * If chain is non-NULL we continue the iteration from just after it's index.
2607 * If chain is NULL we assume the parent was exhausted and continue the
2608 * iteration at the next parent.
2610 * If a fatal error occurs (typically an I/O error), a dummy chain is
2611 * returned with chain->error and error-identifying information set. This
2612 * chain will assert if you try to do anything fancy with it.
2614 * XXX Depending on where the error occurs we should allow continued iteration.
2616 * parent must be locked on entry and remains locked throughout. chain's
2617 * lock status must match flags. Chain is always at least referenced.
2619 * WARNING! The MATCHIND flag does not apply to this function.
2621 hammer2_chain_t *
2622 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2623 hammer2_key_t *key_nextp,
2624 hammer2_key_t key_beg, hammer2_key_t key_end,
2625 int *cache_indexp, int flags)
2627 hammer2_chain_t *parent;
2628 int how_maybe;
2631 * Calculate locking flags for upward recursion.
2633 how_maybe = HAMMER2_RESOLVE_MAYBE;
2634 if (flags & HAMMER2_LOOKUP_SHARED)
2635 how_maybe |= HAMMER2_RESOLVE_SHARED;
2637 parent = *parentp;
2640 * Calculate the next index and recalculate the parent if necessary.
2642 if (chain) {
2643 key_beg = chain->bref.key +
2644 ((hammer2_key_t)1 << chain->bref.keybits);
2645 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2646 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2647 hammer2_chain_unlock(chain);
2649 hammer2_chain_drop(chain);
2652 * chain invalid past this point, but we can still do a
2653 * pointer comparison w/parent.
2655 * Any scan where the lookup returned degenerate data embedded
2656 * in the inode has an invalid index and must terminate.
2658 if (chain == parent)
2659 return(NULL);
2660 if (key_beg == 0 || key_beg > key_end)
2661 return(NULL);
2662 chain = NULL;
2663 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2664 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2666 * We reached the end of the iteration.
2668 return (NULL);
2669 } else {
2671 * Continue iteration with next parent unless the current
2672 * parent covers the range.
2674 * (This also handles the case of a deleted, empty indirect
2675 * node).
2677 key_beg = parent->bref.key +
2678 ((hammer2_key_t)1 << parent->bref.keybits);
2679 if (key_beg == 0 || key_beg > key_end)
2680 return (NULL);
2681 parent = hammer2_chain_repparent(parentp, how_maybe);
2685 * And execute
2687 return (hammer2_chain_lookup(parentp, key_nextp,
2688 key_beg, key_end,
2689 cache_indexp, flags));
2693 * The raw scan function is similar to lookup/next but does not seek to a key.
2694 * Blockrefs are iterated via first_bref = (parent, NULL) and
2695 * next_chain = (parent, bref).
2697 * The passed-in parent must be locked and its data resolved. The function
2698 * nominally returns a locked and referenced *chainp != NULL for chains
2699 * the caller might need to recurse on (and will dipose of any *chainp passed
2700 * in). The caller must check the chain->bref.type either way.
2702 * *chainp is not set for leaf elements.
2704 * This function takes a pointer to a stack-based bref structure whos
2705 * contents is updated for each iteration. The same pointer is returned,
2706 * or NULL when the iteration is complete. *firstp must be set to 1 for
2707 * the first ieration. This function will set it to 0.
2709 hammer2_blockref_t *
2710 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2711 hammer2_blockref_t *bref, int *firstp,
2712 int *cache_indexp, int flags)
2714 hammer2_dev_t *hmp;
2715 hammer2_blockref_t *base;
2716 hammer2_blockref_t *bref_ptr;
2717 hammer2_key_t key;
2718 hammer2_key_t next_key;
2719 hammer2_chain_t *chain = NULL;
2720 int count = 0;
2721 int how_always = HAMMER2_RESOLVE_ALWAYS;
2722 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2723 int how;
2724 int generation;
2725 int maxloops = 300000;
2727 hmp = parent->hmp;
2730 * Scan flags borrowed from lookup.
2732 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2733 how_maybe = how_always;
2734 how = HAMMER2_RESOLVE_ALWAYS;
2735 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2736 how = HAMMER2_RESOLVE_NEVER;
2737 } else {
2738 how = HAMMER2_RESOLVE_MAYBE;
2740 if (flags & HAMMER2_LOOKUP_SHARED) {
2741 how_maybe |= HAMMER2_RESOLVE_SHARED;
2742 how_always |= HAMMER2_RESOLVE_SHARED;
2743 how |= HAMMER2_RESOLVE_SHARED;
2747 * Calculate key to locate first/next element, unlocking the previous
2748 * element as we go. Be careful, the key calculation can overflow.
2750 * (also reset bref to NULL)
2752 if (*firstp) {
2753 key = 0;
2754 *firstp = 0;
2755 } else {
2756 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2757 if ((chain = *chainp) != NULL) {
2758 *chainp = NULL;
2759 hammer2_chain_unlock(chain);
2760 hammer2_chain_drop(chain);
2761 chain = NULL;
2763 if (key == 0) {
2764 bref = NULL;
2765 goto done;
2769 again:
2770 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2771 if (--maxloops == 0)
2772 panic("hammer2_chain_scan: maxloops");
2774 * Locate the blockref array. Currently we do a fully associative
2775 * search through the array.
2777 switch(parent->bref.type) {
2778 case HAMMER2_BREF_TYPE_INODE:
2780 * An inode with embedded data has no sub-chains.
2782 * WARNING! Bulk scan code may pass a static chain marked
2783 * as BREF_TYPE_INODE with a copy of the volume
2784 * root blockset to snapshot the volume.
2786 if (parent->data->ipdata.meta.op_flags &
2787 HAMMER2_OPFLAG_DIRECTDATA) {
2788 bref = NULL;
2789 goto done;
2791 base = &parent->data->ipdata.u.blockset.blockref[0];
2792 count = HAMMER2_SET_COUNT;
2793 break;
2794 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2795 case HAMMER2_BREF_TYPE_INDIRECT:
2797 * Optimize indirect blocks in the INITIAL state to avoid
2798 * I/O.
2800 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2801 base = NULL;
2802 } else {
2803 if (parent->data == NULL)
2804 panic("parent->data is NULL");
2805 base = &parent->data->npdata[0];
2807 count = parent->bytes / sizeof(hammer2_blockref_t);
2808 break;
2809 case HAMMER2_BREF_TYPE_VOLUME:
2810 base = &parent->data->voldata.sroot_blockset.blockref[0];
2811 count = HAMMER2_SET_COUNT;
2812 break;
2813 case HAMMER2_BREF_TYPE_FREEMAP:
2814 base = &parent->data->blkset.blockref[0];
2815 count = HAMMER2_SET_COUNT;
2816 break;
2817 default:
2818 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2819 parent->bref.type);
2820 base = NULL; /* safety */
2821 count = 0; /* safety */
2825 * Merged scan to find next candidate.
2827 * hammer2_base_*() functions require the parent->core.live_* fields
2828 * to be synchronized.
2830 * We need to hold the spinlock to access the block array and RB tree
2831 * and to interlock chain creation.
2833 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2834 hammer2_chain_countbrefs(parent, base, count);
2836 next_key = 0;
2837 bref_ptr = NULL;
2838 hammer2_spin_ex(&parent->core.spin);
2839 chain = hammer2_combined_find(parent, base, count,
2840 cache_indexp, &next_key,
2841 key, HAMMER2_KEY_MAX,
2842 &bref_ptr);
2843 generation = parent->core.generation;
2846 * Exhausted parent chain, we're done.
2848 if (bref_ptr == NULL) {
2849 hammer2_spin_unex(&parent->core.spin);
2850 KKASSERT(chain == NULL);
2851 bref = NULL;
2852 goto done;
2856 * Copy into the supplied stack-based blockref.
2858 *bref = *bref_ptr;
2861 * Selected from blockref or in-memory chain.
2863 if (chain == NULL) {
2864 switch(bref->type) {
2865 case HAMMER2_BREF_TYPE_INODE:
2866 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2867 case HAMMER2_BREF_TYPE_INDIRECT:
2868 case HAMMER2_BREF_TYPE_VOLUME:
2869 case HAMMER2_BREF_TYPE_FREEMAP:
2871 * Recursion, always get the chain
2873 hammer2_spin_unex(&parent->core.spin);
2874 chain = hammer2_chain_get(parent, generation, bref);
2875 if (chain == NULL) {
2876 kprintf("retry scan parent %p keys %016jx\n",
2877 parent, key);
2878 goto again;
2880 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2881 hammer2_chain_drop(chain);
2882 chain = NULL;
2883 goto again;
2885 break;
2886 default:
2888 * No recursion, do not waste time instantiating
2889 * a chain, just iterate using the bref.
2891 hammer2_spin_unex(&parent->core.spin);
2892 break;
2894 } else {
2896 * Recursion or not we need the chain in order to supply
2897 * the bref.
2899 hammer2_chain_ref(chain);
2900 hammer2_spin_unex(&parent->core.spin);
2904 * chain is referenced but not locked. We must lock the chain
2905 * to obtain definitive state.
2907 if (chain)
2908 hammer2_chain_lock(chain, how);
2911 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2913 * NOTE: chain's key range is not relevant as there might be
2914 * one-offs within the range that are not deleted.
2916 * NOTE: XXX this could create problems with scans used in
2917 * situations other than mount-time recovery.
2919 * NOTE: Lookups can race delete-duplicate because
2920 * delete-duplicate does not lock the parent's core
2921 * (they just use the spinlock on the core).
2923 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2924 hammer2_chain_unlock(chain);
2925 hammer2_chain_drop(chain);
2926 chain = NULL;
2928 key = next_key;
2929 if (key == 0) {
2930 bref = NULL;
2931 goto done;
2933 goto again;
2936 done:
2938 * All done, return the bref or NULL, supply chain if necessary.
2940 if (chain)
2941 *chainp = chain;
2942 return (bref);
2946 * Create and return a new hammer2 system memory structure of the specified
2947 * key, type and size and insert it under (*parentp). This is a full
2948 * insertion, based on the supplied key/keybits, and may involve creating
2949 * indirect blocks and moving other chains around via delete/duplicate.
2951 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2952 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2953 * FULL. This typically means that the caller is creating the chain after
2954 * doing a hammer2_chain_lookup().
2956 * (*parentp) must be exclusive locked and may be replaced on return
2957 * depending on how much work the function had to do.
2959 * (*parentp) must not be errored or this function will assert.
2961 * (*chainp) usually starts out NULL and returns the newly created chain,
2962 * but if the caller desires the caller may allocate a disconnected chain
2963 * and pass it in instead.
2965 * This function should NOT be used to insert INDIRECT blocks. It is
2966 * typically used to create/insert inodes and data blocks.
2968 * Caller must pass-in an exclusively locked parent the new chain is to
2969 * be inserted under, and optionally pass-in a disconnected, exclusively
2970 * locked chain to insert (else we create a new chain). The function will
2971 * adjust (*parentp) as necessary, create or connect the chain, and
2972 * return an exclusively locked chain in *chainp.
2974 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2975 * and will be reassigned.
2978 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2979 hammer2_pfs_t *pmp, int methods,
2980 hammer2_key_t key, int keybits, int type, size_t bytes,
2981 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2983 hammer2_dev_t *hmp;
2984 hammer2_chain_t *chain;
2985 hammer2_chain_t *parent;
2986 hammer2_blockref_t *base;
2987 hammer2_blockref_t dummy;
2988 int allocated = 0;
2989 int error = 0;
2990 int count;
2991 int maxloops = 300000;
2994 * Topology may be crossing a PFS boundary.
2996 parent = *parentp;
2997 KKASSERT(hammer2_mtx_owned(&parent->lock));
2998 KKASSERT(parent->error == 0);
2999 hmp = parent->hmp;
3000 chain = *chainp;
3002 if (chain == NULL) {
3004 * First allocate media space and construct the dummy bref,
3005 * then allocate the in-memory chain structure. Set the
3006 * INITIAL flag for fresh chains which do not have embedded
3007 * data.
3009 * XXX for now set the check mode of the child based on
3010 * the parent or, if the parent is an inode, the
3011 * specification in the inode.
3013 bzero(&dummy, sizeof(dummy));
3014 dummy.type = type;
3015 dummy.key = key;
3016 dummy.keybits = keybits;
3017 dummy.data_off = hammer2_getradix(bytes);
3020 * Inherit methods from parent by default. Primarily used
3021 * for BREF_TYPE_DATA. Non-data types *must* be set to
3022 * a non-NONE check algorithm.
3024 if (methods == -1)
3025 dummy.methods = parent->bref.methods;
3026 else
3027 dummy.methods = (uint8_t)methods;
3029 if (type != HAMMER2_BREF_TYPE_DATA &&
3030 HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
3031 dummy.methods |=
3032 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
3035 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
3038 * Lock the chain manually, chain_lock will load the chain
3039 * which we do NOT want to do. (note: chain->refs is set
3040 * to 1 by chain_alloc() for us, but lockcnt is not).
3042 chain->lockcnt = 1;
3043 hammer2_mtx_ex(&chain->lock);
3044 allocated = 1;
3045 ++curthread->td_tracker;
3048 * Set INITIAL to optimize I/O. The flag will generally be
3049 * processed when we call hammer2_chain_modify().
3051 * Recalculate bytes to reflect the actual media block
3052 * allocation. Handle special case radix 0 == 0 bytes.
3054 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3055 if (bytes)
3056 bytes = (hammer2_off_t)1 << bytes;
3057 chain->bytes = bytes;
3059 switch(type) {
3060 case HAMMER2_BREF_TYPE_VOLUME:
3061 case HAMMER2_BREF_TYPE_FREEMAP:
3062 panic("hammer2_chain_create: called with volume type");
3063 break;
3064 case HAMMER2_BREF_TYPE_INDIRECT:
3065 panic("hammer2_chain_create: cannot be used to"
3066 "create indirect block");
3067 break;
3068 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3069 panic("hammer2_chain_create: cannot be used to"
3070 "create freemap root or node");
3071 break;
3072 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3073 KKASSERT(bytes == sizeof(chain->data->bmdata));
3074 /* fall through */
3075 case HAMMER2_BREF_TYPE_DIRENT:
3076 case HAMMER2_BREF_TYPE_INODE:
3077 case HAMMER2_BREF_TYPE_DATA:
3078 default:
3080 * leave chain->data NULL, set INITIAL
3082 KKASSERT(chain->data == NULL);
3083 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
3084 break;
3086 } else {
3088 * We are reattaching a previously deleted chain, possibly
3089 * under a new parent and possibly with a new key/keybits.
3090 * The chain does not have to be in a modified state. The
3091 * UPDATE flag will be set later on in this routine.
3093 * Do NOT mess with the current state of the INITIAL flag.
3095 chain->bref.key = key;
3096 chain->bref.keybits = keybits;
3097 if (chain->flags & HAMMER2_CHAIN_DELETED)
3098 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3099 KKASSERT(chain->parent == NULL);
3101 if (flags & HAMMER2_INSERT_PFSROOT)
3102 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
3103 else
3104 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
3107 * Calculate how many entries we have in the blockref array and
3108 * determine if an indirect block is required.
3110 again:
3111 if (--maxloops == 0)
3112 panic("hammer2_chain_create: maxloops");
3114 switch(parent->bref.type) {
3115 case HAMMER2_BREF_TYPE_INODE:
3116 if ((parent->data->ipdata.meta.op_flags &
3117 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
3118 kprintf("hammer2: parent set for direct-data! "
3119 "pkey=%016jx ckey=%016jx\n",
3120 parent->bref.key,
3121 chain->bref.key);
3123 KKASSERT((parent->data->ipdata.meta.op_flags &
3124 HAMMER2_OPFLAG_DIRECTDATA) == 0);
3125 KKASSERT(parent->data != NULL);
3126 base = &parent->data->ipdata.u.blockset.blockref[0];
3127 count = HAMMER2_SET_COUNT;
3128 break;
3129 case HAMMER2_BREF_TYPE_INDIRECT:
3130 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3131 if (parent->flags & HAMMER2_CHAIN_INITIAL)
3132 base = NULL;
3133 else
3134 base = &parent->data->npdata[0];
3135 count = parent->bytes / sizeof(hammer2_blockref_t);
3136 break;
3137 case HAMMER2_BREF_TYPE_VOLUME:
3138 KKASSERT(parent->data != NULL);
3139 base = &parent->data->voldata.sroot_blockset.blockref[0];
3140 count = HAMMER2_SET_COUNT;
3141 break;
3142 case HAMMER2_BREF_TYPE_FREEMAP:
3143 KKASSERT(parent->data != NULL);
3144 base = &parent->data->blkset.blockref[0];
3145 count = HAMMER2_SET_COUNT;
3146 break;
3147 default:
3148 panic("hammer2_chain_create: unrecognized blockref type: %d",
3149 parent->bref.type);
3150 base = NULL;
3151 count = 0;
3152 break;
3156 * Make sure we've counted the brefs
3158 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3159 hammer2_chain_countbrefs(parent, base, count);
3161 KASSERT(parent->core.live_count >= 0 &&
3162 parent->core.live_count <= count,
3163 ("bad live_count %d/%d (%02x, %d)",
3164 parent->core.live_count, count,
3165 parent->bref.type, parent->bytes));
3168 * If no free blockref could be found we must create an indirect
3169 * block and move a number of blockrefs into it. With the parent
3170 * locked we can safely lock each child in order to delete+duplicate
3171 * it without causing a deadlock.
3173 * This may return the new indirect block or the old parent depending
3174 * on where the key falls. NULL is returned on error.
3176 if (parent->core.live_count == count) {
3177 hammer2_chain_t *nparent;
3179 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3180 mtid, type, &error);
3181 if (nparent == NULL) {
3182 if (allocated)
3183 hammer2_chain_drop(chain);
3184 chain = NULL;
3185 goto done;
3187 if (parent != nparent) {
3188 hammer2_chain_unlock(parent);
3189 hammer2_chain_drop(parent);
3190 parent = *parentp = nparent;
3192 goto again;
3195 if (chain->flags & HAMMER2_CHAIN_DELETED)
3196 kprintf("Inserting deleted chain @%016jx\n",
3197 chain->bref.key);
3200 * Link the chain into its parent.
3202 if (chain->parent != NULL)
3203 panic("hammer2: hammer2_chain_create: chain already connected");
3204 KKASSERT(chain->parent == NULL);
3205 hammer2_chain_insert(parent, chain,
3206 HAMMER2_CHAIN_INSERT_SPIN |
3207 HAMMER2_CHAIN_INSERT_LIVE,
3210 if (allocated) {
3212 * Mark the newly created chain modified. This will cause
3213 * UPDATE to be set and process the INITIAL flag.
3215 * Device buffers are not instantiated for DATA elements
3216 * as these are handled by logical buffers.
3218 * Indirect and freemap node indirect blocks are handled
3219 * by hammer2_chain_create_indirect() and not by this
3220 * function.
3222 * Data for all other bref types is expected to be
3223 * instantiated (INODE, LEAF).
3225 switch(chain->bref.type) {
3226 case HAMMER2_BREF_TYPE_DATA:
3227 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3228 case HAMMER2_BREF_TYPE_DIRENT:
3229 case HAMMER2_BREF_TYPE_INODE:
3230 hammer2_chain_modify(chain, mtid, dedup_off,
3231 HAMMER2_MODIFY_OPTDATA);
3232 break;
3233 default:
3235 * Remaining types are not supported by this function.
3236 * In particular, INDIRECT and LEAF_NODE types are
3237 * handled by create_indirect().
3239 panic("hammer2_chain_create: bad type: %d",
3240 chain->bref.type);
3241 /* NOT REACHED */
3242 break;
3244 } else {
3246 * When reconnecting a chain we must set UPDATE and
3247 * setflush so the flush recognizes that it must update
3248 * the bref in the parent.
3250 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3251 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3255 * We must setflush(parent) to ensure that it recurses through to
3256 * chain. setflush(chain) might not work because ONFLUSH is possibly
3257 * already set in the chain (so it won't recurse up to set it in the
3258 * parent).
3260 hammer2_chain_setflush(parent);
3262 done:
3263 *chainp = chain;
3265 return (error);
3269 * Move the chain from its old parent to a new parent. The chain must have
3270 * already been deleted or already disconnected (or never associated) with
3271 * a parent. The chain is reassociated with the new parent and the deleted
3272 * flag will be cleared (no longer deleted). The chain's modification state
3273 * is not altered.
3275 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3276 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3277 * FULL. This typically means that the caller is creating the chain after
3278 * doing a hammer2_chain_lookup().
3280 * A non-NULL bref is typically passed when key and keybits must be overridden.
3281 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3282 * from a passed-in bref and uses the old chain's bref for everything else.
3284 * Neither (parent) or (chain) can be errored.
3286 * If (parent) is non-NULL then the chain is inserted under the parent.
3288 * If (parent) is NULL then the newly duplicated chain is not inserted
3289 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3290 * passing into hammer2_chain_create() after this function returns).
3292 * WARNING! This function calls create which means it can insert indirect
3293 * blocks. This can cause other unrelated chains in the parent to
3294 * be moved to a newly inserted indirect block in addition to the
3295 * specific chain.
3297 void
3298 hammer2_chain_rename(hammer2_blockref_t *bref,
3299 hammer2_chain_t **parentp, hammer2_chain_t *chain,
3300 hammer2_tid_t mtid, int flags)
3302 hammer2_dev_t *hmp;
3303 hammer2_chain_t *parent;
3304 size_t bytes;
3307 * WARNING! We should never resolve DATA to device buffers
3308 * (XXX allow it if the caller did?), and since
3309 * we currently do not have the logical buffer cache
3310 * buffer in-hand to fix its cached physical offset
3311 * we also force the modify code to not COW it. XXX
3313 hmp = chain->hmp;
3314 KKASSERT(chain->parent == NULL);
3315 KKASSERT(chain->error == 0);
3318 * Now create a duplicate of the chain structure, associating
3319 * it with the same core, making it the same size, pointing it
3320 * to the same bref (the same media block).
3322 * NOTE: Handle special radix == 0 case (means 0 bytes).
3324 if (bref == NULL)
3325 bref = &chain->bref;
3326 bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3327 if (bytes)
3328 bytes = (hammer2_off_t)1 << bytes;
3331 * If parent is not NULL the duplicated chain will be entered under
3332 * the parent and the UPDATE bit set to tell flush to update
3333 * the blockref.
3335 * We must setflush(parent) to ensure that it recurses through to
3336 * chain. setflush(chain) might not work because ONFLUSH is possibly
3337 * already set in the chain (so it won't recurse up to set it in the
3338 * parent).
3340 * Having both chains locked is extremely important for atomicy.
3342 if (parentp && (parent = *parentp) != NULL) {
3343 KKASSERT(hammer2_mtx_owned(&parent->lock));
3344 KKASSERT(parent->refs > 0);
3345 KKASSERT(parent->error == 0);
3347 hammer2_chain_create(parentp, &chain,
3348 chain->pmp, HAMMER2_METH_DEFAULT,
3349 bref->key, bref->keybits, bref->type,
3350 chain->bytes, mtid, 0, flags);
3351 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3352 hammer2_chain_setflush(*parentp);
3357 * Helper function for deleting chains.
3359 * The chain is removed from the live view (the RBTREE) as well as the parent's
3360 * blockmap. Both chain and its parent must be locked.
3362 * parent may not be errored. chain can be errored.
3364 static void
3365 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3366 hammer2_tid_t mtid, int flags)
3368 hammer2_dev_t *hmp;
3370 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3371 HAMMER2_CHAIN_FICTITIOUS)) == 0);
3372 KKASSERT(chain->parent == parent);
3373 hmp = chain->hmp;
3375 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3377 * Chain is blockmapped, so there must be a parent.
3378 * Atomically remove the chain from the parent and remove
3379 * the blockmap entry. The parent must be set modified
3380 * to remove the blockmap entry.
3382 hammer2_blockref_t *base;
3383 int count;
3385 KKASSERT(parent != NULL);
3386 KKASSERT(parent->error == 0);
3387 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3388 hammer2_chain_modify(parent, mtid, 0, 0);
3391 * Calculate blockmap pointer
3393 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3394 hammer2_spin_ex(&chain->core.spin);
3395 hammer2_spin_ex(&parent->core.spin);
3397 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3398 atomic_add_int(&parent->core.live_count, -1);
3399 ++parent->core.generation;
3400 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3401 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3402 --parent->core.chain_count;
3403 chain->parent = NULL;
3405 switch(parent->bref.type) {
3406 case HAMMER2_BREF_TYPE_INODE:
3408 * Access the inode's block array. However, there
3409 * is no block array if the inode is flagged
3410 * DIRECTDATA.
3412 if (parent->data &&
3413 (parent->data->ipdata.meta.op_flags &
3414 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3415 base =
3416 &parent->data->ipdata.u.blockset.blockref[0];
3417 } else {
3418 base = NULL;
3420 count = HAMMER2_SET_COUNT;
3421 break;
3422 case HAMMER2_BREF_TYPE_INDIRECT:
3423 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3424 if (parent->data)
3425 base = &parent->data->npdata[0];
3426 else
3427 base = NULL;
3428 count = parent->bytes / sizeof(hammer2_blockref_t);
3429 break;
3430 case HAMMER2_BREF_TYPE_VOLUME:
3431 base = &parent->data->voldata.
3432 sroot_blockset.blockref[0];
3433 count = HAMMER2_SET_COUNT;
3434 break;
3435 case HAMMER2_BREF_TYPE_FREEMAP:
3436 base = &parent->data->blkset.blockref[0];
3437 count = HAMMER2_SET_COUNT;
3438 break;
3439 default:
3440 base = NULL;
3441 count = 0;
3442 panic("hammer2_flush_pass2: "
3443 "unrecognized blockref type: %d",
3444 parent->bref.type);
3448 * delete blockmapped chain from its parent.
3450 * The parent is not affected by any statistics in chain
3451 * which are pending synchronization. That is, there is
3452 * nothing to undo in the parent since they have not yet
3453 * been incorporated into the parent.
3455 * The parent is affected by statistics stored in inodes.
3456 * Those have already been synchronized, so they must be
3457 * undone. XXX split update possible w/delete in middle?
3459 if (base) {
3460 int cache_index = -1;
3461 hammer2_base_delete(parent, base, count,
3462 &cache_index, chain);
3464 hammer2_spin_unex(&parent->core.spin);
3465 hammer2_spin_unex(&chain->core.spin);
3466 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3468 * Chain is not blockmapped but a parent is present.
3469 * Atomically remove the chain from the parent. There is
3470 * no blockmap entry to remove.
3472 * Because chain was associated with a parent but not
3473 * synchronized, the chain's *_count_up fields contain
3474 * inode adjustment statistics which must be undone.
3476 hammer2_spin_ex(&chain->core.spin);
3477 hammer2_spin_ex(&parent->core.spin);
3478 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3479 atomic_add_int(&parent->core.live_count, -1);
3480 ++parent->core.generation;
3481 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3482 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3483 --parent->core.chain_count;
3484 chain->parent = NULL;
3485 hammer2_spin_unex(&parent->core.spin);
3486 hammer2_spin_unex(&chain->core.spin);
3487 } else {
3489 * Chain is not blockmapped and has no parent. This
3490 * is a degenerate case.
3492 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3497 * Create an indirect block that covers one or more of the elements in the
3498 * current parent. Either returns the existing parent with no locking or
3499 * ref changes or returns the new indirect block locked and referenced
3500 * and leaving the original parent lock/ref intact as well.
3502 * If an error occurs, NULL is returned and *errorp is set to the error.
3504 * The returned chain depends on where the specified key falls.
3506 * The key/keybits for the indirect mode only needs to follow three rules:
3508 * (1) That all elements underneath it fit within its key space and
3510 * (2) That all elements outside it are outside its key space.
3512 * (3) When creating the new indirect block any elements in the current
3513 * parent that fit within the new indirect block's keyspace must be
3514 * moved into the new indirect block.
3516 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3517 * keyspace the the current parent, but lookup/iteration rules will
3518 * ensure (and must ensure) that rule (2) for all parents leading up
3519 * to the nearest inode or the root volume header is adhered to. This
3520 * is accomplished by always recursing through matching keyspaces in
3521 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3523 * The current implementation calculates the current worst-case keyspace by
3524 * iterating the current parent and then divides it into two halves, choosing
3525 * whichever half has the most elements (not necessarily the half containing
3526 * the requested key).
3528 * We can also opt to use the half with the least number of elements. This
3529 * causes lower-numbered keys (aka logical file offsets) to recurse through
3530 * fewer indirect blocks and higher-numbered keys to recurse through more.
3531 * This also has the risk of not moving enough elements to the new indirect
3532 * block and being forced to create several indirect blocks before the element
3533 * can be inserted.
3535 * Must be called with an exclusively locked parent.
3537 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3538 hammer2_key_t *keyp, int keybits,
3539 hammer2_blockref_t *base, int count);
3540 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3541 hammer2_key_t *keyp, int keybits,
3542 hammer2_blockref_t *base, int count,
3543 int ncount);
3544 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3545 hammer2_key_t *keyp, int keybits,
3546 hammer2_blockref_t *base, int count,
3547 int ncount);
3548 static
3549 hammer2_chain_t *
3550 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3551 hammer2_key_t create_key, int create_bits,
3552 hammer2_tid_t mtid, int for_type, int *errorp)
3554 hammer2_dev_t *hmp;
3555 hammer2_blockref_t *base;
3556 hammer2_blockref_t *bref;
3557 hammer2_blockref_t bcopy;
3558 hammer2_chain_t *chain;
3559 hammer2_chain_t *ichain;
3560 hammer2_chain_t dummy;
3561 hammer2_key_t key = create_key;
3562 hammer2_key_t key_beg;
3563 hammer2_key_t key_end;
3564 hammer2_key_t key_next;
3565 int keybits = create_bits;
3566 int count;
3567 int ncount;
3568 int nbytes;
3569 int cache_index;
3570 int loops;
3571 int reason;
3572 int generation;
3573 int maxloops = 300000;
3576 * Calculate the base blockref pointer or NULL if the chain
3577 * is known to be empty. We need to calculate the array count
3578 * for RB lookups either way.
3580 hmp = parent->hmp;
3581 *errorp = 0;
3582 KKASSERT(hammer2_mtx_owned(&parent->lock));
3584 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3585 base = hammer2_chain_base_and_count(parent, &count);
3588 * dummy used in later chain allocation (no longer used for lookups).
3590 bzero(&dummy, sizeof(dummy));
3593 * How big should our new indirect block be? It has to be at least
3594 * as large as its parent for splits to work properly.
3596 * The freemap uses a specific indirect block size. The number of
3597 * levels are built dynamically and ultimately depend on the size
3598 * volume. Because freemap blocks are taken from the reserved areas
3599 * of the volume our goal is efficiency (fewer levels) and not so
3600 * much to save disk space.
3602 * The first indirect block level for a directory usually uses
3603 * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries). Due to
3604 * the hash mechanism, this typically gives us a nominal
3605 * 32 * 4 entries with one level of indirection.
3607 * We use HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs) for FILE
3608 * indirect blocks. The initial 4 entries in the inode gives us
3609 * 256KB. Up to 4 indirect blocks gives us 32MB. Three levels
3610 * of indirection gives us 137GB, and so forth. H2 can support
3611 * huge file sizes but they are not typical, so we try to stick
3612 * with compactness and do not use a larger indirect block size.
3614 * We could use 64KB (PBUFSIZE), giving us 512 blockrefs, but
3615 * due to the way indirect blocks are created this usually winds
3616 * up being extremely inefficient for small files. Even though
3617 * 16KB requires more levels of indirection for very large files,
3618 * the 16KB records can be ganged together into 64KB DIOs.
3620 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3621 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3622 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3623 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3624 if (parent->data->ipdata.meta.type ==
3625 HAMMER2_OBJTYPE_DIRECTORY)
3626 nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3627 else
3628 nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3630 } else {
3631 nbytes = HAMMER2_IND_BYTES_NOM;
3633 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3634 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3635 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3636 nbytes = count * sizeof(hammer2_blockref_t);
3638 ncount = nbytes / sizeof(hammer2_blockref_t);
3641 * When creating an indirect block for a freemap node or leaf
3642 * the key/keybits must be fitted to static radix levels because
3643 * particular radix levels use particular reserved blocks in the
3644 * related zone.
3646 * This routine calculates the key/radix of the indirect block
3647 * we need to create, and whether it is on the high-side or the
3648 * low-side.
3650 switch(for_type) {
3651 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3652 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3653 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3654 base, count);
3655 break;
3656 case HAMMER2_BREF_TYPE_DATA:
3657 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3658 base, count, ncount);
3659 break;
3660 case HAMMER2_BREF_TYPE_DIRENT:
3661 case HAMMER2_BREF_TYPE_INODE:
3662 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3663 base, count, ncount);
3664 break;
3665 default:
3666 panic("illegal indirect block for bref type %d", for_type);
3667 break;
3671 * Normalize the key for the radix being represented, keeping the
3672 * high bits and throwing away the low bits.
3674 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3677 * Ok, create our new indirect block
3679 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3680 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3681 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3682 } else {
3683 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3685 dummy.bref.key = key;
3686 dummy.bref.keybits = keybits;
3687 dummy.bref.data_off = hammer2_getradix(nbytes);
3688 dummy.bref.methods =
3689 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3690 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3692 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3693 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3694 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3695 /* ichain has one ref at this point */
3698 * We have to mark it modified to allocate its block, but use
3699 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3700 * it won't be acted upon by the flush code.
3702 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3705 * Iterate the original parent and move the matching brefs into
3706 * the new indirect block.
3708 * XXX handle flushes.
3710 key_beg = 0;
3711 key_end = HAMMER2_KEY_MAX;
3712 key_next = 0; /* avoid gcc warnings */
3713 cache_index = 0;
3714 hammer2_spin_ex(&parent->core.spin);
3715 loops = 0;
3716 reason = 0;
3718 for (;;) {
3720 * Parent may have been modified, relocating its block array.
3721 * Reload the base pointer.
3723 base = hammer2_chain_base_and_count(parent, &count);
3725 if (++loops > 100000) {
3726 hammer2_spin_unex(&parent->core.spin);
3727 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3728 reason, parent, base, count, key_next);
3732 * NOTE: spinlock stays intact, returned chain (if not NULL)
3733 * is not referenced or locked which means that we
3734 * cannot safely check its flagged / deletion status
3735 * until we lock it.
3737 chain = hammer2_combined_find(parent, base, count,
3738 &cache_index, &key_next,
3739 key_beg, key_end,
3740 &bref);
3741 generation = parent->core.generation;
3742 if (bref == NULL)
3743 break;
3744 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3747 * Skip keys that are not within the key/radix of the new
3748 * indirect block. They stay in the parent.
3750 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3751 (key ^ bref->key)) != 0) {
3752 goto next_key_spinlocked;
3756 * Load the new indirect block by acquiring the related
3757 * chains (potentially from media as it might not be
3758 * in-memory). Then move it to the new parent (ichain).
3760 * chain is referenced but not locked. We must lock the
3761 * chain to obtain definitive state.
3763 if (chain) {
3765 * Use chain already present in the RBTREE
3767 hammer2_chain_ref(chain);
3768 hammer2_spin_unex(&parent->core.spin);
3769 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3770 } else {
3772 * Get chain for blockref element. _get returns NULL
3773 * on insertion race.
3775 bcopy = *bref;
3776 hammer2_spin_unex(&parent->core.spin);
3777 chain = hammer2_chain_get(parent, generation, &bcopy);
3778 if (chain == NULL) {
3779 reason = 1;
3780 hammer2_spin_ex(&parent->core.spin);
3781 continue;
3783 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3784 kprintf("REASON 2\n");
3785 reason = 2;
3786 hammer2_chain_drop(chain);
3787 hammer2_spin_ex(&parent->core.spin);
3788 continue;
3790 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3794 * This is always live so if the chain has been deleted
3795 * we raced someone and we have to retry.
3797 * NOTE: Lookups can race delete-duplicate because
3798 * delete-duplicate does not lock the parent's core
3799 * (they just use the spinlock on the core).
3801 * (note reversed logic for this one)
3803 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3804 hammer2_chain_unlock(chain);
3805 hammer2_chain_drop(chain);
3806 goto next_key;
3810 * Shift the chain to the indirect block.
3812 * WARNING! No reason for us to load chain data, pass NOSTATS
3813 * to prevent delete/insert from trying to access
3814 * inode stats (and thus asserting if there is no
3815 * chain->data loaded).
3817 * WARNING! The (parent, chain) deletion may modify the parent
3818 * and invalidate the base pointer.
3820 hammer2_chain_delete(parent, chain, mtid, 0);
3821 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3822 hammer2_chain_unlock(chain);
3823 hammer2_chain_drop(chain);
3824 KKASSERT(parent->refs > 0);
3825 chain = NULL;
3826 base = NULL; /* safety */
3827 next_key:
3828 hammer2_spin_ex(&parent->core.spin);
3829 next_key_spinlocked:
3830 if (--maxloops == 0)
3831 panic("hammer2_chain_create_indirect: maxloops");
3832 reason = 4;
3833 if (key_next == 0 || key_next > key_end)
3834 break;
3835 key_beg = key_next;
3836 /* loop */
3838 hammer2_spin_unex(&parent->core.spin);
3841 * Insert the new indirect block into the parent now that we've
3842 * cleared out some entries in the parent. We calculated a good
3843 * insertion index in the loop above (ichain->index).
3845 * We don't have to set UPDATE here because we mark ichain
3846 * modified down below (so the normal modified -> flush -> set-moved
3847 * sequence applies).
3849 * The insertion shouldn't race as this is a completely new block
3850 * and the parent is locked.
3852 base = NULL; /* safety, parent modify may change address */
3853 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3854 hammer2_chain_insert(parent, ichain,
3855 HAMMER2_CHAIN_INSERT_SPIN |
3856 HAMMER2_CHAIN_INSERT_LIVE,
3860 * Make sure flushes propogate after our manual insertion.
3862 hammer2_chain_setflush(ichain);
3863 hammer2_chain_setflush(parent);
3866 * Figure out what to return.
3868 if (~(((hammer2_key_t)1 << keybits) - 1) &
3869 (create_key ^ key)) {
3871 * Key being created is outside the key range,
3872 * return the original parent.
3874 hammer2_chain_unlock(ichain);
3875 hammer2_chain_drop(ichain);
3876 } else {
3878 * Otherwise its in the range, return the new parent.
3879 * (leave both the new and old parent locked).
3881 parent = ichain;
3884 return(parent);
3888 * Freemap indirect blocks
3890 * Calculate the keybits and highside/lowside of the freemap node the
3891 * caller is creating.
3893 * This routine will specify the next higher-level freemap key/radix
3894 * representing the lowest-ordered set. By doing so, eventually all
3895 * low-ordered sets will be moved one level down.
3897 * We have to be careful here because the freemap reserves a limited
3898 * number of blocks for a limited number of levels. So we can't just
3899 * push indiscriminately.
3902 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3903 int keybits, hammer2_blockref_t *base, int count)
3905 hammer2_chain_t *chain;
3906 hammer2_blockref_t *bref;
3907 hammer2_key_t key;
3908 hammer2_key_t key_beg;
3909 hammer2_key_t key_end;
3910 hammer2_key_t key_next;
3911 int cache_index;
3912 int locount;
3913 int hicount;
3914 int maxloops = 300000;
3916 key = *keyp;
3917 locount = 0;
3918 hicount = 0;
3919 keybits = 64;
3922 * Calculate the range of keys in the array being careful to skip
3923 * slots which are overridden with a deletion.
3925 key_beg = 0;
3926 key_end = HAMMER2_KEY_MAX;
3927 cache_index = 0;
3928 hammer2_spin_ex(&parent->core.spin);
3930 for (;;) {
3931 if (--maxloops == 0) {
3932 panic("indkey_freemap shit %p %p:%d\n",
3933 parent, base, count);
3935 chain = hammer2_combined_find(parent, base, count,
3936 &cache_index, &key_next,
3937 key_beg, key_end,
3938 &bref);
3941 * Exhausted search
3943 if (bref == NULL)
3944 break;
3947 * Skip deleted chains.
3949 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3950 if (key_next == 0 || key_next > key_end)
3951 break;
3952 key_beg = key_next;
3953 continue;
3957 * Use the full live (not deleted) element for the scan
3958 * iteration. HAMMER2 does not allow partial replacements.
3960 * XXX should be built into hammer2_combined_find().
3962 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3964 if (keybits > bref->keybits) {
3965 key = bref->key;
3966 keybits = bref->keybits;
3967 } else if (keybits == bref->keybits && bref->key < key) {
3968 key = bref->key;
3970 if (key_next == 0)
3971 break;
3972 key_beg = key_next;
3974 hammer2_spin_unex(&parent->core.spin);
3977 * Return the keybits for a higher-level FREEMAP_NODE covering
3978 * this node.
3980 switch(keybits) {
3981 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3982 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3983 break;
3984 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3985 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3986 break;
3987 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3988 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3989 break;
3990 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3991 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3992 break;
3993 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3994 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3995 break;
3996 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3997 panic("hammer2_chain_indkey_freemap: level too high");
3998 break;
3999 default:
4000 panic("hammer2_chain_indkey_freemap: bad radix");
4001 break;
4003 *keyp = key;
4005 return (keybits);
4009 * File indirect blocks
4011 * Calculate the key/keybits for the indirect block to create by scanning
4012 * existing keys. The key being created is also passed in *keyp and can be
4013 * inside or outside the indirect block. Regardless, the indirect block
4014 * must hold at least two keys in order to guarantee sufficient space.
4016 * We use a modified version of the freemap's fixed radix tree, but taylored
4017 * for file data. Basically we configure an indirect block encompassing the
4018 * smallest key.
4020 static int
4021 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
4022 int keybits, hammer2_blockref_t *base, int count,
4023 int ncount)
4025 hammer2_chain_t *chain;
4026 hammer2_blockref_t *bref;
4027 hammer2_key_t key;
4028 hammer2_key_t key_beg;
4029 hammer2_key_t key_end;
4030 hammer2_key_t key_next;
4031 int nradix;
4032 int cache_index;
4033 int locount;
4034 int hicount;
4035 int maxloops = 300000;
4037 key = *keyp;
4038 locount = 0;
4039 hicount = 0;
4040 keybits = 64;
4043 * Calculate the range of keys in the array being careful to skip
4044 * slots which are overridden with a deletion.
4046 * Locate the smallest key.
4048 key_beg = 0;
4049 key_end = HAMMER2_KEY_MAX;
4050 cache_index = 0;
4051 hammer2_spin_ex(&parent->core.spin);
4053 for (;;) {
4054 if (--maxloops == 0) {
4055 panic("indkey_freemap shit %p %p:%d\n",
4056 parent, base, count);
4058 chain = hammer2_combined_find(parent, base, count,
4059 &cache_index, &key_next,
4060 key_beg, key_end,
4061 &bref);
4064 * Exhausted search
4066 if (bref == NULL)
4067 break;
4070 * Skip deleted chains.
4072 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4073 if (key_next == 0 || key_next > key_end)
4074 break;
4075 key_beg = key_next;
4076 continue;
4080 * Use the full live (not deleted) element for the scan
4081 * iteration. HAMMER2 does not allow partial replacements.
4083 * XXX should be built into hammer2_combined_find().
4085 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4087 if (keybits > bref->keybits) {
4088 key = bref->key;
4089 keybits = bref->keybits;
4090 } else if (keybits == bref->keybits && bref->key < key) {
4091 key = bref->key;
4093 if (key_next == 0)
4094 break;
4095 key_beg = key_next;
4097 hammer2_spin_unex(&parent->core.spin);
4100 * Calculate the static keybits for a higher-level indirect block
4101 * that contains the key.
4103 *keyp = key;
4105 switch(ncount) {
4106 case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
4107 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
4108 break;
4109 case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
4110 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
4111 break;
4112 case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
4113 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
4114 break;
4115 default:
4116 panic("bad ncount %d\n", ncount);
4117 nradix = 0;
4118 break;
4122 * The largest radix that can be returned for an indirect block is
4123 * 63 bits. (The largest practical indirect block radix is actually
4124 * 62 bits because the top-level inode or volume root contains four
4125 * entries, but allow 63 to be returned).
4127 if (nradix >= 64)
4128 nradix = 63;
4130 return keybits + nradix;
4133 #if 1
4136 * Directory indirect blocks.
4138 * Covers both the inode index (directory of inodes), and directory contents
4139 * (filenames hardlinked to inodes).
4141 * Because directory keys are hashed we generally try to cut the space in
4142 * half. We accomodate the inode index (which tends to have linearly
4143 * increasing inode numbers) by ensuring that the keyspace is at least large
4144 * enough to fill up the indirect block being created.
4146 static int
4147 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4148 int keybits, hammer2_blockref_t *base, int count,
4149 int ncount)
4151 hammer2_blockref_t *bref;
4152 hammer2_chain_t *chain;
4153 hammer2_key_t key_beg;
4154 hammer2_key_t key_end;
4155 hammer2_key_t key_next;
4156 hammer2_key_t key;
4157 int nkeybits;
4158 int locount;
4159 int hicount;
4160 int cache_index;
4161 int maxloops = 300000;
4164 * Shortcut if the parent is the inode. In this situation the
4165 * parent has 4+1 directory entries and we are creating an indirect
4166 * block capable of holding many more.
4168 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4169 return 63;
4172 key = *keyp;
4173 locount = 0;
4174 hicount = 0;
4177 * Calculate the range of keys in the array being careful to skip
4178 * slots which are overridden with a deletion.
4180 key_beg = 0;
4181 key_end = HAMMER2_KEY_MAX;
4182 cache_index = 0;
4183 hammer2_spin_ex(&parent->core.spin);
4185 for (;;) {
4186 if (--maxloops == 0) {
4187 panic("indkey_freemap shit %p %p:%d\n",
4188 parent, base, count);
4190 chain = hammer2_combined_find(parent, base, count,
4191 &cache_index, &key_next,
4192 key_beg, key_end,
4193 &bref);
4196 * Exhausted search
4198 if (bref == NULL)
4199 break;
4202 * Deleted object
4204 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4205 if (key_next == 0 || key_next > key_end)
4206 break;
4207 key_beg = key_next;
4208 continue;
4212 * Use the full live (not deleted) element for the scan
4213 * iteration. HAMMER2 does not allow partial replacements.
4215 * XXX should be built into hammer2_combined_find().
4217 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4220 * Expand our calculated key range (key, keybits) to fit
4221 * the scanned key. nkeybits represents the full range
4222 * that we will later cut in half (two halves @ nkeybits - 1).
4224 nkeybits = keybits;
4225 if (nkeybits < bref->keybits) {
4226 if (bref->keybits > 64) {
4227 kprintf("bad bref chain %p bref %p\n",
4228 chain, bref);
4229 Debugger("fubar");
4231 nkeybits = bref->keybits;
4233 while (nkeybits < 64 &&
4234 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4235 (key ^ bref->key)) != 0) {
4236 ++nkeybits;
4240 * If the new key range is larger we have to determine
4241 * which side of the new key range the existing keys fall
4242 * under by checking the high bit, then collapsing the
4243 * locount into the hicount or vise-versa.
4245 if (keybits != nkeybits) {
4246 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4247 hicount += locount;
4248 locount = 0;
4249 } else {
4250 locount += hicount;
4251 hicount = 0;
4253 keybits = nkeybits;
4257 * The newly scanned key will be in the lower half or the
4258 * upper half of the (new) key range.
4260 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4261 ++hicount;
4262 else
4263 ++locount;
4265 if (key_next == 0)
4266 break;
4267 key_beg = key_next;
4269 hammer2_spin_unex(&parent->core.spin);
4270 bref = NULL; /* now invalid (safety) */
4273 * Adjust keybits to represent half of the full range calculated
4274 * above (radix 63 max) for our new indirect block.
4276 --keybits;
4279 * Expand keybits to hold at least ncount elements. ncount will be
4280 * a power of 2. This is to try to completely fill leaf nodes (at
4281 * least for keys which are not hashes).
4283 * We aren't counting 'in' or 'out', we are counting 'high side'
4284 * and 'low side' based on the bit at (1LL << keybits). We want
4285 * everything to be inside in these cases so shift it all to
4286 * the low or high side depending on the new high bit.
4288 while (((hammer2_key_t)1 << keybits) < ncount) {
4289 ++keybits;
4290 if (key & ((hammer2_key_t)1 << keybits)) {
4291 hicount += locount;
4292 locount = 0;
4293 } else {
4294 locount += hicount;
4295 hicount = 0;
4299 if (hicount > locount)
4300 key |= (hammer2_key_t)1 << keybits;
4301 else
4302 key &= ~(hammer2_key_t)1 << keybits;
4304 *keyp = key;
4306 return (keybits);
4309 #else
4312 * Directory indirect blocks.
4314 * Covers both the inode index (directory of inodes), and directory contents
4315 * (filenames hardlinked to inodes).
4317 * Because directory keys are hashed we generally try to cut the space in
4318 * half. We accomodate the inode index (which tends to have linearly
4319 * increasing inode numbers) by ensuring that the keyspace is at least large
4320 * enough to fill up the indirect block being created.
4322 static int
4323 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4324 int keybits, hammer2_blockref_t *base, int count,
4325 int ncount)
4327 hammer2_blockref_t *bref;
4328 hammer2_chain_t *chain;
4329 hammer2_key_t key_beg;
4330 hammer2_key_t key_end;
4331 hammer2_key_t key_next;
4332 hammer2_key_t key;
4333 int nkeybits;
4334 int locount;
4335 int hicount;
4336 int cache_index;
4337 int maxloops = 300000;
4340 * Shortcut if the parent is the inode. In this situation the
4341 * parent has 4+1 directory entries and we are creating an indirect
4342 * block capable of holding many more.
4344 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4345 return 63;
4348 key = *keyp;
4349 locount = 0;
4350 hicount = 0;
4353 * Calculate the range of keys in the array being careful to skip
4354 * slots which are overridden with a deletion.
4356 key_beg = 0;
4357 key_end = HAMMER2_KEY_MAX;
4358 cache_index = 0;
4359 hammer2_spin_ex(&parent->core.spin);
4361 for (;;) {
4362 if (--maxloops == 0) {
4363 panic("indkey_freemap shit %p %p:%d\n",
4364 parent, base, count);
4366 chain = hammer2_combined_find(parent, base, count,
4367 &cache_index, &key_next,
4368 key_beg, key_end,
4369 &bref);
4372 * Exhausted search
4374 if (bref == NULL)
4375 break;
4378 * Deleted object
4380 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4381 if (key_next == 0 || key_next > key_end)
4382 break;
4383 key_beg = key_next;
4384 continue;
4388 * Use the full live (not deleted) element for the scan
4389 * iteration. HAMMER2 does not allow partial replacements.
4391 * XXX should be built into hammer2_combined_find().
4393 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4396 * Expand our calculated key range (key, keybits) to fit
4397 * the scanned key. nkeybits represents the full range
4398 * that we will later cut in half (two halves @ nkeybits - 1).
4400 nkeybits = keybits;
4401 if (nkeybits < bref->keybits) {
4402 if (bref->keybits > 64) {
4403 kprintf("bad bref chain %p bref %p\n",
4404 chain, bref);
4405 Debugger("fubar");
4407 nkeybits = bref->keybits;
4409 while (nkeybits < 64 &&
4410 (~(((hammer2_key_t)1 << nkeybits) - 1) &
4411 (key ^ bref->key)) != 0) {
4412 ++nkeybits;
4416 * If the new key range is larger we have to determine
4417 * which side of the new key range the existing keys fall
4418 * under by checking the high bit, then collapsing the
4419 * locount into the hicount or vise-versa.
4421 if (keybits != nkeybits) {
4422 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4423 hicount += locount;
4424 locount = 0;
4425 } else {
4426 locount += hicount;
4427 hicount = 0;
4429 keybits = nkeybits;
4433 * The newly scanned key will be in the lower half or the
4434 * upper half of the (new) key range.
4436 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4437 ++hicount;
4438 else
4439 ++locount;
4441 if (key_next == 0)
4442 break;
4443 key_beg = key_next;
4445 hammer2_spin_unex(&parent->core.spin);
4446 bref = NULL; /* now invalid (safety) */
4449 * Adjust keybits to represent half of the full range calculated
4450 * above (radix 63 max) for our new indirect block.
4452 --keybits;
4455 * Expand keybits to hold at least ncount elements. ncount will be
4456 * a power of 2. This is to try to completely fill leaf nodes (at
4457 * least for keys which are not hashes).
4459 * We aren't counting 'in' or 'out', we are counting 'high side'
4460 * and 'low side' based on the bit at (1LL << keybits). We want
4461 * everything to be inside in these cases so shift it all to
4462 * the low or high side depending on the new high bit.
4464 while (((hammer2_key_t)1 << keybits) < ncount) {
4465 ++keybits;
4466 if (key & ((hammer2_key_t)1 << keybits)) {
4467 hicount += locount;
4468 locount = 0;
4469 } else {
4470 locount += hicount;
4471 hicount = 0;
4475 if (hicount > locount)
4476 key |= (hammer2_key_t)1 << keybits;
4477 else
4478 key &= ~(hammer2_key_t)1 << keybits;
4480 *keyp = key;
4482 return (keybits);
4485 #endif
4488 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4489 * it exists.
4491 * Both parent and chain must be locked exclusively.
4493 * This function will modify the parent if the blockref requires removal
4494 * from the parent's block table.
4496 * This function is NOT recursive. Any entity already pushed into the
4497 * chain (such as an inode) may still need visibility into its contents,
4498 * as well as the ability to read and modify the contents. For example,
4499 * for an unlinked file which is still open.
4501 * Also note that the flusher is responsible for cleaning up empty
4502 * indirect blocks.
4504 void
4505 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4506 hammer2_tid_t mtid, int flags)
4508 KKASSERT(hammer2_mtx_owned(&chain->lock));
4511 * Nothing to do if already marked.
4513 * We need the spinlock on the core whos RBTREE contains chain
4514 * to protect against races.
4516 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4517 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4518 chain->parent == parent);
4519 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4523 * Permanent deletions mark the chain as destroyed.
4525 if (flags & HAMMER2_DELETE_PERMANENT)
4526 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4527 hammer2_chain_setflush(chain);
4531 * Returns the index of the nearest element in the blockref array >= elm.
4532 * Returns (count) if no element could be found.
4534 * Sets *key_nextp to the next key for loop purposes but does not modify
4535 * it if the next key would be higher than the current value of *key_nextp.
4536 * Note that *key_nexp can overflow to 0, which should be tested by the
4537 * caller.
4539 * (*cache_indexp) is a heuristic and can be any value without effecting
4540 * the result.
4542 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4543 * held through the operation.
4545 static int
4546 hammer2_base_find(hammer2_chain_t *parent,
4547 hammer2_blockref_t *base, int count,
4548 int *cache_indexp, hammer2_key_t *key_nextp,
4549 hammer2_key_t key_beg, hammer2_key_t key_end)
4551 hammer2_blockref_t *scan;
4552 hammer2_key_t scan_end;
4553 int i;
4554 int limit;
4557 * Require the live chain's already have their core's counted
4558 * so we can optimize operations.
4560 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4563 * Degenerate case
4565 if (count == 0 || base == NULL)
4566 return(count);
4569 * Sequential optimization using *cache_indexp. This is the most
4570 * likely scenario.
4572 * We can avoid trailing empty entries on live chains, otherwise
4573 * we might have to check the whole block array.
4575 i = *cache_indexp;
4576 cpu_ccfence();
4577 limit = parent->core.live_zero;
4578 if (i >= limit)
4579 i = limit - 1;
4580 if (i < 0)
4581 i = 0;
4582 KKASSERT(i < count);
4585 * Search backwards
4587 scan = &base[i];
4588 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4589 --scan;
4590 --i;
4592 *cache_indexp = i;
4595 * Search forwards, stop when we find a scan element which
4596 * encloses the key or until we know that there are no further
4597 * elements.
4599 while (i < count) {
4600 if (scan->type != 0) {
4601 scan_end = scan->key +
4602 ((hammer2_key_t)1 << scan->keybits) - 1;
4603 if (scan->key > key_beg || scan_end >= key_beg)
4604 break;
4606 if (i >= limit)
4607 return (count);
4608 ++scan;
4609 ++i;
4611 if (i != count) {
4612 *cache_indexp = i;
4613 if (i >= limit) {
4614 i = count;
4615 } else {
4616 scan_end = scan->key +
4617 ((hammer2_key_t)1 << scan->keybits);
4618 if (scan_end && (*key_nextp > scan_end ||
4619 *key_nextp == 0)) {
4620 *key_nextp = scan_end;
4624 return (i);
4628 * Do a combined search and return the next match either from the blockref
4629 * array or from the in-memory chain. Sets *bresp to the returned bref in
4630 * both cases, or sets it to NULL if the search exhausted. Only returns
4631 * a non-NULL chain if the search matched from the in-memory chain.
4633 * When no in-memory chain has been found and a non-NULL bref is returned
4634 * in *bresp.
4637 * The returned chain is not locked or referenced. Use the returned bref
4638 * to determine if the search exhausted or not. Iterate if the base find
4639 * is chosen but matches a deleted chain.
4641 * WARNING! Must be called with parent's spinlock held. Spinlock remains
4642 * held through the operation.
4644 static hammer2_chain_t *
4645 hammer2_combined_find(hammer2_chain_t *parent,
4646 hammer2_blockref_t *base, int count,
4647 int *cache_indexp, hammer2_key_t *key_nextp,
4648 hammer2_key_t key_beg, hammer2_key_t key_end,
4649 hammer2_blockref_t **bresp)
4651 hammer2_blockref_t *bref;
4652 hammer2_chain_t *chain;
4653 int i;
4656 * Lookup in block array and in rbtree.
4658 *key_nextp = key_end + 1;
4659 i = hammer2_base_find(parent, base, count, cache_indexp,
4660 key_nextp, key_beg, key_end);
4661 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4664 * Neither matched
4666 if (i == count && chain == NULL) {
4667 *bresp = NULL;
4668 return(NULL);
4672 * Only chain matched.
4674 if (i == count) {
4675 bref = &chain->bref;
4676 goto found;
4680 * Only blockref matched.
4682 if (chain == NULL) {
4683 bref = &base[i];
4684 goto found;
4688 * Both in-memory and blockref matched, select the nearer element.
4690 * If both are flush with the left-hand side or both are the
4691 * same distance away, select the chain. In this situation the
4692 * chain must have been loaded from the matching blockmap.
4694 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4695 chain->bref.key == base[i].key) {
4696 KKASSERT(chain->bref.key == base[i].key);
4697 bref = &chain->bref;
4698 goto found;
4702 * Select the nearer key
4704 if (chain->bref.key < base[i].key) {
4705 bref = &chain->bref;
4706 } else {
4707 bref = &base[i];
4708 chain = NULL;
4712 * If the bref is out of bounds we've exhausted our search.
4714 found:
4715 if (bref->key > key_end) {
4716 *bresp = NULL;
4717 chain = NULL;
4718 } else {
4719 *bresp = bref;
4721 return(chain);
4725 * Locate the specified block array element and delete it. The element
4726 * must exist.
4728 * The spin lock on the related chain must be held.
4730 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4731 * need to be adjusted when we commit the media change.
4733 void
4734 hammer2_base_delete(hammer2_chain_t *parent,
4735 hammer2_blockref_t *base, int count,
4736 int *cache_indexp, hammer2_chain_t *chain)
4738 hammer2_blockref_t *elm = &chain->bref;
4739 hammer2_blockref_t *scan;
4740 hammer2_key_t key_next;
4741 int i;
4744 * Delete element. Expect the element to exist.
4746 * XXX see caller, flush code not yet sophisticated enough to prevent
4747 * re-flushed in some cases.
4749 key_next = 0; /* max range */
4750 i = hammer2_base_find(parent, base, count, cache_indexp,
4751 &key_next, elm->key, elm->key);
4752 scan = &base[i];
4753 if (i == count || scan->type == 0 ||
4754 scan->key != elm->key ||
4755 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4756 scan->keybits != elm->keybits)) {
4757 hammer2_spin_unex(&parent->core.spin);
4758 panic("delete base %p element not found at %d/%d elm %p\n",
4759 base, i, count, elm);
4760 return;
4764 * Update stats and zero the entry.
4766 * NOTE: Handle radix == 0 (0 bytes) case.
4768 if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4769 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4770 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4772 switch(scan->type) {
4773 case HAMMER2_BREF_TYPE_INODE:
4774 parent->bref.embed.stats.inode_count -= 1;
4775 /* fall through */
4776 case HAMMER2_BREF_TYPE_DATA:
4777 case HAMMER2_BREF_TYPE_INDIRECT:
4778 parent->bref.embed.stats.data_count -=
4779 scan->embed.stats.data_count;
4780 parent->bref.embed.stats.inode_count -=
4781 scan->embed.stats.inode_count;
4782 break;
4783 default:
4784 break;
4787 bzero(scan, sizeof(*scan));
4790 * We can only optimize parent->core.live_zero for live chains.
4792 if (parent->core.live_zero == i + 1) {
4793 while (--i >= 0 && base[i].type == 0)
4795 parent->core.live_zero = i + 1;
4799 * Clear appropriate blockmap flags in chain.
4801 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4802 HAMMER2_CHAIN_BMAPUPD);
4806 * Insert the specified element. The block array must not already have the
4807 * element and must have space available for the insertion.
4809 * The spin lock on the related chain must be held.
4811 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4812 * need to be adjusted when we commit the media change.
4814 void
4815 hammer2_base_insert(hammer2_chain_t *parent,
4816 hammer2_blockref_t *base, int count,
4817 int *cache_indexp, hammer2_chain_t *chain)
4819 hammer2_blockref_t *elm = &chain->bref;
4820 hammer2_key_t key_next;
4821 hammer2_key_t xkey;
4822 int i;
4823 int j;
4824 int k;
4825 int l;
4826 int u = 1;
4829 * Insert new element. Expect the element to not already exist
4830 * unless we are replacing it.
4832 * XXX see caller, flush code not yet sophisticated enough to prevent
4833 * re-flushed in some cases.
4835 key_next = 0; /* max range */
4836 i = hammer2_base_find(parent, base, count, cache_indexp,
4837 &key_next, elm->key, elm->key);
4840 * Shortcut fill optimization, typical ordered insertion(s) may not
4841 * require a search.
4843 KKASSERT(i >= 0 && i <= count);
4846 * Set appropriate blockmap flags in chain.
4848 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4851 * Update stats and zero the entry
4853 if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4854 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4855 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4857 switch(elm->type) {
4858 case HAMMER2_BREF_TYPE_INODE:
4859 parent->bref.embed.stats.inode_count += 1;
4860 /* fall through */
4861 case HAMMER2_BREF_TYPE_DATA:
4862 case HAMMER2_BREF_TYPE_INDIRECT:
4863 parent->bref.embed.stats.data_count +=
4864 elm->embed.stats.data_count;
4865 parent->bref.embed.stats.inode_count +=
4866 elm->embed.stats.inode_count;
4867 break;
4868 default:
4869 break;
4874 * We can only optimize parent->core.live_zero for live chains.
4876 if (i == count && parent->core.live_zero < count) {
4877 i = parent->core.live_zero++;
4878 base[i] = *elm;
4879 return;
4882 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4883 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4884 hammer2_spin_unex(&parent->core.spin);
4885 panic("insert base %p overlapping elements at %d elm %p\n",
4886 base, i, elm);
4890 * Try to find an empty slot before or after.
4892 j = i;
4893 k = i;
4894 while (j > 0 || k < count) {
4895 --j;
4896 if (j >= 0 && base[j].type == 0) {
4897 if (j == i - 1) {
4898 base[j] = *elm;
4899 } else {
4900 bcopy(&base[j+1], &base[j],
4901 (i - j - 1) * sizeof(*base));
4902 base[i - 1] = *elm;
4904 goto validate;
4906 ++k;
4907 if (k < count && base[k].type == 0) {
4908 bcopy(&base[i], &base[i+1],
4909 (k - i) * sizeof(hammer2_blockref_t));
4910 base[i] = *elm;
4913 * We can only update parent->core.live_zero for live
4914 * chains.
4916 if (parent->core.live_zero <= k)
4917 parent->core.live_zero = k + 1;
4918 u = 2;
4919 goto validate;
4922 panic("hammer2_base_insert: no room!");
4925 * Debugging
4927 validate:
4928 key_next = 0;
4929 for (l = 0; l < count; ++l) {
4930 if (base[l].type) {
4931 key_next = base[l].key +
4932 ((hammer2_key_t)1 << base[l].keybits) - 1;
4933 break;
4936 while (++l < count) {
4937 if (base[l].type) {
4938 if (base[l].key <= key_next)
4939 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4940 key_next = base[l].key +
4941 ((hammer2_key_t)1 << base[l].keybits) - 1;
4948 #if 0
4951 * Sort the blockref array for the chain. Used by the flush code to
4952 * sort the blockref[] array.
4954 * The chain must be exclusively locked AND spin-locked.
4956 typedef hammer2_blockref_t *hammer2_blockref_p;
4958 static
4960 hammer2_base_sort_callback(const void *v1, const void *v2)
4962 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4963 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4966 * Make sure empty elements are placed at the end of the array
4968 if (bref1->type == 0) {
4969 if (bref2->type == 0)
4970 return(0);
4971 return(1);
4972 } else if (bref2->type == 0) {
4973 return(-1);
4977 * Sort by key
4979 if (bref1->key < bref2->key)
4980 return(-1);
4981 if (bref1->key > bref2->key)
4982 return(1);
4983 return(0);
4986 void
4987 hammer2_base_sort(hammer2_chain_t *chain)
4989 hammer2_blockref_t *base;
4990 int count;
4992 switch(chain->bref.type) {
4993 case HAMMER2_BREF_TYPE_INODE:
4995 * Special shortcut for embedded data returns the inode
4996 * itself. Callers must detect this condition and access
4997 * the embedded data (the strategy code does this for us).
4999 * This is only applicable to regular files and softlinks.
5001 if (chain->data->ipdata.meta.op_flags &
5002 HAMMER2_OPFLAG_DIRECTDATA) {
5003 return;
5005 base = &chain->data->ipdata.u.blockset.blockref[0];
5006 count = HAMMER2_SET_COUNT;
5007 break;
5008 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
5009 case HAMMER2_BREF_TYPE_INDIRECT:
5011 * Optimize indirect blocks in the INITIAL state to avoid
5012 * I/O.
5014 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
5015 base = &chain->data->npdata[0];
5016 count = chain->bytes / sizeof(hammer2_blockref_t);
5017 break;
5018 case HAMMER2_BREF_TYPE_VOLUME:
5019 base = &chain->data->voldata.sroot_blockset.blockref[0];
5020 count = HAMMER2_SET_COUNT;
5021 break;
5022 case HAMMER2_BREF_TYPE_FREEMAP:
5023 base = &chain->data->blkset.blockref[0];
5024 count = HAMMER2_SET_COUNT;
5025 break;
5026 default:
5027 kprintf("hammer2_chain_lookup: unrecognized "
5028 "blockref(A) type: %d",
5029 chain->bref.type);
5030 while (1)
5031 tsleep(&base, 0, "dead", 0);
5032 panic("hammer2_chain_lookup: unrecognized "
5033 "blockref(A) type: %d",
5034 chain->bref.type);
5035 base = NULL; /* safety */
5036 count = 0; /* safety */
5038 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
5041 #endif
5044 * Chain memory management
5046 void
5047 hammer2_chain_wait(hammer2_chain_t *chain)
5049 tsleep(chain, 0, "chnflw", 1);
5052 const hammer2_media_data_t *
5053 hammer2_chain_rdata(hammer2_chain_t *chain)
5055 KKASSERT(chain->data != NULL);
5056 return (chain->data);
5059 hammer2_media_data_t *
5060 hammer2_chain_wdata(hammer2_chain_t *chain)
5062 KKASSERT(chain->data != NULL);
5063 return (chain->data);
5067 * Set the check data for a chain. This can be a heavy-weight operation
5068 * and typically only runs on-flush. For file data check data is calculated
5069 * when the logical buffers are flushed.
5071 void
5072 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
5074 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
5076 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5077 case HAMMER2_CHECK_NONE:
5078 break;
5079 case HAMMER2_CHECK_DISABLED:
5080 break;
5081 case HAMMER2_CHECK_ISCSI32:
5082 chain->bref.check.iscsi32.value =
5083 hammer2_icrc32(bdata, chain->bytes);
5084 break;
5085 case HAMMER2_CHECK_XXHASH64:
5086 chain->bref.check.xxhash64.value =
5087 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5088 break;
5089 case HAMMER2_CHECK_SHA192:
5091 SHA256_CTX hash_ctx;
5092 union {
5093 uint8_t digest[SHA256_DIGEST_LENGTH];
5094 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5095 } u;
5097 SHA256_Init(&hash_ctx);
5098 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5099 SHA256_Final(u.digest, &hash_ctx);
5100 u.digest64[2] ^= u.digest64[3];
5101 bcopy(u.digest,
5102 chain->bref.check.sha192.data,
5103 sizeof(chain->bref.check.sha192.data));
5105 break;
5106 case HAMMER2_CHECK_FREEMAP:
5107 chain->bref.check.freemap.icrc32 =
5108 hammer2_icrc32(bdata, chain->bytes);
5109 break;
5110 default:
5111 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5112 chain->bref.methods);
5113 break;
5118 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
5120 uint32_t check32;
5121 uint64_t check64;
5122 int r;
5124 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
5125 return 1;
5127 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
5128 case HAMMER2_CHECK_NONE:
5129 r = 1;
5130 break;
5131 case HAMMER2_CHECK_DISABLED:
5132 r = 1;
5133 break;
5134 case HAMMER2_CHECK_ISCSI32:
5135 check32 = hammer2_icrc32(bdata, chain->bytes);
5136 r = (chain->bref.check.iscsi32.value == check32);
5137 if (r == 0) {
5138 kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
5139 "(flags=%08x, bref/data %08x/%08x)\n",
5140 chain->bref.data_off,
5141 chain->bref.type,
5142 chain->bref.methods,
5143 chain->flags,
5144 chain->bref.check.iscsi32.value,
5145 check32);
5147 hammer2_check_icrc32 += chain->bytes;
5148 break;
5149 case HAMMER2_CHECK_XXHASH64:
5150 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
5151 r = (chain->bref.check.xxhash64.value == check64);
5152 if (r == 0) {
5153 kprintf("chain %016jx.%02x key=%016jx "
5154 "meth=%02x CHECK FAIL "
5155 "(flags=%08x, bref/data %016jx/%016jx)\n",
5156 chain->bref.data_off,
5157 chain->bref.type,
5158 chain->bref.key,
5159 chain->bref.methods,
5160 chain->flags,
5161 chain->bref.check.xxhash64.value,
5162 check64);
5164 hammer2_check_xxhash64 += chain->bytes;
5165 break;
5166 case HAMMER2_CHECK_SHA192:
5168 SHA256_CTX hash_ctx;
5169 union {
5170 uint8_t digest[SHA256_DIGEST_LENGTH];
5171 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5172 } u;
5174 SHA256_Init(&hash_ctx);
5175 SHA256_Update(&hash_ctx, bdata, chain->bytes);
5176 SHA256_Final(u.digest, &hash_ctx);
5177 u.digest64[2] ^= u.digest64[3];
5178 if (bcmp(u.digest,
5179 chain->bref.check.sha192.data,
5180 sizeof(chain->bref.check.sha192.data)) == 0) {
5181 r = 1;
5182 } else {
5183 r = 0;
5184 kprintf("chain %016jx.%02x meth=%02x "
5185 "CHECK FAIL\n",
5186 chain->bref.data_off,
5187 chain->bref.type,
5188 chain->bref.methods);
5191 break;
5192 case HAMMER2_CHECK_FREEMAP:
5193 r = (chain->bref.check.freemap.icrc32 ==
5194 hammer2_icrc32(bdata, chain->bytes));
5195 if (r == 0) {
5196 kprintf("chain %016jx.%02x meth=%02x "
5197 "CHECK FAIL\n",
5198 chain->bref.data_off,
5199 chain->bref.type,
5200 chain->bref.methods);
5201 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5202 chain->bref.check.freemap.icrc32,
5203 hammer2_icrc32(bdata, chain->bytes),
5204 chain->bytes);
5205 if (chain->dio)
5206 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5207 chain->dio, chain->dio->bp->b_loffset,
5208 chain->dio->bp->b_bufsize, bdata,
5209 chain->dio->bp->b_data);
5212 break;
5213 default:
5214 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5215 chain->bref.methods);
5216 r = 1;
5217 break;
5219 return r;
5223 * Acquire the chain and parent representing the specified inode for the
5224 * device at the specified cluster index.
5226 * The flags passed in are LOOKUP flags, not RESOLVE flags.
5228 * If we are unable to locate the hardlink, INVAL is returned and *chainp
5229 * will be NULL. *parentp may still be set error or not, or NULL if the
5230 * parent itself could not be resolved.
5232 * Caller must pass-in a valid or NULL *parentp or *chainp. The passed-in
5233 * *parentp and *chainp will be unlocked if not NULL.
5236 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5237 int clindex, int flags,
5238 hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5240 hammer2_chain_t *parent;
5241 hammer2_chain_t *rchain;
5242 hammer2_key_t key_dummy;
5243 int cache_index = -1;
5244 int resolve_flags;
5246 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5247 HAMMER2_RESOLVE_SHARED : 0;
5250 * Caller expects us to replace these.
5252 if (*chainp) {
5253 hammer2_chain_unlock(*chainp);
5254 hammer2_chain_drop(*chainp);
5255 *chainp = NULL;
5257 if (*parentp) {
5258 hammer2_chain_unlock(*parentp);
5259 hammer2_chain_drop(*parentp);
5260 *parentp = NULL;
5264 * Inodes hang off of the iroot (bit 63 is clear, differentiating
5265 * inodes from root directory entries in the key lookup).
5267 parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5268 rchain = NULL;
5269 if (parent) {
5270 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5271 inum, inum,
5272 &cache_index, flags);
5274 *parentp = parent;
5275 *chainp = rchain;
5277 return (rchain ? 0 : EINVAL);
5281 * Used by the bulkscan code to snapshot the synchronized storage for
5282 * a volume, allowing it to be scanned concurrently against normal
5283 * operation.
5285 hammer2_chain_t *
5286 hammer2_chain_bulksnap(hammer2_dev_t *hmp)
5288 hammer2_chain_t *copy;
5290 copy = hammer2_chain_alloc(hmp, hmp->spmp, &hmp->vchain.bref);
5291 copy->data = kmalloc(sizeof(copy->data->voldata),
5292 hmp->mchain,
5293 M_WAITOK | M_ZERO);
5294 hammer2_voldata_lock(hmp);
5295 copy->data->voldata = hmp->volsync;
5296 hammer2_voldata_unlock(hmp);
5298 return copy;
5301 void
5302 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5304 KKASSERT(copy->bref.type == HAMMER2_BREF_TYPE_VOLUME);
5305 KKASSERT(copy->data);
5306 kfree(copy->data, copy->hmp->mchain);
5307 copy->data = NULL;
5308 atomic_add_long(&hammer2_chain_allocs, -1);
5309 hammer2_chain_drop(copy);
5313 * Create a snapshot of the specified (chain) with the specified label.
5314 * The originating hammer2_inode must be exclusively locked for
5315 * safety. The device's bulklk should be held by the caller. The caller
5316 * is responsible for synchronizing the filesystem to storage before
5317 * taking the snapshot.
5320 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5321 hammer2_tid_t mtid)
5323 hammer2_dev_t *hmp;
5324 const hammer2_inode_data_t *ripdata;
5325 hammer2_inode_data_t *wipdata;
5326 hammer2_chain_t *nchain;
5327 hammer2_inode_t *nip;
5328 size_t name_len;
5329 hammer2_key_t lhc;
5330 struct vattr vat;
5331 #if 0
5332 uuid_t opfs_clid;
5333 #endif
5334 int error;
5336 kprintf("snapshot %s\n", pmp->name);
5338 name_len = strlen(pmp->name);
5339 lhc = hammer2_dirhash(pmp->name, name_len);
5342 * Get the clid
5344 ripdata = &chain->data->ipdata;
5345 #if 0
5346 opfs_clid = ripdata->meta.pfs_clid;
5347 #endif
5348 hmp = chain->hmp;
5351 * Create the snapshot directory under the super-root
5353 * Set PFS type, generate a unique filesystem id, and generate
5354 * a cluster id. Use the same clid when snapshotting a PFS root,
5355 * which theoretically allows the snapshot to be used as part of
5356 * the same cluster (perhaps as a cache).
5358 * Copy the (flushed) blockref array. Theoretically we could use
5359 * chain_duplicate() but it becomes difficult to disentangle
5360 * the shared core so for now just brute-force it.
5362 VATTR_NULL(&vat);
5363 vat.va_type = VDIR;
5364 vat.va_mode = 0755;
5365 hammer2_chain_unlock(chain);
5366 nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5367 &vat, proc0.p_ucred,
5368 pmp->name, name_len, 0,
5369 1, 0, 0,
5370 HAMMER2_INSERT_PFSROOT, &error);
5371 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
5373 if (nip) {
5374 hammer2_inode_modify(nip);
5375 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5376 hammer2_chain_modify(nchain, mtid, 0, 0);
5377 wipdata = &nchain->data->ipdata;
5379 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5380 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5381 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5382 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5385 * Give the snapshot its own private cluster id. As a
5386 * snapshot no further synchronization with the original
5387 * cluster will be done.
5389 #if 0
5390 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5391 nip->meta.pfs_clid = opfs_clid;
5392 else
5393 kern_uuidgen(&nip->meta.pfs_clid, 1);
5394 #endif
5395 kern_uuidgen(&nip->meta.pfs_clid, 1);
5396 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5398 /* XXX hack blockset copy */
5399 /* XXX doesn't work with real cluster */
5400 wipdata->meta = nip->meta;
5401 wipdata->u.blockset = ripdata->u.blockset;
5403 hammer2_flush(nchain, 1);
5404 KKASSERT(wipdata == &nchain->data->ipdata);
5405 hammer2_pfsalloc(nchain, wipdata, nchain->bref.modify_tid, 0);
5407 hammer2_chain_unlock(nchain);
5408 hammer2_chain_drop(nchain);
5409 hammer2_inode_chain_sync(nip);
5410 hammer2_inode_unlock(nip);
5411 hammer2_inode_run_sideq(hmp->spmp);
5413 return (error);
5417 * Returns non-zero if the chain (INODE or DIRENT) matches the
5418 * filename.
5421 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5422 size_t name_len)
5424 const hammer2_inode_data_t *ripdata;
5425 const hammer2_dirent_head_t *den;
5427 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5428 ripdata = &chain->data->ipdata;
5429 if (ripdata->meta.name_len == name_len &&
5430 bcmp(ripdata->filename, name, name_len) == 0) {
5431 return 1;
5434 if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5435 chain->bref.embed.dirent.namlen == name_len) {
5436 den = &chain->bref.embed.dirent;
5437 if (name_len > sizeof(chain->bref.check.buf) &&
5438 bcmp(chain->data->buf, name, name_len) == 0) {
5439 return 1;
5441 if (name_len <= sizeof(chain->bref.check.buf) &&
5442 bcmp(chain->bref.check.buf, name, name_len) == 0) {
5443 return 1;
5446 return 0;