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
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This subsystem implements most of the core support functions for
37 * the hammer2_chain structure.
39 * Chains are the in-memory version on media objects (volume header, inodes,
40 * indirect blocks, data blocks, etc). Chains represent a portion of the
43 * Chains are no-longer delete-duplicated. Instead, the original in-memory
44 * chain will be moved along with its block reference (e.g. for things like
45 * renames, hardlink operations, modifications, etc), and will be indexed
46 * on a secondary list for flush handling instead of propagating a flag
49 * Concurrent front-end operations can still run against backend flushes
50 * as long as they do not cross the current flush boundary. An operation
51 * running above the current flush (in areas not yet flushed) can become
52 * part of the current flush while ano peration running below the current
53 * flush can become part of the next flush.
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
60 #include <sys/kern_syscall.h>
63 #include <crypto/sha2/sha2.h>
67 static int hammer2_indirect_optimize; /* XXX SYSCTL */
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70 hammer2_chain_t *parent,
71 hammer2_key_t key, int keybits,
72 hammer2_tid_t mtid, int for_type, int *errorp);
73 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
74 static hammer2_chain_t *hammer2_combined_find(
75 hammer2_chain_t *parent,
76 hammer2_blockref_t *base, int count,
77 int *cache_indexp, hammer2_key_t *key_nextp,
78 hammer2_key_t key_beg, hammer2_key_t key_end,
79 hammer2_blockref_t **bresp);
82 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
83 * overlap in the RB trees. Deleted chains are moved from rbtree to either
86 * Chains in delete-duplicate sequences can always iterate through core_entry
87 * to locate the live version of the chain.
89 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
91 extern int h2timer[32];
95 #define TIMER(which) do { \
97 h2timer[h2lid] += (int)(ticks - h2last);\
103 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
105 hammer2_key_t c1_beg;
106 hammer2_key_t c1_end;
107 hammer2_key_t c2_beg;
108 hammer2_key_t c2_end;
111 * Compare chains. Overlaps are not supposed to happen and catch
112 * any software issues early we count overlaps as a match.
114 c1_beg = chain1->bref.key;
115 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
116 c2_beg = chain2->bref.key;
117 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
119 if (c1_end < c2_beg) /* fully to the left */
121 if (c1_beg > c2_end) /* fully to the right */
123 return(0); /* overlap (must not cross edge boundary) */
128 hammer2_isclusterable(hammer2_chain_t *chain)
130 if (hammer2_cluster_enable) {
131 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
132 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
133 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
141 * Make a chain visible to the flusher. The flusher needs to be able to
142 * do flushes of subdirectory chains or single files so it does a top-down
143 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
144 * or UPDATE chains and flushes back up the chain to the volume root.
146 * This routine sets ONFLUSH upward until it hits the volume root. For
147 * simplicity we ignore PFSROOT boundaries whos rules can be complex.
148 * Extra ONFLUSH flagging doesn't hurt the filesystem.
151 hammer2_chain_setflush(hammer2_chain_t *chain)
153 hammer2_chain_t *parent;
155 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
156 hammer2_spin_sh(&chain->core.spin);
157 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
158 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
159 if ((parent = chain->parent) == NULL)
161 hammer2_spin_sh(&parent->core.spin);
162 hammer2_spin_unsh(&chain->core.spin);
165 hammer2_spin_unsh(&chain->core.spin);
170 * Allocate a new disconnected chain element representing the specified
171 * bref. chain->refs is set to 1 and the passed bref is copied to
172 * chain->bref. chain->bytes is derived from the bref.
174 * chain->pmp inherits pmp unless the chain is an inode (other than the
177 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
180 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
181 hammer2_blockref_t *bref)
183 hammer2_chain_t *chain;
184 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
186 atomic_add_long(&hammer2_chain_allocs, 1);
189 * Construct the appropriate system structure.
192 case HAMMER2_BREF_TYPE_INODE:
193 case HAMMER2_BREF_TYPE_INDIRECT:
194 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
195 case HAMMER2_BREF_TYPE_DATA:
196 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
198 * Chain's are really only associated with the hmp but we
199 * maintain a pmp association for per-mount memory tracking
200 * purposes. The pmp can be NULL.
202 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
204 case HAMMER2_BREF_TYPE_VOLUME:
205 case HAMMER2_BREF_TYPE_FREEMAP:
207 * Only hammer2_chain_bulksnap() calls this function with these
210 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
214 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
219 * Initialize the new chain structure. pmp must be set to NULL for
220 * chains belonging to the super-root topology of a device mount.
222 if (pmp == hmp->spmp)
228 chain->bytes = bytes;
230 chain->flags = HAMMER2_CHAIN_ALLOCATED;
233 * Set the PFS boundary flag if this chain represents a PFS root.
235 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
236 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
237 hammer2_chain_core_init(chain);
243 * Initialize a chain's core structure. This structure used to be allocated
244 * but is now embedded.
246 * The core is not locked. No additional refs on the chain are made.
247 * (trans) must not be NULL if (core) is not NULL.
250 hammer2_chain_core_init(hammer2_chain_t *chain)
253 * Fresh core under nchain (no multi-homing of ochain's
256 RB_INIT(&chain->core.rbtree); /* live chains */
257 hammer2_mtx_init(&chain->lock, "h2chain");
261 * Add a reference to a chain element, preventing its destruction.
263 * (can be called with spinlock held)
266 hammer2_chain_ref(hammer2_chain_t *chain)
268 atomic_add_int(&chain->refs, 1);
270 kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
276 * Insert the chain in the core rbtree.
278 * Normal insertions are placed in the live rbtree. Insertion of a deleted
279 * chain is a special case used by the flush code that is placed on the
280 * unstaged deleted list to avoid confusing the live view.
282 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
283 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
284 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
288 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
289 int flags, int generation)
291 hammer2_chain_t *xchain;
294 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
295 hammer2_spin_ex(&parent->core.spin);
298 * Interlocked by spinlock, check for race
300 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
301 parent->core.generation != generation) {
309 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
310 KASSERT(xchain == NULL,
311 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
312 chain, xchain, chain->bref.key));
313 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
314 chain->parent = parent;
315 ++parent->core.chain_count;
316 ++parent->core.generation; /* XXX incs for _get() too, XXX */
319 * We have to keep track of the effective live-view blockref count
320 * so the create code knows when to push an indirect block.
322 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
323 atomic_add_int(&parent->core.live_count, 1);
325 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
326 hammer2_spin_unex(&parent->core.spin);
331 * Drop the caller's reference to the chain. When the ref count drops to
332 * zero this function will try to disassociate the chain from its parent and
333 * deallocate it, then recursely drop the parent using the implied ref
334 * from the chain's chain->parent.
336 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
339 hammer2_chain_drop(hammer2_chain_t *chain)
343 if (hammer2_debug & 0x200000)
346 kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
350 KKASSERT(chain->refs > 0);
358 chain = hammer2_chain_lastdrop(chain);
360 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
362 /* retry the same chain */
368 * Safe handling of the 1->0 transition on chain. Returns a chain for
369 * recursive drop or NULL, possibly returning the same chain if the atomic
372 * Whem two chains need to be recursively dropped we use the chain
373 * we would otherwise free to placehold the additional chain. It's a bit
374 * convoluted but we can't just recurse without potentially blowing out
377 * The chain cannot be freed if it has any children.
378 * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
379 * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
381 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
385 hammer2_chain_lastdrop(hammer2_chain_t *chain)
389 hammer2_chain_t *parent;
390 hammer2_chain_t *rdrop;
393 * Critical field access.
395 hammer2_spin_ex(&chain->core.spin);
399 * If the chain has a parent the UPDATE bit prevents scrapping
400 * as the chain is needed to properly flush the parent. Try
401 * to complete the 1->0 transition and return NULL. Retry
402 * (return chain) if we are unable to complete the 1->0
403 * transition, else return NULL (nothing more to do).
405 * If the chain has a parent the MODIFIED bit prevents
408 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
409 HAMMER2_CHAIN_MODIFIED)) {
410 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
411 hammer2_spin_unex(&chain->core.spin);
414 hammer2_spin_unex(&chain->core.spin);
418 /* spinlock still held */
421 * The chain has no parent and can be flagged for destruction.
422 * Since it has no parent, UPDATE can also be cleared.
424 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
425 if (chain->flags & HAMMER2_CHAIN_UPDATE)
426 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
429 * If the chain has children or if it has been MODIFIED and
430 * also recorded for DEDUP, we must still flush the chain.
432 * In the case where it has children, the DESTROY flag test
433 * in the flush code will prevent unnecessary flushes of
434 * MODIFIED chains that are not flagged DEDUP so don't worry
437 if (chain->core.chain_count ||
438 (chain->flags & (HAMMER2_CHAIN_MODIFIED |
439 HAMMER2_CHAIN_DEDUP)) ==
440 (HAMMER2_CHAIN_MODIFIED |
441 HAMMER2_CHAIN_DEDUP)) {
443 * Put on flushq (should ensure refs > 1), retry
446 hammer2_spin_unex(&chain->core.spin);
447 hammer2_delayed_flush(chain);
448 return(chain); /* retry drop */
452 * Otherwise we can scrap the MODIFIED bit if it is set,
453 * and continue along the freeing path.
455 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
456 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
457 atomic_add_long(&hammer2_count_modified_chains, -1);
459 /* spinlock still held */
463 * If any children exist we must leave the chain intact with refs == 0.
464 * They exist because chains are retained below us which have refs or
465 * may require flushing. This case can occur when parent != NULL.
467 * Retry (return chain) if we fail to transition the refs to 0, else
468 * return NULL indication nothing more to do.
470 if (chain->core.chain_count) {
471 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
472 hammer2_spin_unex(&chain->core.spin);
475 hammer2_spin_unex(&chain->core.spin);
479 /* spinlock still held */
480 /* no chains left under us */
483 * chain->core has no children left so no accessors can get to our
484 * chain from there. Now we have to lock the parent core to interlock
485 * remaining possible accessors that might bump chain's refs before
486 * we can safely drop chain's refs with intent to free the chain.
489 pmp = chain->pmp; /* can be NULL */
493 * Spinlock the parent and try to drop the last ref on chain.
494 * On success remove chain from its parent, otherwise return NULL.
496 * (normal core locks are top-down recursive but we define core
497 * spinlocks as bottom-up recursive, so this is safe).
499 if ((parent = chain->parent) != NULL) {
500 hammer2_spin_ex(&parent->core.spin);
501 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
502 /* 1->0 transition failed, retry */
503 hammer2_spin_unex(&parent->core.spin);
504 hammer2_spin_unex(&chain->core.spin);
509 * 1->0 transition successful, remove chain from the
512 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
513 RB_REMOVE(hammer2_chain_tree,
514 &parent->core.rbtree, chain);
515 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
516 --parent->core.chain_count;
517 chain->parent = NULL;
521 * If our chain was the last chain in the parent's core the
522 * core is now empty and its parent might have to be
523 * re-dropped if it has 0 refs.
525 if (parent->core.chain_count == 0) {
527 atomic_add_int(&rdrop->refs, 1);
529 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
533 hammer2_spin_unex(&parent->core.spin);
534 parent = NULL; /* safety */
538 * Successful 1->0 transition and the chain can be destroyed now.
540 * We still have the core spinlock, and core's chain_count is 0.
541 * Any parent spinlock is gone.
543 hammer2_spin_unex(&chain->core.spin);
544 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
545 chain->core.chain_count == 0);
548 * All spin locks are gone, no pointers remain to the chain, finish
551 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
552 HAMMER2_CHAIN_MODIFIED)) == 0);
553 hammer2_chain_drop_data(chain, 1);
555 KKASSERT(chain->dio == NULL);
558 * Once chain resources are gone we can use the now dead chain
559 * structure to placehold what might otherwise require a recursive
560 * drop, because we have potentially two things to drop and can only
561 * return one directly.
563 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
564 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
566 kfree(chain, hmp->mchain);
570 * Possible chaining loop when parent re-drop needed.
576 * On either last lock release or last drop
579 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
581 /*hammer2_dev_t *hmp = chain->hmp;*/
583 switch(chain->bref.type) {
584 case HAMMER2_BREF_TYPE_VOLUME:
585 case HAMMER2_BREF_TYPE_FREEMAP:
590 KKASSERT(chain->data == NULL);
596 * Lock a referenced chain element, acquiring its data with I/O if necessary,
597 * and specify how you would like the data to be resolved.
599 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
601 * The lock is allowed to recurse, multiple locking ops will aggregate
602 * the requested resolve types. Once data is assigned it will not be
603 * removed until the last unlock.
605 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
606 * (typically used to avoid device/logical buffer
609 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
610 * the INITIAL-create state (indirect blocks only).
612 * Do not resolve data elements for DATA chains.
613 * (typically used to avoid device/logical buffer
616 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
618 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
619 * it will be locked exclusive.
621 * NOTE: Embedded elements (volume header, inodes) are always resolved
624 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
625 * element will instantiate and zero its buffer, and flush it on
628 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
629 * so as not to instantiate a device buffer, which could alias against
630 * a logical file buffer. However, if ALWAYS is specified the
631 * device buffer will be instantiated anyway.
633 * WARNING! This function blocks on I/O if data needs to be fetched. This
634 * blocking can run concurrent with other compatible lock holders
635 * who do not need data returning. The lock is not upgraded to
636 * exclusive during a data fetch, a separate bit is used to
637 * interlock I/O. However, an exclusive lock holder can still count
638 * on being interlocked against an I/O fetch managed by a shared
642 hammer2_chain_lock(hammer2_chain_t *chain, int how)
645 * Ref and lock the element. Recursive locks are allowed.
647 KKASSERT(chain->refs > 0);
648 atomic_add_int(&chain->lockcnt, 1);
652 * Get the appropriate lock.
654 if (how & HAMMER2_RESOLVE_SHARED)
655 hammer2_mtx_sh(&chain->lock);
657 hammer2_mtx_ex(&chain->lock);
658 ++curthread->td_tracker;
662 * If we already have a valid data pointer no further action is
670 * Do we have to resolve the data?
672 switch(how & HAMMER2_RESOLVE_MASK) {
673 case HAMMER2_RESOLVE_NEVER:
675 case HAMMER2_RESOLVE_MAYBE:
676 if (chain->flags & HAMMER2_CHAIN_INITIAL)
678 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
681 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
683 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
687 case HAMMER2_RESOLVE_ALWAYS:
693 * Caller requires data
695 hammer2_chain_load_data(chain);
699 * Downgrade an exclusive chain lock to a shared chain lock.
701 * NOTE: There is no upgrade equivalent due to the ease of
702 * deadlocks in that direction.
705 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
707 hammer2_mtx_downgrade(&chain->lock);
711 * Obtains a second shared lock on the chain, does not account the second
712 * shared lock as being owned by the current thread.
714 * Caller must already own a shared lock on this chain.
716 * The lock function is required to obtain the second shared lock without
717 * blocking on pending exclusive requests.
720 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
722 hammer2_mtx_sh_again(&chain->lock);
723 atomic_add_int(&chain->lockcnt, 1);
724 /* do not count in td_tracker for this thread */
728 * Accounts for a shared lock that was pushed to us as being owned by our
732 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
734 ++curthread->td_tracker;
738 * Issue I/O and install chain->data. Caller must hold a chain lock, lock
739 * may be of any type.
741 * Once chain->data is set it cannot be disposed of until all locks are
745 hammer2_chain_load_data(hammer2_chain_t *chain)
747 hammer2_blockref_t *bref;
753 * Degenerate case, data already present.
760 KKASSERT(hmp != NULL);
763 * Gain the IOINPROG bit, interlocked block.
769 oflags = chain->flags;
771 if (oflags & HAMMER2_CHAIN_IOINPROG) {
772 nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
773 tsleep_interlock(&chain->flags, 0);
774 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
775 tsleep(&chain->flags, PINTERLOCKED,
780 nflags = oflags | HAMMER2_CHAIN_IOINPROG;
781 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
790 * We own CHAIN_IOINPROG
792 * Degenerate case if we raced another load.
798 * We must resolve to a device buffer, either by issuing I/O or
799 * by creating a zero-fill element. We do not mark the buffer
800 * dirty when creating a zero-fill element (the hammer2_chain_modify()
801 * API must still be used to do that).
803 * The device buffer is variable-sized in powers of 2 down
804 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
805 * chunk always contains buffers of the same size. (XXX)
807 * The minimum physical IO size may be larger than the variable
813 * The getblk() optimization can only be used on newly created
814 * elements if the physical block size matches the request.
816 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
817 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
820 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
822 hammer2_adjreadcounter(&chain->bref, chain->bytes);
826 chain->error = HAMMER2_ERROR_IO;
827 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
828 (intmax_t)bref->data_off, error);
829 hammer2_io_bqrelse(&chain->dio);
835 * NOTE: A locked chain's data cannot be modified without first
836 * calling hammer2_chain_modify().
840 * Clear INITIAL. In this case we used io_new() and the buffer has
841 * been zero'd and marked dirty.
843 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
844 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
845 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
846 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
847 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
849 * check data not currently synchronized due to
850 * modification. XXX assumes data stays in the buffer
851 * cache, which might not be true (need biodep on flush
852 * to calculate crc? or simple crc?).
854 } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
858 if (hammer2_io_crc_good(chain, &mask)) {
859 chain->flags |= HAMMER2_CHAIN_TESTEDGOOD;
860 } else if (hammer2_chain_testcheck(chain, bdata) == 0) {
861 kprintf("chain %016jx.%02x meth=%02x "
862 "CHECK FAIL %08x (flags=%08x)\n",
863 chain->bref.data_off,
866 hammer2_icrc32(bdata, chain->bytes),
868 chain->error = HAMMER2_ERROR_CHECK;
870 hammer2_io_crc_setmask(chain->dio, mask);
872 kprintf("chain %02x %016jx %u\n",
873 chain->bref.type, chain->bref.key,
876 chain->flags |= HAMMER2_CHAIN_TESTEDGOOD;
882 * Setup the data pointer, either pointing it to an embedded data
883 * structure and copying the data from the buffer, or pointing it
886 * The buffer is not retained when copying to an embedded data
887 * structure in order to avoid potential deadlocks or recursions
888 * on the same physical buffer.
890 * WARNING! Other threads can start using the data the instant we
891 * set chain->data non-NULL.
893 switch (bref->type) {
894 case HAMMER2_BREF_TYPE_VOLUME:
895 case HAMMER2_BREF_TYPE_FREEMAP:
897 * Copy data from bp to embedded buffer
899 panic("hammer2_chain_lock: called on unresolved volume header");
901 case HAMMER2_BREF_TYPE_INODE:
902 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
903 case HAMMER2_BREF_TYPE_INDIRECT:
904 case HAMMER2_BREF_TYPE_DATA:
905 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
908 * Point data at the device buffer and leave dio intact.
910 chain->data = (void *)bdata;
915 * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
922 oflags = chain->flags;
923 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
924 HAMMER2_CHAIN_IOSIGNAL);
925 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
926 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
927 if (oflags & HAMMER2_CHAIN_IOSIGNAL)
928 wakeup(&chain->flags);
936 * Unlock and deref a chain element.
938 * On the last lock release any non-embedded data (chain->dio) will be
942 hammer2_chain_unlock(hammer2_chain_t *chain)
944 hammer2_mtx_state_t ostate;
948 --curthread->td_tracker;
950 * If multiple locks are present (or being attempted) on this
951 * particular chain we can just unlock, drop refs, and return.
953 * Otherwise fall-through on the 1->0 transition.
956 lockcnt = chain->lockcnt;
957 KKASSERT(lockcnt > 0);
960 if (atomic_cmpset_int(&chain->lockcnt,
961 lockcnt, lockcnt - 1)) {
962 hammer2_mtx_unlock(&chain->lock);
966 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
973 * On the 1->0 transition we upgrade the core lock (if necessary)
974 * to exclusive for terminal processing. If after upgrading we find
975 * that lockcnt is non-zero, another thread is racing us and will
976 * handle the unload for us later on, so just cleanup and return
977 * leaving the data/io intact
979 * Otherwise if lockcnt is still 0 it is possible for it to become
980 * non-zero and race, but since we hold the core->lock exclusively
981 * all that will happen is that the chain will be reloaded after we
984 ostate = hammer2_mtx_upgrade(&chain->lock);
985 if (chain->lockcnt) {
986 hammer2_mtx_unlock(&chain->lock);
991 * Shortcut the case if the data is embedded or not resolved.
992 * Only drop non-DIO-based data if the chain is not modified.
994 * Do NOT NULL out chain->data (e.g. inode data), it might be
997 if (chain->dio == NULL) {
998 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
999 hammer2_chain_drop_data(chain, 0);
1000 hammer2_mtx_unlock(&chain->lock);
1007 if (hammer2_io_isdirty(chain->dio)) {
1008 switch(chain->bref.type) {
1009 case HAMMER2_BREF_TYPE_DATA:
1010 counterp = &hammer2_iod_file_write;
1012 case HAMMER2_BREF_TYPE_INODE:
1013 counterp = &hammer2_iod_meta_write;
1015 case HAMMER2_BREF_TYPE_INDIRECT:
1016 counterp = &hammer2_iod_indr_write;
1018 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1019 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1020 counterp = &hammer2_iod_fmap_write;
1023 counterp = &hammer2_iod_volu_write;
1026 *counterp += chain->bytes;
1030 * Clean out the dio.
1032 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1036 hammer2_io_bqrelse(&chain->dio);
1037 hammer2_mtx_unlock(&chain->lock);
1041 * Helper to obtain the blockref[] array base and count for a chain.
1043 * XXX Not widely used yet, various use cases need to be validated and
1044 * converted to use this function.
1047 hammer2_blockref_t *
1048 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1050 hammer2_blockref_t *base;
1053 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1056 switch(parent->bref.type) {
1057 case HAMMER2_BREF_TYPE_INODE:
1058 count = HAMMER2_SET_COUNT;
1060 case HAMMER2_BREF_TYPE_INDIRECT:
1061 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1062 count = parent->bytes / sizeof(hammer2_blockref_t);
1064 case HAMMER2_BREF_TYPE_VOLUME:
1065 count = HAMMER2_SET_COUNT;
1067 case HAMMER2_BREF_TYPE_FREEMAP:
1068 count = HAMMER2_SET_COUNT;
1071 panic("hammer2_chain_create_indirect: "
1072 "unrecognized blockref type: %d",
1078 switch(parent->bref.type) {
1079 case HAMMER2_BREF_TYPE_INODE:
1080 base = &parent->data->ipdata.u.blockset.blockref[0];
1081 count = HAMMER2_SET_COUNT;
1083 case HAMMER2_BREF_TYPE_INDIRECT:
1084 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1085 base = &parent->data->npdata[0];
1086 count = parent->bytes / sizeof(hammer2_blockref_t);
1088 case HAMMER2_BREF_TYPE_VOLUME:
1089 base = &parent->data->voldata.
1090 sroot_blockset.blockref[0];
1091 count = HAMMER2_SET_COUNT;
1093 case HAMMER2_BREF_TYPE_FREEMAP:
1094 base = &parent->data->blkset.blockref[0];
1095 count = HAMMER2_SET_COUNT;
1098 panic("hammer2_chain_create_indirect: "
1099 "unrecognized blockref type: %d",
1111 * This counts the number of live blockrefs in a block array and
1112 * also calculates the point at which all remaining blockrefs are empty.
1113 * This routine can only be called on a live chain (DUPLICATED flag not set).
1115 * NOTE: Flag is not set until after the count is complete, allowing
1116 * callers to test the flag without holding the spinlock.
1118 * NOTE: If base is NULL the related chain is still in the INITIAL
1119 * state and there are no blockrefs to count.
1121 * NOTE: live_count may already have some counts accumulated due to
1122 * creation and deletion and could even be initially negative.
1125 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1126 hammer2_blockref_t *base, int count)
1128 hammer2_spin_ex(&chain->core.spin);
1129 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1131 while (--count >= 0) {
1132 if (base[count].type)
1135 chain->core.live_zero = count + 1;
1136 while (count >= 0) {
1137 if (base[count].type)
1138 atomic_add_int(&chain->core.live_count,
1143 chain->core.live_zero = 0;
1145 /* else do not modify live_count */
1146 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1148 hammer2_spin_unex(&chain->core.spin);
1152 * Resize the chain's physical storage allocation in-place. This function does
1153 * not adjust the data pointer and must be followed by (typically) a
1154 * hammer2_chain_modify() call to copy any old data over and adjust the
1157 * Chains can be resized smaller without reallocating the storage. Resizing
1158 * larger will reallocate the storage. Excess or prior storage is reclaimed
1159 * asynchronously at a later time.
1161 * Must be passed an exclusively locked parent and chain.
1163 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1164 * to avoid instantiating a device buffer that conflicts with the vnode data
1165 * buffer. However, because H2 can compress or encrypt data, the chain may
1166 * have a dio assigned to it in those situations, and they do not conflict.
1168 * XXX return error if cannot resize.
1171 hammer2_chain_resize(hammer2_inode_t *ip,
1172 hammer2_chain_t *parent, hammer2_chain_t *chain,
1173 hammer2_tid_t mtid, hammer2_off_t dedup_off,
1174 int nradix, int flags)
1183 * Only data and indirect blocks can be resized for now.
1184 * (The volu root, inodes, and freemap elements use a fixed size).
1186 KKASSERT(chain != &hmp->vchain);
1187 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1188 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1189 KKASSERT(chain->parent == parent);
1192 * Nothing to do if the element is already the proper size
1194 obytes = chain->bytes;
1195 nbytes = 1U << nradix;
1196 if (obytes == nbytes)
1200 * Make sure the old data is instantiated so we can copy it. If this
1201 * is a data block, the device data may be superfluous since the data
1202 * might be in a logical block, but compressed or encrypted data is
1205 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1207 hammer2_chain_modify(chain, mtid, dedup_off, 0);
1210 * Relocate the block, even if making it smaller (because different
1211 * block sizes may be in different regions).
1213 * (data blocks only, we aren't copying the storage here).
1215 hammer2_freemap_alloc(chain, nbytes);
1216 chain->bytes = nbytes;
1217 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1220 * We don't want the followup chain_modify() to try to copy data
1221 * from the old (wrong-sized) buffer. It won't know how much to
1222 * copy. This case should only occur during writes when the
1223 * originator already has the data to write in-hand.
1226 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1227 hammer2_io_brelse(&chain->dio);
1233 * Set the chain modified so its data can be changed by the caller.
1235 * Sets bref.modify_tid to mtid only if mtid != 0. Note that bref.modify_tid
1236 * is a CLC (cluster level change) field and is not updated by parent
1237 * propagation during a flush.
1239 * If the caller passes a non-zero dedup_off we assign data_off to that
1240 * instead of allocating a ne block. Caller must not modify the data already
1241 * present at the target offset.
1244 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1245 hammer2_off_t dedup_off, int flags)
1247 hammer2_blockref_t obref;
1256 obref = chain->bref;
1257 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1260 * Data is not optional for freemap chains (we must always be sure
1261 * to copy the data on COW storage allocations).
1263 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1264 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1265 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1266 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1270 * Data must be resolved if already assigned, unless explicitly
1271 * flagged otherwise.
1273 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1274 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1275 hammer2_chain_load_data(chain);
1279 * Set MODIFIED to indicate that the chain has been modified.
1280 * Set UPDATE to ensure that the blockref is updated in the parent.
1282 if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1283 (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1285 * Modified already set but a new allocation is needed
1286 * anyway because we recorded this data_off for possible
1290 } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1292 * Must set modified bit.
1294 atomic_add_long(&hammer2_count_modified_chains, 1);
1295 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1296 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1300 * Already flagged modified, no new allocation is needed.
1306 * Flag parent update required, clear DEDUP flag (already processed
1309 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1310 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1311 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1314 * The modification or re-modification requires an allocation and
1317 * If dedup_off is non-zero, caller already has a data offset
1318 * containing the caller's desired data. The dedup offset is
1319 * allowed to be in a partially free state and we must be sure
1320 * to reset it to a fully allocated state to force two bulkfree
1321 * passes to free it again.
1323 * XXX can a chain already be marked MODIFIED without a data
1324 * assignment? If not, assert here instead of testing the case.
1326 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1327 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1331 chain->bref.data_off = dedup_off;
1332 chain->bytes = 1 << (dedup_off &
1333 HAMMER2_OFF_MASK_RADIX);
1334 atomic_set_int(&chain->flags,
1335 HAMMER2_CHAIN_DEDUP);
1336 hammer2_freemap_adjust(hmp, &chain->bref,
1337 HAMMER2_FREEMAP_DORECOVER);
1339 hammer2_freemap_alloc(chain, chain->bytes);
1341 /* XXX failed allocation */
1346 * Update mirror_tid and modify_tid. modify_tid is only updated
1347 * if not passed as zero (during flushes, parent propagation passes
1350 * NOTE: chain->pmp could be the device spmp.
1352 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1354 chain->bref.modify_tid = mtid;
1357 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1358 * requires updating as well as to tell the delete code that the
1359 * chain's blockref might not exactly match (in terms of physical size
1360 * or block offset) the one in the parent's blocktable. The base key
1361 * of course will still match.
1363 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1364 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1367 * Short-cut data blocks which the caller does not need an actual
1368 * data reference to (aka OPTDATA), as long as the chain does not
1369 * already have a data pointer to the data. This generally means
1370 * that the modifications are being done via the logical buffer cache.
1371 * The INITIAL flag relates only to the device data buffer and thus
1372 * remains unchange in this situation.
1374 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1375 (flags & HAMMER2_MODIFY_OPTDATA) &&
1376 chain->data == NULL) {
1381 * Clearing the INITIAL flag (for indirect blocks) indicates that
1382 * we've processed the uninitialized storage allocation.
1384 * If this flag is already clear we are likely in a copy-on-write
1385 * situation but we have to be sure NOT to bzero the storage if
1386 * no data is present.
1388 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1389 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1396 * Instantiate data buffer and possibly execute COW operation
1398 switch(chain->bref.type) {
1399 case HAMMER2_BREF_TYPE_VOLUME:
1400 case HAMMER2_BREF_TYPE_FREEMAP:
1402 * The data is embedded, no copy-on-write operation is
1405 KKASSERT(chain->dio == NULL);
1407 case HAMMER2_BREF_TYPE_INODE:
1408 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1409 case HAMMER2_BREF_TYPE_DATA:
1410 case HAMMER2_BREF_TYPE_INDIRECT:
1411 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1413 * Perform the copy-on-write operation
1415 * zero-fill or copy-on-write depending on whether
1416 * chain->data exists or not and set the dirty state for
1417 * the new buffer. hammer2_io_new() will handle the
1420 * If a dedup_off was supplied this is an existing block
1421 * and no COW, copy, or further modification is required.
1423 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1425 if (wasinitial && dedup_off == 0) {
1426 error = hammer2_io_new(hmp, chain->bref.data_off,
1427 chain->bytes, &dio);
1429 error = hammer2_io_bread(hmp, chain->bref.data_off,
1430 chain->bytes, &dio);
1432 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1435 * If an I/O error occurs make sure callers cannot accidently
1436 * modify the old buffer's contents and corrupt the filesystem.
1439 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1441 chain->error = HAMMER2_ERROR_IO;
1442 hammer2_io_brelse(&dio);
1443 hammer2_io_brelse(&chain->dio);
1448 bdata = hammer2_io_data(dio, chain->bref.data_off);
1452 * COW (unless a dedup).
1454 KKASSERT(chain->dio != NULL);
1455 if (chain->data != (void *)bdata && dedup_off == 0) {
1456 bcopy(chain->data, bdata, chain->bytes);
1458 } else if (wasinitial == 0) {
1460 * We have a problem. We were asked to COW but
1461 * we don't have any data to COW with!
1463 panic("hammer2_chain_modify: having a COW %p\n",
1468 * Retire the old buffer, replace with the new. Dirty or
1469 * redirty the new buffer.
1471 * WARNING! The system buffer cache may have already flushed
1472 * the buffer, so we must be sure to [re]dirty it
1473 * for further modification.
1475 * If dedup_off was supplied, the caller is not
1476 * expected to make any further modification to the
1480 hammer2_io_bqrelse(&chain->dio);
1481 chain->data = (void *)bdata;
1484 hammer2_io_setdirty(dio);
1487 panic("hammer2_chain_modify: illegal non-embedded type %d",
1494 * setflush on parent indicating that the parent must recurse down
1495 * to us. Do not call on chain itself which might already have it
1499 hammer2_chain_setflush(chain->parent);
1503 * Modify the chain associated with an inode.
1506 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1507 hammer2_tid_t mtid, int flags)
1509 hammer2_inode_modify(ip);
1510 hammer2_chain_modify(chain, mtid, 0, flags);
1514 * Volume header data locks
1517 hammer2_voldata_lock(hammer2_dev_t *hmp)
1519 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1523 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1525 lockmgr(&hmp->vollk, LK_RELEASE);
1529 hammer2_voldata_modify(hammer2_dev_t *hmp)
1531 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1532 atomic_add_long(&hammer2_count_modified_chains, 1);
1533 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1534 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1539 * This function returns the chain at the nearest key within the specified
1540 * range. The returned chain will be referenced but not locked.
1542 * This function will recurse through chain->rbtree as necessary and will
1543 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1544 * the iteration value is less than the current value of *key_nextp.
1546 * The caller should use (*key_nextp) to calculate the actual range of
1547 * the returned element, which will be (key_beg to *key_nextp - 1), because
1548 * there might be another element which is superior to the returned element
1551 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1552 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1553 * it will wind up being (key_end + 1).
1555 * WARNING! Must be called with child's spinlock held. Spinlock remains
1556 * held through the operation.
1558 struct hammer2_chain_find_info {
1559 hammer2_chain_t *best;
1560 hammer2_key_t key_beg;
1561 hammer2_key_t key_end;
1562 hammer2_key_t key_next;
1565 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1566 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1570 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1571 hammer2_key_t key_beg, hammer2_key_t key_end)
1573 struct hammer2_chain_find_info info;
1576 info.key_beg = key_beg;
1577 info.key_end = key_end;
1578 info.key_next = *key_nextp;
1580 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1581 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1583 *key_nextp = info.key_next;
1585 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1586 parent, key_beg, key_end, *key_nextp);
1594 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1596 struct hammer2_chain_find_info *info = data;
1597 hammer2_key_t child_beg;
1598 hammer2_key_t child_end;
1600 child_beg = child->bref.key;
1601 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1603 if (child_end < info->key_beg)
1605 if (child_beg > info->key_end)
1612 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1614 struct hammer2_chain_find_info *info = data;
1615 hammer2_chain_t *best;
1616 hammer2_key_t child_end;
1619 * WARNING! Do not discard DUPLICATED chains, it is possible that
1620 * we are catching an insertion half-way done. If a
1621 * duplicated chain turns out to be the best choice the
1622 * caller will re-check its flags after locking it.
1624 * WARNING! Layerq is scanned forwards, exact matches should keep
1625 * the existing info->best.
1627 if ((best = info->best) == NULL) {
1629 * No previous best. Assign best
1632 } else if (best->bref.key <= info->key_beg &&
1633 child->bref.key <= info->key_beg) {
1638 /*info->best = child;*/
1639 } else if (child->bref.key < best->bref.key) {
1641 * Child has a nearer key and best is not flush with key_beg.
1642 * Set best to child. Truncate key_next to the old best key.
1645 if (info->key_next > best->bref.key || info->key_next == 0)
1646 info->key_next = best->bref.key;
1647 } else if (child->bref.key == best->bref.key) {
1649 * If our current best is flush with the child then this
1650 * is an illegal overlap.
1652 * key_next will automatically be limited to the smaller of
1653 * the two end-points.
1659 * Keep the current best but truncate key_next to the child's
1662 * key_next will also automatically be limited to the smaller
1663 * of the two end-points (probably not necessary for this case
1664 * but we do it anyway).
1666 if (info->key_next > child->bref.key || info->key_next == 0)
1667 info->key_next = child->bref.key;
1671 * Always truncate key_next based on child's end-of-range.
1673 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1674 if (child_end && (info->key_next > child_end || info->key_next == 0))
1675 info->key_next = child_end;
1681 * Retrieve the specified chain from a media blockref, creating the
1682 * in-memory chain structure which reflects it.
1684 * To handle insertion races pass the INSERT_RACE flag along with the
1685 * generation number of the core. NULL will be returned if the generation
1686 * number changes before we have a chance to insert the chain. Insert
1687 * races can occur because the parent might be held shared.
1689 * Caller must hold the parent locked shared or exclusive since we may
1690 * need the parent's bref array to find our block.
1692 * WARNING! chain->pmp is always set to NULL for any chain representing
1693 * part of the super-root topology.
1696 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1697 hammer2_blockref_t *bref)
1699 hammer2_dev_t *hmp = parent->hmp;
1700 hammer2_chain_t *chain;
1704 * Allocate a chain structure representing the existing media
1705 * entry. Resulting chain has one ref and is not locked.
1707 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1708 chain = hammer2_chain_alloc(hmp, NULL, bref);
1710 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1711 /* ref'd chain returned */
1714 * Flag that the chain is in the parent's blockmap so delete/flush
1715 * knows what to do with it.
1717 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1720 * Link the chain into its parent. A spinlock is required to safely
1721 * access the RBTREE, and it is possible to collide with another
1722 * hammer2_chain_get() operation because the caller might only hold
1723 * a shared lock on the parent.
1725 KKASSERT(parent->refs > 0);
1726 error = hammer2_chain_insert(parent, chain,
1727 HAMMER2_CHAIN_INSERT_SPIN |
1728 HAMMER2_CHAIN_INSERT_RACE,
1731 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1732 kprintf("chain %p get race\n", chain);
1733 hammer2_chain_drop(chain);
1736 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1740 * Return our new chain referenced but not locked, or NULL if
1747 * Lookup initialization/completion API
1750 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1752 hammer2_chain_ref(parent);
1753 if (flags & HAMMER2_LOOKUP_SHARED) {
1754 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1755 HAMMER2_RESOLVE_SHARED);
1757 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1763 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1766 hammer2_chain_unlock(parent);
1767 hammer2_chain_drop(parent);
1772 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1774 hammer2_chain_t *oparent;
1775 hammer2_chain_t *nparent;
1778 * Be careful of order, oparent must be unlocked before nparent
1779 * is locked below to avoid a deadlock.
1782 hammer2_spin_ex(&oparent->core.spin);
1783 nparent = oparent->parent;
1784 hammer2_chain_ref(nparent);
1785 hammer2_spin_unex(&oparent->core.spin);
1787 hammer2_chain_unlock(oparent);
1788 hammer2_chain_drop(oparent);
1792 hammer2_chain_lock(nparent, how);
1799 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1800 * (*parentp) typically points to an inode but can also point to a related
1801 * indirect block and this function will recurse upwards and find the inode
1804 * (*parentp) must be exclusively locked and referenced and can be an inode
1805 * or an existing indirect block within the inode.
1807 * On return (*parentp) will be modified to point at the deepest parent chain
1808 * element encountered during the search, as a helper for an insertion or
1809 * deletion. The new (*parentp) will be locked and referenced and the old
1810 * will be unlocked and dereferenced (no change if they are both the same).
1812 * The matching chain will be returned exclusively locked. If NOLOCK is
1813 * requested the chain will be returned only referenced. Note that the
1814 * parent chain must always be locked shared or exclusive, matching the
1815 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1816 * when NOLOCK is specified but that complicates matters if *parentp must
1817 * inherit the chain.
1819 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1820 * data pointer or can otherwise be in flux.
1822 * NULL is returned if no match was found, but (*parentp) will still
1823 * potentially be adjusted.
1825 * If a fatal error occurs (typically an I/O error), a dummy chain is
1826 * returned with chain->error and error-identifying information set. This
1827 * chain will assert if you try to do anything fancy with it.
1829 * XXX Depending on where the error occurs we should allow continued iteration.
1831 * On return (*key_nextp) will point to an iterative value for key_beg.
1832 * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1834 * This function will also recurse up the chain if the key is not within the
1835 * current parent's range. (*parentp) can never be set to NULL. An iteration
1836 * can simply allow (*parentp) to float inside the loop.
1838 * NOTE! chain->data is not always resolved. By default it will not be
1839 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1840 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1841 * BREF_TYPE_DATA as the device buffer can alias the logical file
1846 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1847 hammer2_key_t key_beg, hammer2_key_t key_end,
1848 int *cache_indexp, int flags)
1851 hammer2_chain_t *parent;
1852 hammer2_chain_t *chain;
1853 hammer2_blockref_t *base;
1854 hammer2_blockref_t *bref;
1855 hammer2_blockref_t bcopy;
1856 hammer2_key_t scan_beg;
1857 hammer2_key_t scan_end;
1859 int how_always = HAMMER2_RESOLVE_ALWAYS;
1860 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1863 int maxloops = 300000;
1867 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1868 how_maybe = how_always;
1869 how = HAMMER2_RESOLVE_ALWAYS;
1870 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1871 how = HAMMER2_RESOLVE_NEVER;
1873 how = HAMMER2_RESOLVE_MAYBE;
1875 if (flags & HAMMER2_LOOKUP_SHARED) {
1876 how_maybe |= HAMMER2_RESOLVE_SHARED;
1877 how_always |= HAMMER2_RESOLVE_SHARED;
1878 how |= HAMMER2_RESOLVE_SHARED;
1882 * Recurse (*parentp) upward if necessary until the parent completely
1883 * encloses the key range or we hit the inode.
1885 * This function handles races against the flusher doing a delete-
1886 * duplicate above us and re-homes the parent to the duplicate in
1887 * that case, otherwise we'd wind up recursing down a stale chain.
1892 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1893 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1894 scan_beg = parent->bref.key;
1895 scan_end = scan_beg +
1896 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1897 if (key_beg >= scan_beg && key_end <= scan_end)
1899 parent = hammer2_chain_getparent(parentp, how_maybe);
1904 if (--maxloops == 0)
1905 panic("hammer2_chain_lookup: maxloops");
1907 * Locate the blockref array. Currently we do a fully associative
1908 * search through the array.
1910 switch(parent->bref.type) {
1911 case HAMMER2_BREF_TYPE_INODE:
1913 * Special shortcut for embedded data returns the inode
1914 * itself. Callers must detect this condition and access
1915 * the embedded data (the strategy code does this for us).
1917 * This is only applicable to regular files and softlinks.
1919 if (parent->data->ipdata.meta.op_flags &
1920 HAMMER2_OPFLAG_DIRECTDATA) {
1921 if (flags & HAMMER2_LOOKUP_NODIRECT) {
1923 *key_nextp = key_end + 1;
1926 hammer2_chain_ref(parent);
1927 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1928 hammer2_chain_lock(parent, how_always);
1929 *key_nextp = key_end + 1;
1932 base = &parent->data->ipdata.u.blockset.blockref[0];
1933 count = HAMMER2_SET_COUNT;
1935 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1936 case HAMMER2_BREF_TYPE_INDIRECT:
1938 * Handle MATCHIND on the parent
1940 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1941 scan_beg = parent->bref.key;
1942 scan_end = scan_beg +
1943 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1944 if (key_beg == scan_beg && key_end == scan_end) {
1946 hammer2_chain_ref(chain);
1947 hammer2_chain_lock(chain, how_maybe);
1948 *key_nextp = scan_end + 1;
1953 * Optimize indirect blocks in the INITIAL state to avoid
1956 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1959 if (parent->data == NULL)
1960 panic("parent->data is NULL");
1961 base = &parent->data->npdata[0];
1963 count = parent->bytes / sizeof(hammer2_blockref_t);
1965 case HAMMER2_BREF_TYPE_VOLUME:
1966 base = &parent->data->voldata.sroot_blockset.blockref[0];
1967 count = HAMMER2_SET_COUNT;
1969 case HAMMER2_BREF_TYPE_FREEMAP:
1970 base = &parent->data->blkset.blockref[0];
1971 count = HAMMER2_SET_COUNT;
1974 kprintf("hammer2_chain_lookup: unrecognized "
1975 "blockref(B) type: %d",
1978 tsleep(&base, 0, "dead", 0);
1979 panic("hammer2_chain_lookup: unrecognized "
1980 "blockref(B) type: %d",
1982 base = NULL; /* safety */
1983 count = 0; /* safety */
1988 * Merged scan to find next candidate.
1990 * hammer2_base_*() functions require the parent->core.live_* fields
1991 * to be synchronized.
1993 * We need to hold the spinlock to access the block array and RB tree
1994 * and to interlock chain creation.
1996 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1997 hammer2_chain_countbrefs(parent, base, count);
2004 hammer2_spin_ex(&parent->core.spin);
2005 chain = hammer2_combined_find(parent, base, count,
2006 cache_indexp, key_nextp,
2009 generation = parent->core.generation;
2014 * Exhausted parent chain, iterate.
2018 hammer2_spin_unex(&parent->core.spin);
2019 if (key_beg == key_end) /* short cut single-key case */
2023 * Stop if we reached the end of the iteration.
2025 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2026 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2031 * Calculate next key, stop if we reached the end of the
2032 * iteration, otherwise go up one level and loop.
2034 key_beg = parent->bref.key +
2035 ((hammer2_key_t)1 << parent->bref.keybits);
2036 if (key_beg == 0 || key_beg > key_end)
2038 parent = hammer2_chain_getparent(parentp, how_maybe);
2043 * Selected from blockref or in-memory chain.
2045 if (chain == NULL) {
2048 hammer2_spin_unex(&parent->core.spin);
2049 chain = hammer2_chain_get(parent, generation,
2051 if (chain == NULL) {
2052 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2053 parent, key_beg, key_end);
2056 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2057 hammer2_chain_drop(chain);
2062 hammer2_chain_ref(chain);
2063 hammer2_spin_unex(&parent->core.spin);
2068 * chain is referenced but not locked. We must lock the chain
2069 * to obtain definitive DUPLICATED/DELETED state
2071 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2072 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2073 hammer2_chain_lock(chain, how_maybe);
2075 hammer2_chain_lock(chain, how);
2080 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2082 * NOTE: Chain's key range is not relevant as there might be
2083 * one-offs within the range that are not deleted.
2085 * NOTE: Lookups can race delete-duplicate because
2086 * delete-duplicate does not lock the parent's core
2087 * (they just use the spinlock on the core). We must
2088 * check for races by comparing the DUPLICATED flag before
2089 * releasing the spinlock with the flag after locking the
2092 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2093 hammer2_chain_unlock(chain);
2094 hammer2_chain_drop(chain);
2095 key_beg = *key_nextp;
2096 if (key_beg == 0 || key_beg > key_end)
2103 * If the chain element is an indirect block it becomes the new
2104 * parent and we loop on it. We must maintain our top-down locks
2105 * to prevent the flusher from interfering (i.e. doing a
2106 * delete-duplicate and leaving us recursing down a deleted chain).
2108 * The parent always has to be locked with at least RESOLVE_MAYBE
2109 * so we can access its data. It might need a fixup if the caller
2110 * passed incompatible flags. Be careful not to cause a deadlock
2111 * as a data-load requires an exclusive lock.
2113 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2114 * range is within the requested key range we return the indirect
2115 * block and do NOT loop. This is usually only used to acquire
2118 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2119 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2120 hammer2_chain_unlock(parent);
2121 hammer2_chain_drop(parent);
2122 *parentp = parent = chain;
2128 * All done, return the chain.
2130 * If the caller does not want a locked chain, replace the lock with
2131 * a ref. Perhaps this can eventually be optimized to not obtain the
2132 * lock in the first place for situations where the data does not
2133 * need to be resolved.
2136 if (flags & HAMMER2_LOOKUP_NOLOCK)
2137 hammer2_chain_unlock(chain);
2145 * After having issued a lookup we can iterate all matching keys.
2147 * If chain is non-NULL we continue the iteration from just after it's index.
2149 * If chain is NULL we assume the parent was exhausted and continue the
2150 * iteration at the next parent.
2152 * If a fatal error occurs (typically an I/O error), a dummy chain is
2153 * returned with chain->error and error-identifying information set. This
2154 * chain will assert if you try to do anything fancy with it.
2156 * XXX Depending on where the error occurs we should allow continued iteration.
2158 * parent must be locked on entry and remains locked throughout. chain's
2159 * lock status must match flags. Chain is always at least referenced.
2161 * WARNING! The MATCHIND flag does not apply to this function.
2164 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2165 hammer2_key_t *key_nextp,
2166 hammer2_key_t key_beg, hammer2_key_t key_end,
2167 int *cache_indexp, int flags)
2169 hammer2_chain_t *parent;
2173 * Calculate locking flags for upward recursion.
2175 how_maybe = HAMMER2_RESOLVE_MAYBE;
2176 if (flags & HAMMER2_LOOKUP_SHARED)
2177 how_maybe |= HAMMER2_RESOLVE_SHARED;
2182 * Calculate the next index and recalculate the parent if necessary.
2185 key_beg = chain->bref.key +
2186 ((hammer2_key_t)1 << chain->bref.keybits);
2187 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2188 HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2189 hammer2_chain_unlock(chain);
2191 hammer2_chain_drop(chain);
2194 * chain invalid past this point, but we can still do a
2195 * pointer comparison w/parent.
2197 * Any scan where the lookup returned degenerate data embedded
2198 * in the inode has an invalid index and must terminate.
2200 if (chain == parent)
2202 if (key_beg == 0 || key_beg > key_end)
2205 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2206 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2208 * We reached the end of the iteration.
2213 * Continue iteration with next parent unless the current
2214 * parent covers the range.
2216 key_beg = parent->bref.key +
2217 ((hammer2_key_t)1 << parent->bref.keybits);
2218 if (key_beg == 0 || key_beg > key_end)
2220 parent = hammer2_chain_getparent(parentp, how_maybe);
2226 return (hammer2_chain_lookup(parentp, key_nextp,
2228 cache_indexp, flags));
2232 * The raw scan function is similar to lookup/next but does not seek to a key.
2233 * Blockrefs are iterated via first_bref = (parent, NULL) and
2234 * next_chain = (parent, bref).
2236 * The passed-in parent must be locked and its data resolved. The function
2237 * nominally returns a locked and referenced *chainp != NULL for chains
2238 * the caller might need to recurse on (and will dipose of any *chainp passed
2239 * in). The caller must check the chain->bref.type either way.
2241 * *chainp is not set for leaf elements.
2243 * This function takes a pointer to a stack-based bref structure whos
2244 * contents is updated for each iteration. The same pointer is returned,
2245 * or NULL when the iteration is complete. *firstp must be set to 1 for
2246 * the first ieration. This function will set it to 0.
2248 hammer2_blockref_t *
2249 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2250 hammer2_blockref_t *bref, int *firstp,
2251 int *cache_indexp, int flags)
2254 hammer2_blockref_t *base;
2255 hammer2_blockref_t *bref_ptr;
2257 hammer2_key_t next_key;
2258 hammer2_chain_t *chain = NULL;
2260 int how_always = HAMMER2_RESOLVE_ALWAYS;
2261 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2264 int maxloops = 300000;
2269 * Scan flags borrowed from lookup.
2271 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2272 how_maybe = how_always;
2273 how = HAMMER2_RESOLVE_ALWAYS;
2274 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2275 how = HAMMER2_RESOLVE_NEVER;
2277 how = HAMMER2_RESOLVE_MAYBE;
2279 if (flags & HAMMER2_LOOKUP_SHARED) {
2280 how_maybe |= HAMMER2_RESOLVE_SHARED;
2281 how_always |= HAMMER2_RESOLVE_SHARED;
2282 how |= HAMMER2_RESOLVE_SHARED;
2286 * Calculate key to locate first/next element, unlocking the previous
2287 * element as we go. Be careful, the key calculation can overflow.
2289 * (also reset bref to NULL)
2295 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2296 if ((chain = *chainp) != NULL) {
2298 hammer2_chain_unlock(chain);
2299 hammer2_chain_drop(chain);
2309 KKASSERT(parent->error == 0); /* XXX case not handled yet */
2310 if (--maxloops == 0)
2311 panic("hammer2_chain_scan: maxloops");
2313 * Locate the blockref array. Currently we do a fully associative
2314 * search through the array.
2316 switch(parent->bref.type) {
2317 case HAMMER2_BREF_TYPE_INODE:
2319 * An inode with embedded data has no sub-chains.
2321 * WARNING! Bulk scan code may pass a static chain marked
2322 * as BREF_TYPE_INODE with a copy of the volume
2323 * root blockset to snapshot the volume.
2325 if (parent->data->ipdata.meta.op_flags &
2326 HAMMER2_OPFLAG_DIRECTDATA) {
2330 base = &parent->data->ipdata.u.blockset.blockref[0];
2331 count = HAMMER2_SET_COUNT;
2333 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2334 case HAMMER2_BREF_TYPE_INDIRECT:
2336 * Optimize indirect blocks in the INITIAL state to avoid
2339 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2342 if (parent->data == NULL)
2343 panic("parent->data is NULL");
2344 base = &parent->data->npdata[0];
2346 count = parent->bytes / sizeof(hammer2_blockref_t);
2348 case HAMMER2_BREF_TYPE_VOLUME:
2349 base = &parent->data->voldata.sroot_blockset.blockref[0];
2350 count = HAMMER2_SET_COUNT;
2352 case HAMMER2_BREF_TYPE_FREEMAP:
2353 base = &parent->data->blkset.blockref[0];
2354 count = HAMMER2_SET_COUNT;
2357 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2359 base = NULL; /* safety */
2360 count = 0; /* safety */
2364 * Merged scan to find next candidate.
2366 * hammer2_base_*() functions require the parent->core.live_* fields
2367 * to be synchronized.
2369 * We need to hold the spinlock to access the block array and RB tree
2370 * and to interlock chain creation.
2372 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2373 hammer2_chain_countbrefs(parent, base, count);
2377 hammer2_spin_ex(&parent->core.spin);
2378 chain = hammer2_combined_find(parent, base, count,
2379 cache_indexp, &next_key,
2380 key, HAMMER2_KEY_MAX,
2382 generation = parent->core.generation;
2385 * Exhausted parent chain, we're done.
2387 if (bref_ptr == NULL) {
2388 hammer2_spin_unex(&parent->core.spin);
2389 KKASSERT(chain == NULL);
2395 * Copy into the supplied stack-based blockref.
2400 * Selected from blockref or in-memory chain.
2402 if (chain == NULL) {
2403 switch(bref->type) {
2404 case HAMMER2_BREF_TYPE_INODE:
2405 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2406 case HAMMER2_BREF_TYPE_INDIRECT:
2407 case HAMMER2_BREF_TYPE_VOLUME:
2408 case HAMMER2_BREF_TYPE_FREEMAP:
2410 * Recursion, always get the chain
2412 hammer2_spin_unex(&parent->core.spin);
2413 chain = hammer2_chain_get(parent, generation, bref);
2414 if (chain == NULL) {
2415 kprintf("retry scan parent %p keys %016jx\n",
2419 if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2420 hammer2_chain_drop(chain);
2427 * No recursion, do not waste time instantiating
2428 * a chain, just iterate using the bref.
2430 hammer2_spin_unex(&parent->core.spin);
2435 * Recursion or not we need the chain in order to supply
2438 hammer2_chain_ref(chain);
2439 hammer2_spin_unex(&parent->core.spin);
2443 * chain is referenced but not locked. We must lock the chain
2444 * to obtain definitive DUPLICATED/DELETED state
2447 hammer2_chain_lock(chain, how);
2450 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2452 * NOTE: chain's key range is not relevant as there might be
2453 * one-offs within the range that are not deleted.
2455 * NOTE: XXX this could create problems with scans used in
2456 * situations other than mount-time recovery.
2458 * NOTE: Lookups can race delete-duplicate because
2459 * delete-duplicate does not lock the parent's core
2460 * (they just use the spinlock on the core). We must
2461 * check for races by comparing the DUPLICATED flag before
2462 * releasing the spinlock with the flag after locking the
2465 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2466 hammer2_chain_unlock(chain);
2467 hammer2_chain_drop(chain);
2480 * All done, return the bref or NULL, supply chain if necessary.
2488 * Create and return a new hammer2 system memory structure of the specified
2489 * key, type and size and insert it under (*parentp). This is a full
2490 * insertion, based on the supplied key/keybits, and may involve creating
2491 * indirect blocks and moving other chains around via delete/duplicate.
2493 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2494 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2495 * FULL. This typically means that the caller is creating the chain after
2496 * doing a hammer2_chain_lookup().
2498 * (*parentp) must be exclusive locked and may be replaced on return
2499 * depending on how much work the function had to do.
2501 * (*parentp) must not be errored or this function will assert.
2503 * (*chainp) usually starts out NULL and returns the newly created chain,
2504 * but if the caller desires the caller may allocate a disconnected chain
2505 * and pass it in instead.
2507 * This function should NOT be used to insert INDIRECT blocks. It is
2508 * typically used to create/insert inodes and data blocks.
2510 * Caller must pass-in an exclusively locked parent the new chain is to
2511 * be inserted under, and optionally pass-in a disconnected, exclusively
2512 * locked chain to insert (else we create a new chain). The function will
2513 * adjust (*parentp) as necessary, create or connect the chain, and
2514 * return an exclusively locked chain in *chainp.
2516 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2517 * and will be reassigned.
2520 hammer2_chain_create(hammer2_chain_t **parentp,
2521 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2522 hammer2_key_t key, int keybits, int type, size_t bytes,
2523 hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2526 hammer2_chain_t *chain;
2527 hammer2_chain_t *parent;
2528 hammer2_blockref_t *base;
2529 hammer2_blockref_t dummy;
2533 int maxloops = 300000;
2536 * Topology may be crossing a PFS boundary.
2539 KKASSERT(hammer2_mtx_owned(&parent->lock));
2540 KKASSERT(parent->error == 0);
2544 if (chain == NULL) {
2546 * First allocate media space and construct the dummy bref,
2547 * then allocate the in-memory chain structure. Set the
2548 * INITIAL flag for fresh chains which do not have embedded
2551 * XXX for now set the check mode of the child based on
2552 * the parent or, if the parent is an inode, the
2553 * specification in the inode.
2555 bzero(&dummy, sizeof(dummy));
2558 dummy.keybits = keybits;
2559 dummy.data_off = hammer2_getradix(bytes);
2560 dummy.methods = parent->bref.methods;
2561 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2563 dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2564 dummy.methods |= HAMMER2_ENC_CHECK(
2565 parent->data->ipdata.meta.check_algo);
2568 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2571 * Lock the chain manually, chain_lock will load the chain
2572 * which we do NOT want to do. (note: chain->refs is set
2573 * to 1 by chain_alloc() for us, but lockcnt is not).
2576 hammer2_mtx_ex(&chain->lock);
2578 ++curthread->td_tracker;
2581 * Set INITIAL to optimize I/O. The flag will generally be
2582 * processed when we call hammer2_chain_modify().
2584 * Recalculate bytes to reflect the actual media block
2587 bytes = (hammer2_off_t)1 <<
2588 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2589 chain->bytes = bytes;
2592 case HAMMER2_BREF_TYPE_VOLUME:
2593 case HAMMER2_BREF_TYPE_FREEMAP:
2594 panic("hammer2_chain_create: called with volume type");
2596 case HAMMER2_BREF_TYPE_INDIRECT:
2597 panic("hammer2_chain_create: cannot be used to"
2598 "create indirect block");
2600 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2601 panic("hammer2_chain_create: cannot be used to"
2602 "create freemap root or node");
2604 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2605 KKASSERT(bytes == sizeof(chain->data->bmdata));
2607 case HAMMER2_BREF_TYPE_INODE:
2608 case HAMMER2_BREF_TYPE_DATA:
2611 * leave chain->data NULL, set INITIAL
2613 KKASSERT(chain->data == NULL);
2614 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2619 * We are reattaching a previously deleted chain, possibly
2620 * under a new parent and possibly with a new key/keybits.
2621 * The chain does not have to be in a modified state. The
2622 * UPDATE flag will be set later on in this routine.
2624 * Do NOT mess with the current state of the INITIAL flag.
2626 chain->bref.key = key;
2627 chain->bref.keybits = keybits;
2628 if (chain->flags & HAMMER2_CHAIN_DELETED)
2629 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2630 KKASSERT(chain->parent == NULL);
2632 if (flags & HAMMER2_INSERT_PFSROOT)
2633 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2635 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2638 * Calculate how many entries we have in the blockref array and
2639 * determine if an indirect block is required.
2642 if (--maxloops == 0)
2643 panic("hammer2_chain_create: maxloops");
2645 switch(parent->bref.type) {
2646 case HAMMER2_BREF_TYPE_INODE:
2647 if ((parent->data->ipdata.meta.op_flags &
2648 HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2649 kprintf("hammer2: parent set for direct-data! "
2650 "pkey=%016jx ckey=%016jx\n",
2654 KKASSERT((parent->data->ipdata.meta.op_flags &
2655 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2656 KKASSERT(parent->data != NULL);
2657 base = &parent->data->ipdata.u.blockset.blockref[0];
2658 count = HAMMER2_SET_COUNT;
2660 case HAMMER2_BREF_TYPE_INDIRECT:
2661 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2662 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2665 base = &parent->data->npdata[0];
2666 count = parent->bytes / sizeof(hammer2_blockref_t);
2668 case HAMMER2_BREF_TYPE_VOLUME:
2669 KKASSERT(parent->data != NULL);
2670 base = &parent->data->voldata.sroot_blockset.blockref[0];
2671 count = HAMMER2_SET_COUNT;
2673 case HAMMER2_BREF_TYPE_FREEMAP:
2674 KKASSERT(parent->data != NULL);
2675 base = &parent->data->blkset.blockref[0];
2676 count = HAMMER2_SET_COUNT;
2679 panic("hammer2_chain_create: unrecognized blockref type: %d",
2687 * Make sure we've counted the brefs
2689 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2690 hammer2_chain_countbrefs(parent, base, count);
2692 KKASSERT(parent->core.live_count >= 0 &&
2693 parent->core.live_count <= count);
2696 * If no free blockref could be found we must create an indirect
2697 * block and move a number of blockrefs into it. With the parent
2698 * locked we can safely lock each child in order to delete+duplicate
2699 * it without causing a deadlock.
2701 * This may return the new indirect block or the old parent depending
2702 * on where the key falls. NULL is returned on error.
2704 if (parent->core.live_count == count) {
2705 hammer2_chain_t *nparent;
2707 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2708 mtid, type, &error);
2709 if (nparent == NULL) {
2711 hammer2_chain_drop(chain);
2715 if (parent != nparent) {
2716 hammer2_chain_unlock(parent);
2717 hammer2_chain_drop(parent);
2718 parent = *parentp = nparent;
2724 * Link the chain into its parent.
2726 if (chain->parent != NULL)
2727 panic("hammer2: hammer2_chain_create: chain already connected");
2728 KKASSERT(chain->parent == NULL);
2729 hammer2_chain_insert(parent, chain,
2730 HAMMER2_CHAIN_INSERT_SPIN |
2731 HAMMER2_CHAIN_INSERT_LIVE,
2736 * Mark the newly created chain modified. This will cause
2737 * UPDATE to be set and process the INITIAL flag.
2739 * Device buffers are not instantiated for DATA elements
2740 * as these are handled by logical buffers.
2742 * Indirect and freemap node indirect blocks are handled
2743 * by hammer2_chain_create_indirect() and not by this
2746 * Data for all other bref types is expected to be
2747 * instantiated (INODE, LEAF).
2749 switch(chain->bref.type) {
2750 case HAMMER2_BREF_TYPE_DATA:
2751 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2752 case HAMMER2_BREF_TYPE_INODE:
2753 hammer2_chain_modify(chain, mtid, dedup_off,
2754 HAMMER2_MODIFY_OPTDATA);
2758 * Remaining types are not supported by this function.
2759 * In particular, INDIRECT and LEAF_NODE types are
2760 * handled by create_indirect().
2762 panic("hammer2_chain_create: bad type: %d",
2769 * When reconnecting a chain we must set UPDATE and
2770 * setflush so the flush recognizes that it must update
2771 * the bref in the parent.
2773 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
2774 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2778 * We must setflush(parent) to ensure that it recurses through to
2779 * chain. setflush(chain) might not work because ONFLUSH is possibly
2780 * already set in the chain (so it won't recurse up to set it in the
2783 hammer2_chain_setflush(parent);
2792 * Move the chain from its old parent to a new parent. The chain must have
2793 * already been deleted or already disconnected (or never associated) with
2794 * a parent. The chain is reassociated with the new parent and the deleted
2795 * flag will be cleared (no longer deleted). The chain's modification state
2798 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2799 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2800 * FULL. This typically means that the caller is creating the chain after
2801 * doing a hammer2_chain_lookup().
2803 * A non-NULL bref is typically passed when key and keybits must be overridden.
2804 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2805 * from a passed-in bref and uses the old chain's bref for everything else.
2807 * Neither (parent) or (chain) can be errored.
2809 * If (parent) is non-NULL then the new duplicated chain is inserted under
2812 * If (parent) is NULL then the newly duplicated chain is not inserted
2813 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2814 * passing into hammer2_chain_create() after this function returns).
2816 * WARNING! This function calls create which means it can insert indirect
2817 * blocks. This can cause other unrelated chains in the parent to
2818 * be moved to a newly inserted indirect block in addition to the
2822 hammer2_chain_rename(hammer2_blockref_t *bref,
2823 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2824 hammer2_tid_t mtid, int flags)
2827 hammer2_chain_t *parent;
2831 * WARNING! We should never resolve DATA to device buffers
2832 * (XXX allow it if the caller did?), and since
2833 * we currently do not have the logical buffer cache
2834 * buffer in-hand to fix its cached physical offset
2835 * we also force the modify code to not COW it. XXX
2838 KKASSERT(chain->parent == NULL);
2839 KKASSERT(chain->error == 0);
2842 * Now create a duplicate of the chain structure, associating
2843 * it with the same core, making it the same size, pointing it
2844 * to the same bref (the same media block).
2847 bref = &chain->bref;
2848 bytes = (hammer2_off_t)1 <<
2849 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2852 * If parent is not NULL the duplicated chain will be entered under
2853 * the parent and the UPDATE bit set to tell flush to update
2856 * We must setflush(parent) to ensure that it recurses through to
2857 * chain. setflush(chain) might not work because ONFLUSH is possibly
2858 * already set in the chain (so it won't recurse up to set it in the
2861 * Having both chains locked is extremely important for atomicy.
2863 if (parentp && (parent = *parentp) != NULL) {
2864 KKASSERT(hammer2_mtx_owned(&parent->lock));
2865 KKASSERT(parent->refs > 0);
2866 KKASSERT(parent->error == 0);
2868 hammer2_chain_create(parentp, &chain, chain->pmp,
2869 bref->key, bref->keybits, bref->type,
2870 chain->bytes, mtid, 0, flags);
2871 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2872 hammer2_chain_setflush(*parentp);
2877 * Helper function for deleting chains.
2879 * The chain is removed from the live view (the RBTREE) as well as the parent's
2880 * blockmap. Both chain and its parent must be locked.
2882 * parent may not be errored. chain can be errored.
2885 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2886 hammer2_tid_t mtid, int flags)
2890 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2891 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2892 KKASSERT(chain->parent == parent);
2895 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2897 * Chain is blockmapped, so there must be a parent.
2898 * Atomically remove the chain from the parent and remove
2899 * the blockmap entry. The parent must be set modified
2900 * to remove the blockmap entry.
2902 hammer2_blockref_t *base;
2905 KKASSERT(parent != NULL);
2906 KKASSERT(parent->error == 0);
2907 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2908 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
2911 * Calculate blockmap pointer
2913 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2914 hammer2_spin_ex(&parent->core.spin);
2916 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2917 atomic_add_int(&parent->core.live_count, -1);
2918 ++parent->core.generation;
2919 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2920 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2921 --parent->core.chain_count;
2922 chain->parent = NULL;
2924 switch(parent->bref.type) {
2925 case HAMMER2_BREF_TYPE_INODE:
2927 * Access the inode's block array. However, there
2928 * is no block array if the inode is flagged
2929 * DIRECTDATA. The DIRECTDATA case typicaly only
2930 * occurs when a hardlink has been shifted up the
2931 * tree and the original inode gets replaced with
2932 * an OBJTYPE_HARDLINK placeholding inode.
2935 (parent->data->ipdata.meta.op_flags &
2936 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2938 &parent->data->ipdata.u.blockset.blockref[0];
2942 count = HAMMER2_SET_COUNT;
2944 case HAMMER2_BREF_TYPE_INDIRECT:
2945 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2947 base = &parent->data->npdata[0];
2950 count = parent->bytes / sizeof(hammer2_blockref_t);
2952 case HAMMER2_BREF_TYPE_VOLUME:
2953 base = &parent->data->voldata.
2954 sroot_blockset.blockref[0];
2955 count = HAMMER2_SET_COUNT;
2957 case HAMMER2_BREF_TYPE_FREEMAP:
2958 base = &parent->data->blkset.blockref[0];
2959 count = HAMMER2_SET_COUNT;
2964 panic("hammer2_flush_pass2: "
2965 "unrecognized blockref type: %d",
2970 * delete blockmapped chain from its parent.
2972 * The parent is not affected by any statistics in chain
2973 * which are pending synchronization. That is, there is
2974 * nothing to undo in the parent since they have not yet
2975 * been incorporated into the parent.
2977 * The parent is affected by statistics stored in inodes.
2978 * Those have already been synchronized, so they must be
2979 * undone. XXX split update possible w/delete in middle?
2982 int cache_index = -1;
2983 hammer2_base_delete(parent, base, count,
2984 &cache_index, chain);
2986 hammer2_spin_unex(&parent->core.spin);
2987 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2989 * Chain is not blockmapped but a parent is present.
2990 * Atomically remove the chain from the parent. There is
2991 * no blockmap entry to remove.
2993 * Because chain was associated with a parent but not
2994 * synchronized, the chain's *_count_up fields contain
2995 * inode adjustment statistics which must be undone.
2997 hammer2_spin_ex(&parent->core.spin);
2998 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2999 atomic_add_int(&parent->core.live_count, -1);
3000 ++parent->core.generation;
3001 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3002 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3003 --parent->core.chain_count;
3004 chain->parent = NULL;
3005 hammer2_spin_unex(&parent->core.spin);
3008 * Chain is not blockmapped and has no parent. This
3009 * is a degenerate case.
3011 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3016 * Create an indirect block that covers one or more of the elements in the
3017 * current parent. Either returns the existing parent with no locking or
3018 * ref changes or returns the new indirect block locked and referenced
3019 * and leaving the original parent lock/ref intact as well.
3021 * If an error occurs, NULL is returned and *errorp is set to the error.
3023 * The returned chain depends on where the specified key falls.
3025 * The key/keybits for the indirect mode only needs to follow three rules:
3027 * (1) That all elements underneath it fit within its key space and
3029 * (2) That all elements outside it are outside its key space.
3031 * (3) When creating the new indirect block any elements in the current
3032 * parent that fit within the new indirect block's keyspace must be
3033 * moved into the new indirect block.
3035 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3036 * keyspace the the current parent, but lookup/iteration rules will
3037 * ensure (and must ensure) that rule (2) for all parents leading up
3038 * to the nearest inode or the root volume header is adhered to. This
3039 * is accomplished by always recursing through matching keyspaces in
3040 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3042 * The current implementation calculates the current worst-case keyspace by
3043 * iterating the current parent and then divides it into two halves, choosing
3044 * whichever half has the most elements (not necessarily the half containing
3045 * the requested key).
3047 * We can also opt to use the half with the least number of elements. This
3048 * causes lower-numbered keys (aka logical file offsets) to recurse through
3049 * fewer indirect blocks and higher-numbered keys to recurse through more.
3050 * This also has the risk of not moving enough elements to the new indirect
3051 * block and being forced to create several indirect blocks before the element
3054 * Must be called with an exclusively locked parent.
3056 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3057 hammer2_key_t *keyp, int keybits,
3058 hammer2_blockref_t *base, int count);
3059 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3060 hammer2_key_t *keyp, int keybits,
3061 hammer2_blockref_t *base, int count);
3064 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3065 hammer2_key_t create_key, int create_bits,
3066 hammer2_tid_t mtid, int for_type, int *errorp)
3069 hammer2_blockref_t *base;
3070 hammer2_blockref_t *bref;
3071 hammer2_blockref_t bcopy;
3072 hammer2_chain_t *chain;
3073 hammer2_chain_t *ichain;
3074 hammer2_chain_t dummy;
3075 hammer2_key_t key = create_key;
3076 hammer2_key_t key_beg;
3077 hammer2_key_t key_end;
3078 hammer2_key_t key_next;
3079 int keybits = create_bits;
3086 int maxloops = 300000;
3089 * Calculate the base blockref pointer or NULL if the chain
3090 * is known to be empty. We need to calculate the array count
3091 * for RB lookups either way.
3095 KKASSERT(hammer2_mtx_owned(&parent->lock));
3097 /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3098 base = hammer2_chain_base_and_count(parent, &count);
3101 * dummy used in later chain allocation (no longer used for lookups).
3103 bzero(&dummy, sizeof(dummy));
3106 * When creating an indirect block for a freemap node or leaf
3107 * the key/keybits must be fitted to static radix levels because
3108 * particular radix levels use particular reserved blocks in the
3111 * This routine calculates the key/radix of the indirect block
3112 * we need to create, and whether it is on the high-side or the
3115 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3116 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3117 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3120 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3125 * Normalize the key for the radix being represented, keeping the
3126 * high bits and throwing away the low bits.
3128 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3131 * How big should our new indirect block be? It has to be at least
3132 * as large as its parent.
3134 * The freemap uses a specific indirect block size.
3136 * The first indirect block level down from an inode typically
3137 * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3139 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3140 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3141 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3142 } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3143 nbytes = HAMMER2_IND_BYTES_MIN;
3145 nbytes = HAMMER2_IND_BYTES_MAX;
3147 if (nbytes < count * sizeof(hammer2_blockref_t)) {
3148 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3149 for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3150 nbytes = count * sizeof(hammer2_blockref_t);
3154 * Ok, create our new indirect block
3156 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3157 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3158 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3160 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3162 dummy.bref.key = key;
3163 dummy.bref.keybits = keybits;
3164 dummy.bref.data_off = hammer2_getradix(nbytes);
3165 dummy.bref.methods = parent->bref.methods;
3167 ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3168 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3169 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3170 /* ichain has one ref at this point */
3173 * We have to mark it modified to allocate its block, but use
3174 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3175 * it won't be acted upon by the flush code.
3177 hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3180 * Iterate the original parent and move the matching brefs into
3181 * the new indirect block.
3183 * XXX handle flushes.
3186 key_end = HAMMER2_KEY_MAX;
3188 hammer2_spin_ex(&parent->core.spin);
3194 * Parent may have been modified, relocating its block array.
3195 * Reload the base pointer.
3197 base = hammer2_chain_base_and_count(parent, &count);
3199 if (++loops > 100000) {
3200 hammer2_spin_unex(&parent->core.spin);
3201 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3202 reason, parent, base, count, key_next);
3206 * NOTE: spinlock stays intact, returned chain (if not NULL)
3207 * is not referenced or locked which means that we
3208 * cannot safely check its flagged / deletion status
3211 chain = hammer2_combined_find(parent, base, count,
3212 &cache_index, &key_next,
3215 generation = parent->core.generation;
3218 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3221 * Skip keys that are not within the key/radix of the new
3222 * indirect block. They stay in the parent.
3224 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3225 (key ^ bref->key)) != 0) {
3226 goto next_key_spinlocked;
3230 * Load the new indirect block by acquiring the related
3231 * chains (potentially from media as it might not be
3232 * in-memory). Then move it to the new parent (ichain)
3233 * via DELETE-DUPLICATE.
3235 * chain is referenced but not locked. We must lock the
3236 * chain to obtain definitive DUPLICATED/DELETED state
3240 * Use chain already present in the RBTREE
3242 hammer2_chain_ref(chain);
3243 hammer2_spin_unex(&parent->core.spin);
3244 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3247 * Get chain for blockref element. _get returns NULL
3248 * on insertion race.
3251 hammer2_spin_unex(&parent->core.spin);
3252 chain = hammer2_chain_get(parent, generation, &bcopy);
3253 if (chain == NULL) {
3255 hammer2_spin_ex(&parent->core.spin);
3258 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3259 kprintf("REASON 2\n");
3261 hammer2_chain_drop(chain);
3262 hammer2_spin_ex(&parent->core.spin);
3265 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3269 * This is always live so if the chain has been deleted
3270 * we raced someone and we have to retry.
3272 * NOTE: Lookups can race delete-duplicate because
3273 * delete-duplicate does not lock the parent's core
3274 * (they just use the spinlock on the core). We must
3275 * check for races by comparing the DUPLICATED flag before
3276 * releasing the spinlock with the flag after locking the
3279 * (note reversed logic for this one)
3281 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3282 hammer2_chain_unlock(chain);
3283 hammer2_chain_drop(chain);
3288 * Shift the chain to the indirect block.
3290 * WARNING! No reason for us to load chain data, pass NOSTATS
3291 * to prevent delete/insert from trying to access
3292 * inode stats (and thus asserting if there is no
3293 * chain->data loaded).
3295 * WARNING! The (parent, chain) deletion may modify the parent
3296 * and invalidate the base pointer.
3298 hammer2_chain_delete(parent, chain, mtid, 0);
3299 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3300 hammer2_chain_unlock(chain);
3301 hammer2_chain_drop(chain);
3302 KKASSERT(parent->refs > 0);
3304 base = NULL; /* safety */
3306 hammer2_spin_ex(&parent->core.spin);
3307 next_key_spinlocked:
3308 if (--maxloops == 0)
3309 panic("hammer2_chain_create_indirect: maxloops");
3311 if (key_next == 0 || key_next > key_end)
3316 hammer2_spin_unex(&parent->core.spin);
3319 * Insert the new indirect block into the parent now that we've
3320 * cleared out some entries in the parent. We calculated a good
3321 * insertion index in the loop above (ichain->index).
3323 * We don't have to set UPDATE here because we mark ichain
3324 * modified down below (so the normal modified -> flush -> set-moved
3325 * sequence applies).
3327 * The insertion shouldn't race as this is a completely new block
3328 * and the parent is locked.
3330 base = NULL; /* safety, parent modify may change address */
3331 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3332 hammer2_chain_insert(parent, ichain,
3333 HAMMER2_CHAIN_INSERT_SPIN |
3334 HAMMER2_CHAIN_INSERT_LIVE,
3338 * Make sure flushes propogate after our manual insertion.
3340 hammer2_chain_setflush(ichain);
3341 hammer2_chain_setflush(parent);
3344 * Figure out what to return.
3346 if (~(((hammer2_key_t)1 << keybits) - 1) &
3347 (create_key ^ key)) {
3349 * Key being created is outside the key range,
3350 * return the original parent.
3352 hammer2_chain_unlock(ichain);
3353 hammer2_chain_drop(ichain);
3356 * Otherwise its in the range, return the new parent.
3357 * (leave both the new and old parent locked).
3366 * Calculate the keybits and highside/lowside of the freemap node the
3367 * caller is creating.
3369 * This routine will specify the next higher-level freemap key/radix
3370 * representing the lowest-ordered set. By doing so, eventually all
3371 * low-ordered sets will be moved one level down.
3373 * We have to be careful here because the freemap reserves a limited
3374 * number of blocks for a limited number of levels. So we can't just
3375 * push indiscriminately.
3378 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3379 int keybits, hammer2_blockref_t *base, int count)
3381 hammer2_chain_t *chain;
3382 hammer2_blockref_t *bref;
3384 hammer2_key_t key_beg;
3385 hammer2_key_t key_end;
3386 hammer2_key_t key_next;
3390 int maxloops = 300000;
3398 * Calculate the range of keys in the array being careful to skip
3399 * slots which are overridden with a deletion.
3402 key_end = HAMMER2_KEY_MAX;
3404 hammer2_spin_ex(&parent->core.spin);
3407 if (--maxloops == 0) {
3408 panic("indkey_freemap shit %p %p:%d\n",
3409 parent, base, count);
3411 chain = hammer2_combined_find(parent, base, count,
3412 &cache_index, &key_next,
3423 * Skip deleted chains.
3425 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3426 if (key_next == 0 || key_next > key_end)
3433 * Use the full live (not deleted) element for the scan
3434 * iteration. HAMMER2 does not allow partial replacements.
3436 * XXX should be built into hammer2_combined_find().
3438 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3440 if (keybits > bref->keybits) {
3442 keybits = bref->keybits;
3443 } else if (keybits == bref->keybits && bref->key < key) {
3450 hammer2_spin_unex(&parent->core.spin);
3453 * Return the keybits for a higher-level FREEMAP_NODE covering
3457 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3458 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3460 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3461 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3463 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3464 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3466 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3467 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3469 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3470 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3472 case HAMMER2_FREEMAP_LEVEL5_RADIX:
3473 panic("hammer2_chain_indkey_freemap: level too high");
3476 panic("hammer2_chain_indkey_freemap: bad radix");
3485 * Calculate the keybits and highside/lowside of the indirect block the
3486 * caller is creating.
3489 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3490 int keybits, hammer2_blockref_t *base, int count)
3492 hammer2_blockref_t *bref;
3493 hammer2_chain_t *chain;
3494 hammer2_key_t key_beg;
3495 hammer2_key_t key_end;
3496 hammer2_key_t key_next;
3502 int maxloops = 300000;
3509 * Calculate the range of keys in the array being careful to skip
3510 * slots which are overridden with a deletion. Once the scan
3511 * completes we will cut the key range in half and shift half the
3512 * range into the new indirect block.
3515 key_end = HAMMER2_KEY_MAX;
3517 hammer2_spin_ex(&parent->core.spin);
3520 if (--maxloops == 0) {
3521 panic("indkey_freemap shit %p %p:%d\n",
3522 parent, base, count);
3524 chain = hammer2_combined_find(parent, base, count,
3525 &cache_index, &key_next,
3536 * NOTE: No need to check DUPLICATED here because we do
3537 * not release the spinlock.
3539 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3540 if (key_next == 0 || key_next > key_end)
3547 * Use the full live (not deleted) element for the scan
3548 * iteration. HAMMER2 does not allow partial replacements.
3550 * XXX should be built into hammer2_combined_find().
3552 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3555 * Expand our calculated key range (key, keybits) to fit
3556 * the scanned key. nkeybits represents the full range
3557 * that we will later cut in half (two halves @ nkeybits - 1).
3560 if (nkeybits < bref->keybits) {
3561 if (bref->keybits > 64) {
3562 kprintf("bad bref chain %p bref %p\n",
3566 nkeybits = bref->keybits;
3568 while (nkeybits < 64 &&
3569 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3570 (key ^ bref->key)) != 0) {
3575 * If the new key range is larger we have to determine
3576 * which side of the new key range the existing keys fall
3577 * under by checking the high bit, then collapsing the
3578 * locount into the hicount or vise-versa.
3580 if (keybits != nkeybits) {
3581 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3592 * The newly scanned key will be in the lower half or the
3593 * upper half of the (new) key range.
3595 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3604 hammer2_spin_unex(&parent->core.spin);
3605 bref = NULL; /* now invalid (safety) */
3608 * Adjust keybits to represent half of the full range calculated
3609 * above (radix 63 max)
3614 * Select whichever half contains the most elements. Theoretically
3615 * we can select either side as long as it contains at least one
3616 * element (in order to ensure that a free slot is present to hold
3617 * the indirect block).
3619 if (hammer2_indirect_optimize) {
3621 * Insert node for least number of keys, this will arrange
3622 * the first few blocks of a large file or the first few
3623 * inodes in a directory with fewer indirect blocks when
3626 if (hicount < locount && hicount != 0)
3627 key |= (hammer2_key_t)1 << keybits;
3629 key &= ~(hammer2_key_t)1 << keybits;
3632 * Insert node for most number of keys, best for heavily
3635 if (hicount > locount)
3636 key |= (hammer2_key_t)1 << keybits;
3638 key &= ~(hammer2_key_t)1 << keybits;
3646 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3649 * Both parent and chain must be locked exclusively.
3651 * This function will modify the parent if the blockref requires removal
3652 * from the parent's block table.
3654 * This function is NOT recursive. Any entity already pushed into the
3655 * chain (such as an inode) may still need visibility into its contents,
3656 * as well as the ability to read and modify the contents. For example,
3657 * for an unlinked file which is still open.
3660 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3661 hammer2_tid_t mtid, int flags)
3663 KKASSERT(hammer2_mtx_owned(&chain->lock));
3666 * Nothing to do if already marked.
3668 * We need the spinlock on the core whos RBTREE contains chain
3669 * to protect against races.
3671 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3672 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3673 chain->parent == parent);
3674 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3678 * Permanent deletions mark the chain as destroyed. H
3680 if (flags & HAMMER2_DELETE_PERMANENT) {
3681 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3683 /* XXX might not be needed */
3684 hammer2_chain_setflush(chain);
3689 * Returns the index of the nearest element in the blockref array >= elm.
3690 * Returns (count) if no element could be found.
3692 * Sets *key_nextp to the next key for loop purposes but does not modify
3693 * it if the next key would be higher than the current value of *key_nextp.
3694 * Note that *key_nexp can overflow to 0, which should be tested by the
3697 * (*cache_indexp) is a heuristic and can be any value without effecting
3700 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3701 * held through the operation.
3704 hammer2_base_find(hammer2_chain_t *parent,
3705 hammer2_blockref_t *base, int count,
3706 int *cache_indexp, hammer2_key_t *key_nextp,
3707 hammer2_key_t key_beg, hammer2_key_t key_end)
3709 hammer2_blockref_t *scan;
3710 hammer2_key_t scan_end;
3715 * Require the live chain's already have their core's counted
3716 * so we can optimize operations.
3718 KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3723 if (count == 0 || base == NULL)
3727 * Sequential optimization using *cache_indexp. This is the most
3730 * We can avoid trailing empty entries on live chains, otherwise
3731 * we might have to check the whole block array.
3735 limit = parent->core.live_zero;
3740 KKASSERT(i < count);
3746 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3753 * Search forwards, stop when we find a scan element which
3754 * encloses the key or until we know that there are no further
3758 if (scan->type != 0) {
3759 scan_end = scan->key +
3760 ((hammer2_key_t)1 << scan->keybits) - 1;
3761 if (scan->key > key_beg || scan_end >= key_beg)
3774 scan_end = scan->key +
3775 ((hammer2_key_t)1 << scan->keybits);
3776 if (scan_end && (*key_nextp > scan_end ||
3778 *key_nextp = scan_end;
3786 * Do a combined search and return the next match either from the blockref
3787 * array or from the in-memory chain. Sets *bresp to the returned bref in
3788 * both cases, or sets it to NULL if the search exhausted. Only returns
3789 * a non-NULL chain if the search matched from the in-memory chain.
3791 * When no in-memory chain has been found and a non-NULL bref is returned
3795 * The returned chain is not locked or referenced. Use the returned bref
3796 * to determine if the search exhausted or not. Iterate if the base find
3797 * is chosen but matches a deleted chain.
3799 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3800 * held through the operation.
3802 static hammer2_chain_t *
3803 hammer2_combined_find(hammer2_chain_t *parent,
3804 hammer2_blockref_t *base, int count,
3805 int *cache_indexp, hammer2_key_t *key_nextp,
3806 hammer2_key_t key_beg, hammer2_key_t key_end,
3807 hammer2_blockref_t **bresp)
3809 hammer2_blockref_t *bref;
3810 hammer2_chain_t *chain;
3814 * Lookup in block array and in rbtree.
3816 *key_nextp = key_end + 1;
3817 i = hammer2_base_find(parent, base, count, cache_indexp,
3818 key_nextp, key_beg, key_end);
3819 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3824 if (i == count && chain == NULL) {
3830 * Only chain matched.
3833 bref = &chain->bref;
3838 * Only blockref matched.
3840 if (chain == NULL) {
3846 * Both in-memory and blockref matched, select the nearer element.
3848 * If both are flush with the left-hand side or both are the
3849 * same distance away, select the chain. In this situation the
3850 * chain must have been loaded from the matching blockmap.
3852 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3853 chain->bref.key == base[i].key) {
3854 KKASSERT(chain->bref.key == base[i].key);
3855 bref = &chain->bref;
3860 * Select the nearer key
3862 if (chain->bref.key < base[i].key) {
3863 bref = &chain->bref;
3870 * If the bref is out of bounds we've exhausted our search.
3873 if (bref->key > key_end) {
3883 * Locate the specified block array element and delete it. The element
3886 * The spin lock on the related chain must be held.
3888 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3889 * need to be adjusted when we commit the media change.
3892 hammer2_base_delete(hammer2_chain_t *parent,
3893 hammer2_blockref_t *base, int count,
3894 int *cache_indexp, hammer2_chain_t *chain)
3896 hammer2_blockref_t *elm = &chain->bref;
3897 hammer2_key_t key_next;
3901 * Delete element. Expect the element to exist.
3903 * XXX see caller, flush code not yet sophisticated enough to prevent
3904 * re-flushed in some cases.
3906 key_next = 0; /* max range */
3907 i = hammer2_base_find(parent, base, count, cache_indexp,
3908 &key_next, elm->key, elm->key);
3909 if (i == count || base[i].type == 0 ||
3910 base[i].key != elm->key ||
3911 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3912 base[i].keybits != elm->keybits)) {
3913 hammer2_spin_unex(&parent->core.spin);
3914 panic("delete base %p element not found at %d/%d elm %p\n",
3915 base, i, count, elm);
3920 * Update stats and zero the entry
3922 parent->bref.data_count -= base[i].data_count;
3923 parent->bref.data_count -= (hammer2_off_t)1 <<
3924 (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3925 parent->bref.inode_count -= base[i].inode_count;
3926 if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3927 parent->bref.inode_count -= 1;
3929 bzero(&base[i], sizeof(*base));
3932 * We can only optimize parent->core.live_zero for live chains.
3934 if (parent->core.live_zero == i + 1) {
3935 while (--i >= 0 && base[i].type == 0)
3937 parent->core.live_zero = i + 1;
3941 * Clear appropriate blockmap flags in chain.
3943 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3944 HAMMER2_CHAIN_BMAPUPD);
3948 * Insert the specified element. The block array must not already have the
3949 * element and must have space available for the insertion.
3951 * The spin lock on the related chain must be held.
3953 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3954 * need to be adjusted when we commit the media change.
3957 hammer2_base_insert(hammer2_chain_t *parent,
3958 hammer2_blockref_t *base, int count,
3959 int *cache_indexp, hammer2_chain_t *chain)
3961 hammer2_blockref_t *elm = &chain->bref;
3962 hammer2_key_t key_next;
3971 * Insert new element. Expect the element to not already exist
3972 * unless we are replacing it.
3974 * XXX see caller, flush code not yet sophisticated enough to prevent
3975 * re-flushed in some cases.
3977 key_next = 0; /* max range */
3978 i = hammer2_base_find(parent, base, count, cache_indexp,
3979 &key_next, elm->key, elm->key);
3982 * Shortcut fill optimization, typical ordered insertion(s) may not
3985 KKASSERT(i >= 0 && i <= count);
3988 * Set appropriate blockmap flags in chain.
3990 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3993 * Update stats and zero the entry
3995 parent->bref.data_count += elm->data_count;
3996 parent->bref.data_count += (hammer2_off_t)1 <<
3997 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3998 parent->bref.inode_count += elm->inode_count;
3999 if (elm->type == HAMMER2_BREF_TYPE_INODE)
4000 parent->bref.inode_count += 1;
4004 * We can only optimize parent->core.live_zero for live chains.
4006 if (i == count && parent->core.live_zero < count) {
4007 i = parent->core.live_zero++;
4012 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4013 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4014 hammer2_spin_unex(&parent->core.spin);
4015 panic("insert base %p overlapping elements at %d elm %p\n",
4020 * Try to find an empty slot before or after.
4024 while (j > 0 || k < count) {
4026 if (j >= 0 && base[j].type == 0) {
4030 bcopy(&base[j+1], &base[j],
4031 (i - j - 1) * sizeof(*base));
4037 if (k < count && base[k].type == 0) {
4038 bcopy(&base[i], &base[i+1],
4039 (k - i) * sizeof(hammer2_blockref_t));
4043 * We can only update parent->core.live_zero for live
4046 if (parent->core.live_zero <= k)
4047 parent->core.live_zero = k + 1;
4052 panic("hammer2_base_insert: no room!");
4059 for (l = 0; l < count; ++l) {
4061 key_next = base[l].key +
4062 ((hammer2_key_t)1 << base[l].keybits) - 1;
4066 while (++l < count) {
4068 if (base[l].key <= key_next)
4069 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4070 key_next = base[l].key +
4071 ((hammer2_key_t)1 << base[l].keybits) - 1;
4081 * Sort the blockref array for the chain. Used by the flush code to
4082 * sort the blockref[] array.
4084 * The chain must be exclusively locked AND spin-locked.
4086 typedef hammer2_blockref_t *hammer2_blockref_p;
4090 hammer2_base_sort_callback(const void *v1, const void *v2)
4092 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4093 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4096 * Make sure empty elements are placed at the end of the array
4098 if (bref1->type == 0) {
4099 if (bref2->type == 0)
4102 } else if (bref2->type == 0) {
4109 if (bref1->key < bref2->key)
4111 if (bref1->key > bref2->key)
4117 hammer2_base_sort(hammer2_chain_t *chain)
4119 hammer2_blockref_t *base;
4122 switch(chain->bref.type) {
4123 case HAMMER2_BREF_TYPE_INODE:
4125 * Special shortcut for embedded data returns the inode
4126 * itself. Callers must detect this condition and access
4127 * the embedded data (the strategy code does this for us).
4129 * This is only applicable to regular files and softlinks.
4131 if (chain->data->ipdata.meta.op_flags &
4132 HAMMER2_OPFLAG_DIRECTDATA) {
4135 base = &chain->data->ipdata.u.blockset.blockref[0];
4136 count = HAMMER2_SET_COUNT;
4138 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4139 case HAMMER2_BREF_TYPE_INDIRECT:
4141 * Optimize indirect blocks in the INITIAL state to avoid
4144 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4145 base = &chain->data->npdata[0];
4146 count = chain->bytes / sizeof(hammer2_blockref_t);
4148 case HAMMER2_BREF_TYPE_VOLUME:
4149 base = &chain->data->voldata.sroot_blockset.blockref[0];
4150 count = HAMMER2_SET_COUNT;
4152 case HAMMER2_BREF_TYPE_FREEMAP:
4153 base = &chain->data->blkset.blockref[0];
4154 count = HAMMER2_SET_COUNT;
4157 kprintf("hammer2_chain_lookup: unrecognized "
4158 "blockref(A) type: %d",
4161 tsleep(&base, 0, "dead", 0);
4162 panic("hammer2_chain_lookup: unrecognized "
4163 "blockref(A) type: %d",
4165 base = NULL; /* safety */
4166 count = 0; /* safety */
4168 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4174 * Chain memory management
4177 hammer2_chain_wait(hammer2_chain_t *chain)
4179 tsleep(chain, 0, "chnflw", 1);
4182 const hammer2_media_data_t *
4183 hammer2_chain_rdata(hammer2_chain_t *chain)
4185 KKASSERT(chain->data != NULL);
4186 return (chain->data);
4189 hammer2_media_data_t *
4190 hammer2_chain_wdata(hammer2_chain_t *chain)
4192 KKASSERT(chain->data != NULL);
4193 return (chain->data);
4197 * Set the check data for a chain. This can be a heavy-weight operation
4198 * and typically only runs on-flush. For file data check data is calculated
4199 * when the logical buffers are flushed.
4202 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4204 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4206 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4207 case HAMMER2_CHECK_NONE:
4209 case HAMMER2_CHECK_DISABLED:
4211 case HAMMER2_CHECK_ISCSI32:
4212 chain->bref.check.iscsi32.value =
4213 hammer2_icrc32(bdata, chain->bytes);
4215 case HAMMER2_CHECK_XXHASH64:
4216 chain->bref.check.xxhash64.value =
4217 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4219 case HAMMER2_CHECK_SHA192:
4221 SHA256_CTX hash_ctx;
4223 uint8_t digest[SHA256_DIGEST_LENGTH];
4224 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4227 SHA256_Init(&hash_ctx);
4228 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4229 SHA256_Final(u.digest, &hash_ctx);
4230 u.digest64[2] ^= u.digest64[3];
4232 chain->bref.check.sha192.data,
4233 sizeof(chain->bref.check.sha192.data));
4236 case HAMMER2_CHECK_FREEMAP:
4237 chain->bref.check.freemap.icrc32 =
4238 hammer2_icrc32(bdata, chain->bytes);
4241 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4242 chain->bref.methods);
4248 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4252 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4255 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4256 case HAMMER2_CHECK_NONE:
4259 case HAMMER2_CHECK_DISABLED:
4262 case HAMMER2_CHECK_ISCSI32:
4263 r = (chain->bref.check.iscsi32.value ==
4264 hammer2_icrc32(bdata, chain->bytes));
4265 hammer2_check_icrc32 += chain->bytes;
4267 case HAMMER2_CHECK_XXHASH64:
4268 r = (chain->bref.check.xxhash64.value ==
4269 XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED));
4270 hammer2_check_xxhash64 += chain->bytes;
4272 case HAMMER2_CHECK_SHA192:
4274 SHA256_CTX hash_ctx;
4276 uint8_t digest[SHA256_DIGEST_LENGTH];
4277 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4280 SHA256_Init(&hash_ctx);
4281 SHA256_Update(&hash_ctx, bdata, chain->bytes);
4282 SHA256_Final(u.digest, &hash_ctx);
4283 u.digest64[2] ^= u.digest64[3];
4285 chain->bref.check.sha192.data,
4286 sizeof(chain->bref.check.sha192.data)) == 0) {
4293 case HAMMER2_CHECK_FREEMAP:
4294 r = (chain->bref.check.freemap.icrc32 ==
4295 hammer2_icrc32(bdata, chain->bytes));
4297 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4298 chain->bref.check.freemap.icrc32,
4299 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4301 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4302 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4307 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4308 chain->bref.methods);
4316 * The caller presents a shared-locked (parent, chain) where the chain
4317 * is of type HAMMER2_OBJTYPE_HARDLINK. The caller must hold the ip
4318 * structure representing the inode locked to prevent
4319 * consolidation/deconsolidation races.
4321 * The flags passed in are LOOKUP flags, not RESOLVE flags. Only
4322 * HAMMER2_LOOKUP_SHARED is supported.
4324 * We locate the hardlink in the current or a common parent directory.
4326 * If we are unable to locate the hardlink, EIO is returned and
4327 * (*chainp) is unlocked and dropped.
4330 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4331 hammer2_chain_t **parentp,
4332 hammer2_chain_t **chainp,
4335 hammer2_chain_t *parent;
4336 hammer2_chain_t *rchain;
4337 hammer2_key_t key_dummy;
4339 int cache_index = -1;
4342 resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
4343 HAMMER2_RESOLVE_SHARED : 0;
4346 * Obtain the key for the hardlink from *chainp.
4349 lhc = rchain->data->ipdata.meta.inum;
4350 hammer2_chain_unlock(rchain);
4351 hammer2_chain_drop(rchain);
4357 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4359 &cache_index, flags);
4364 * Iterate parents, handle parent rename races by retrying
4370 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4375 if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4378 if (parent->parent == NULL)
4380 parent = parent->parent;
4381 hammer2_chain_ref(parent);
4382 hammer2_chain_unlock(*parentp);
4383 hammer2_chain_lock(parent,
4384 HAMMER2_RESOLVE_ALWAYS |
4386 if ((*parentp)->parent == parent) {
4387 hammer2_chain_drop(*parentp);
4391 hammer2_chain_unlock(parent);
4392 hammer2_chain_drop(parent);
4393 hammer2_chain_lock(*parentp,
4394 HAMMER2_RESOLVE_ALWAYS |
4403 return (rchain ? 0 : EINVAL);
4407 * Used by the bulkscan code to snapshot the synchronized storage for
4408 * a volume, allowing it to be scanned concurrently against normal
4412 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4414 hammer2_chain_t *copy;
4416 copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4417 switch(chain->bref.type) {
4418 case HAMMER2_BREF_TYPE_VOLUME:
4419 copy->data = kmalloc(sizeof(copy->data->voldata),
4422 hammer2_spin_ex(&chain->core.spin);
4423 copy->data->voldata = chain->data->voldata;
4424 hammer2_spin_unex(&chain->core.spin);
4426 case HAMMER2_BREF_TYPE_FREEMAP:
4427 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4430 hammer2_spin_ex(&chain->core.spin);
4431 copy->data->blkset = chain->data->blkset;
4432 hammer2_spin_unex(&chain->core.spin);
4441 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4443 switch(copy->bref.type) {
4444 case HAMMER2_BREF_TYPE_VOLUME:
4445 case HAMMER2_BREF_TYPE_FREEMAP:
4446 KKASSERT(copy->data);
4447 kfree(copy->data, copy->hmp->mchain);
4449 atomic_add_long(&hammer2_chain_allocs, -1);
4454 hammer2_chain_drop(copy);
4458 * Create a snapshot of the specified {parent, ochain} with the specified
4459 * label. The originating hammer2_inode must be exclusively locked for
4462 * The ioctl code has already synced the filesystem.
4465 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4469 const hammer2_inode_data_t *ripdata;
4470 hammer2_inode_data_t *wipdata;
4471 hammer2_chain_t *nchain;
4472 hammer2_inode_t *nip;
4481 kprintf("snapshot %s\n", pmp->name);
4483 name_len = strlen(pmp->name);
4484 lhc = hammer2_dirhash(pmp->name, name_len);
4489 ripdata = &chain->data->ipdata;
4491 opfs_clid = ripdata->meta.pfs_clid;
4496 * Create the snapshot directory under the super-root
4498 * Set PFS type, generate a unique filesystem id, and generate
4499 * a cluster id. Use the same clid when snapshotting a PFS root,
4500 * which theoretically allows the snapshot to be used as part of
4501 * the same cluster (perhaps as a cache).
4503 * Copy the (flushed) blockref array. Theoretically we could use
4504 * chain_duplicate() but it becomes difficult to disentangle
4505 * the shared core so for now just brute-force it.
4510 nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4511 pmp->name, name_len, 0,
4513 HAMMER2_INSERT_PFSROOT, &error);
4516 hammer2_inode_modify(nip);
4517 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4518 hammer2_chain_modify(nchain, mtid, 0, 0);
4519 wipdata = &nchain->data->ipdata;
4521 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4522 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4523 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4524 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4527 * Give the snapshot its own private cluster id. As a
4528 * snapshot no further synchronization with the original
4529 * cluster will be done.
4532 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4533 nip->meta.pfs_clid = opfs_clid;
4535 kern_uuidgen(&nip->meta.pfs_clid, 1);
4537 kern_uuidgen(&nip->meta.pfs_clid, 1);
4538 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4540 /* XXX hack blockset copy */
4541 /* XXX doesn't work with real cluster */
4542 wipdata->meta = nip->meta;
4543 wipdata->u.blockset = ripdata->u.blockset;
4544 hammer2_flush(nchain, 1);
4545 hammer2_chain_unlock(nchain);
4546 hammer2_chain_drop(nchain);
4547 hammer2_inode_unlock(nip);