2 * Copyright (c) 2011-2014 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_trans_t *trans, hammer2_chain_t *parent,
71 hammer2_key_t key, int keybits, int for_type, int *errorp);
72 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
73 static hammer2_chain_t *hammer2_combined_find(
74 hammer2_chain_t *parent,
75 hammer2_blockref_t *base, int count,
76 int *cache_indexp, hammer2_key_t *key_nextp,
77 hammer2_key_t key_beg, hammer2_key_t key_end,
78 hammer2_blockref_t **bresp);
81 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
82 * overlap in the RB trees. Deleted chains are moved from rbtree to either
85 * Chains in delete-duplicate sequences can always iterate through core_entry
86 * to locate the live version of the chain.
88 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
91 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
99 * Compare chains. Overlaps are not supposed to happen and catch
100 * any software issues early we count overlaps as a match.
102 c1_beg = chain1->bref.key;
103 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
104 c2_beg = chain2->bref.key;
105 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
107 if (c1_end < c2_beg) /* fully to the left */
109 if (c1_beg > c2_end) /* fully to the right */
111 return(0); /* overlap (must not cross edge boundary) */
116 hammer2_isclusterable(hammer2_chain_t *chain)
118 if (hammer2_cluster_enable) {
119 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
120 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
121 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
129 * Make a chain visible to the flusher. The flusher needs to be able to
130 * do flushes of a subdirectory chains or single files so it does a top-down
131 * recursion using the ONFLUSH flag for the recursion. It locates MODIFIED
132 * or UPDATE chains and flushes back up the chain to the root.
135 hammer2_chain_setflush(hammer2_trans_t *trans, hammer2_chain_t *chain)
137 hammer2_chain_t *parent;
139 if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
140 hammer2_spin_sh(&chain->core.spin);
141 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
142 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
143 if ((parent = chain->parent) == NULL)
145 hammer2_spin_sh(&parent->core.spin);
146 hammer2_spin_unsh(&chain->core.spin);
149 hammer2_spin_unsh(&chain->core.spin);
154 * Allocate a new disconnected chain element representing the specified
155 * bref. chain->refs is set to 1 and the passed bref is copied to
156 * chain->bref. chain->bytes is derived from the bref.
158 * chain->pmp inherits pmp unless the chain is an inode (other than the
161 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
164 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
165 hammer2_trans_t *trans, hammer2_blockref_t *bref)
167 hammer2_chain_t *chain;
168 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
171 * Construct the appropriate system structure.
174 case HAMMER2_BREF_TYPE_INODE:
175 case HAMMER2_BREF_TYPE_INDIRECT:
176 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
177 case HAMMER2_BREF_TYPE_DATA:
178 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
180 * Chain's are really only associated with the hmp but we
181 * maintain a pmp association for per-mount memory tracking
182 * purposes. The pmp can be NULL.
184 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
186 case HAMMER2_BREF_TYPE_VOLUME:
187 case HAMMER2_BREF_TYPE_FREEMAP:
189 panic("hammer2_chain_alloc volume type illegal for op");
192 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
197 * Initialize the new chain structure. pmp must be set to NULL for
198 * chains belonging to the super-root topology of a device mount.
200 if (pmp == hmp->spmp)
206 chain->bytes = bytes;
208 chain->flags = HAMMER2_CHAIN_ALLOCATED;
211 * Set the PFS boundary flag if this chain represents a PFS root.
213 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
214 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
215 hammer2_chain_core_init(chain);
221 * Initialize a chain's core structure. This structure used to be allocated
222 * but is now embedded.
224 * The core is not locked. No additional refs on the chain are made.
225 * (trans) must not be NULL if (core) is not NULL.
228 hammer2_chain_core_init(hammer2_chain_t *chain)
230 hammer2_chain_core_t *core = &chain->core;
233 * Fresh core under nchain (no multi-homing of ochain's
236 RB_INIT(&core->rbtree); /* live chains */
237 hammer2_mtx_init(&core->lock, "h2chain");
241 * Add a reference to a chain element, preventing its destruction.
243 * (can be called with spinlock held)
246 hammer2_chain_ref(hammer2_chain_t *chain)
248 atomic_add_int(&chain->refs, 1);
252 * Insert the chain in the core rbtree.
254 * Normal insertions are placed in the live rbtree. Insertion of a deleted
255 * chain is a special case used by the flush code that is placed on the
256 * unstaged deleted list to avoid confusing the live view.
258 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
259 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
260 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
264 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
265 int flags, int generation)
267 hammer2_chain_t *xchain;
270 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
271 hammer2_spin_ex(&parent->core.spin);
274 * Interlocked by spinlock, check for race
276 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
277 parent->core.generation != generation) {
285 xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
286 KASSERT(xchain == NULL,
287 ("hammer2_chain_insert: collision %p %p", chain, xchain));
288 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
289 chain->parent = parent;
290 ++parent->core.chain_count;
291 ++parent->core.generation; /* XXX incs for _get() too, XXX */
294 * We have to keep track of the effective live-view blockref count
295 * so the create code knows when to push an indirect block.
297 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
298 atomic_add_int(&parent->core.live_count, 1);
300 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
301 hammer2_spin_unex(&parent->core.spin);
306 * Drop the caller's reference to the chain. When the ref count drops to
307 * zero this function will try to disassociate the chain from its parent and
308 * deallocate it, then recursely drop the parent using the implied ref
309 * from the chain's chain->parent.
311 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
314 hammer2_chain_drop(hammer2_chain_t *chain)
319 if (hammer2_debug & 0x200000)
322 if (chain->flags & HAMMER2_CHAIN_UPDATE)
324 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
326 KKASSERT(chain->refs > need);
334 chain = hammer2_chain_lastdrop(chain);
336 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
338 /* retry the same chain */
344 * Safe handling of the 1->0 transition on chain. Returns a chain for
345 * recursive drop or NULL, possibly returning the same chain if the atomic
348 * Whem two chains need to be recursively dropped we use the chain
349 * we would otherwise free to placehold the additional chain. It's a bit
350 * convoluted but we can't just recurse without potentially blowing out
353 * The chain cannot be freed if it has any children.
355 * The core spinlock is allowed nest child-to-parent (not parent-to-child).
359 hammer2_chain_lastdrop(hammer2_chain_t *chain)
363 hammer2_chain_t *parent;
364 hammer2_chain_t *rdrop;
367 * Spinlock the core and check to see if it is empty. If it is
368 * not empty we leave chain intact with refs == 0. The elements
369 * in core->rbtree are associated with other chains contemporary
370 * with ours but not with our chain directly.
372 hammer2_spin_ex(&chain->core.spin);
375 * We can't free non-stale chains with children until we are
376 * able to free the children because there might be a flush
377 * dependency. Flushes of stale children (which should also
378 * have their deleted flag set) short-cut recursive flush
379 * dependencies and can be freed here. Any flushes which run
380 * through stale children due to the flush synchronization
381 * point should have a FLUSH_* bit set in the chain and not
382 * reach lastdrop at this time.
384 * NOTE: We return (chain) on failure to retry.
386 if (chain->core.chain_count) {
387 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
388 hammer2_spin_unex(&chain->core.spin);
389 chain = NULL; /* success */
391 hammer2_spin_unex(&chain->core.spin);
395 /* no chains left under us */
398 * chain->core has no children left so no accessors can get to our
399 * chain from there. Now we have to lock the parent core to interlock
400 * remaining possible accessors that might bump chain's refs before
401 * we can safely drop chain's refs with intent to free the chain.
404 pmp = chain->pmp; /* can be NULL */
408 * Spinlock the parent and try to drop the last ref on chain.
409 * On success remove chain from its parent, otherwise return NULL.
411 * (normal core locks are top-down recursive but we define core
412 * spinlocks as bottom-up recursive, so this is safe).
414 if ((parent = chain->parent) != NULL) {
415 hammer2_spin_ex(&parent->core.spin);
416 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
417 /* 1->0 transition failed */
418 hammer2_spin_unex(&parent->core.spin);
419 hammer2_spin_unex(&chain->core.spin);
420 return(chain); /* retry */
424 * 1->0 transition successful, remove chain from its
427 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
428 RB_REMOVE(hammer2_chain_tree,
429 &parent->core.rbtree, chain);
430 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
431 --parent->core.chain_count;
432 chain->parent = NULL;
436 * If our chain was the last chain in the parent's core the
437 * core is now empty and its parent might have to be
438 * re-dropped if it has 0 refs.
440 if (parent->core.chain_count == 0) {
442 if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
446 hammer2_spin_unex(&parent->core.spin);
447 parent = NULL; /* safety */
451 * Successful 1->0 transition and the chain can be destroyed now.
453 * We still have the core spinlock, and core's chain_count is 0.
454 * Any parent spinlock is gone.
456 hammer2_spin_unex(&chain->core.spin);
457 KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
458 chain->core.chain_count == 0);
461 * All spin locks are gone, finish freeing stuff.
463 KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
464 HAMMER2_CHAIN_MODIFIED)) == 0);
465 hammer2_chain_drop_data(chain, 1);
467 KKASSERT(chain->dio == NULL);
470 * Once chain resources are gone we can use the now dead chain
471 * structure to placehold what might otherwise require a recursive
472 * drop, because we have potentially two things to drop and can only
473 * return one directly.
475 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
476 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
478 kfree(chain, hmp->mchain);
482 * Possible chaining loop when parent re-drop needed.
488 * On either last lock release or last drop
491 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
493 /*hammer2_dev_t *hmp = chain->hmp;*/
495 switch(chain->bref.type) {
496 case HAMMER2_BREF_TYPE_VOLUME:
497 case HAMMER2_BREF_TYPE_FREEMAP:
502 KKASSERT(chain->data == NULL);
508 * Lock a referenced chain element, acquiring its data with I/O if necessary,
509 * and specify how you would like the data to be resolved.
511 * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
513 * The lock is allowed to recurse, multiple locking ops will aggregate
514 * the requested resolve types. Once data is assigned it will not be
515 * removed until the last unlock.
517 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
518 * (typically used to avoid device/logical buffer
521 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
522 * the INITIAL-create state (indirect blocks only).
524 * Do not resolve data elements for DATA chains.
525 * (typically used to avoid device/logical buffer
528 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
530 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
531 * it will be locked exclusive.
533 * NOTE: Embedded elements (volume header, inodes) are always resolved
536 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
537 * element will instantiate and zero its buffer, and flush it on
540 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
541 * so as not to instantiate a device buffer, which could alias against
542 * a logical file buffer. However, if ALWAYS is specified the
543 * device buffer will be instantiated anyway.
545 * WARNING! If data must be fetched a shared lock will temporarily be
546 * upgraded to exclusive. However, a deadlock can occur if
547 * the caller owns more than one shared lock.
550 hammer2_chain_lock(hammer2_chain_t *chain, int how)
553 hammer2_blockref_t *bref;
554 hammer2_mtx_state_t ostate;
559 * Ref and lock the element. Recursive locks are allowed.
561 KKASSERT(chain->refs > 0);
562 atomic_add_int(&chain->lockcnt, 1);
565 KKASSERT(hmp != NULL);
568 * Get the appropriate lock.
570 if (how & HAMMER2_RESOLVE_SHARED)
571 hammer2_mtx_sh(&chain->core.lock);
573 hammer2_mtx_ex(&chain->core.lock);
576 * If we already have a valid data pointer no further action is
583 * Do we have to resolve the data?
585 switch(how & HAMMER2_RESOLVE_MASK) {
586 case HAMMER2_RESOLVE_NEVER:
588 case HAMMER2_RESOLVE_MAYBE:
589 if (chain->flags & HAMMER2_CHAIN_INITIAL)
591 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
594 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
596 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
600 case HAMMER2_RESOLVE_ALWAYS:
605 * Upgrade to an exclusive lock so we can safely manipulate the
606 * buffer cache. If another thread got to it before us we
609 ostate = hammer2_mtx_upgrade(&chain->core.lock);
611 hammer2_mtx_downgrade(&chain->core.lock, ostate);
616 * We must resolve to a device buffer, either by issuing I/O or
617 * by creating a zero-fill element. We do not mark the buffer
618 * dirty when creating a zero-fill element (the hammer2_chain_modify()
619 * API must still be used to do that).
621 * The device buffer is variable-sized in powers of 2 down
622 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
623 * chunk always contains buffers of the same size. (XXX)
625 * The minimum physical IO size may be larger than the variable
631 * The getblk() optimization can only be used on newly created
632 * elements if the physical block size matches the request.
634 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
635 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
638 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
640 hammer2_adjreadcounter(&chain->bref, chain->bytes);
643 chain->error = HAMMER2_ERROR_IO;
644 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
645 (intmax_t)bref->data_off, error);
646 hammer2_io_bqrelse(&chain->dio);
647 hammer2_mtx_downgrade(&chain->core.lock, ostate);
653 * NOTE: A locked chain's data cannot be modified without first
654 * calling hammer2_chain_modify().
658 * Clear INITIAL. In this case we used io_new() and the buffer has
659 * been zero'd and marked dirty.
661 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
662 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
663 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
664 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
665 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
667 * check data not currently synchronized due to
668 * modification. XXX assumes data stays in the buffer
669 * cache, which might not be true (need biodep on flush
670 * to calculate crc? or simple crc?).
673 if (hammer2_chain_testcheck(chain, bdata) == 0) {
674 kprintf("chain %016jx.%02x meth=%02x "
675 "CHECK FAIL %08x (flags=%08x)\n",
676 chain->bref.data_off,
679 hammer2_icrc32(bdata, chain->bytes),
681 chain->error = HAMMER2_ERROR_CHECK;
686 * Setup the data pointer, either pointing it to an embedded data
687 * structure and copying the data from the buffer, or pointing it
690 * The buffer is not retained when copying to an embedded data
691 * structure in order to avoid potential deadlocks or recursions
692 * on the same physical buffer.
694 switch (bref->type) {
695 case HAMMER2_BREF_TYPE_VOLUME:
696 case HAMMER2_BREF_TYPE_FREEMAP:
698 * Copy data from bp to embedded buffer
700 panic("hammer2_chain_lock: called on unresolved volume header");
702 case HAMMER2_BREF_TYPE_INODE:
703 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
704 case HAMMER2_BREF_TYPE_INDIRECT:
705 case HAMMER2_BREF_TYPE_DATA:
706 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
709 * Point data at the device buffer and leave dio intact.
711 chain->data = (void *)bdata;
714 hammer2_mtx_downgrade(&chain->core.lock, ostate);
718 * Unlock and deref a chain element.
720 * On the last lock release any non-embedded data (chain->dio) will be
724 hammer2_chain_unlock(hammer2_chain_t *chain)
726 hammer2_mtx_state_t ostate;
731 * If multiple locks are present (or being attempted) on this
732 * particular chain we can just unlock, drop refs, and return.
734 * Otherwise fall-through on the 1->0 transition.
737 lockcnt = chain->lockcnt;
738 KKASSERT(lockcnt > 0);
741 if (atomic_cmpset_int(&chain->lockcnt,
742 lockcnt, lockcnt - 1)) {
743 hammer2_mtx_unlock(&chain->core.lock);
747 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
754 * On the 1->0 transition we upgrade the core lock (if necessary)
755 * to exclusive for terminal processing. If after upgrading we find
756 * that lockcnt is non-zero, another thread is racing us and will
757 * handle the unload for us later on, so just cleanup and return
758 * leaving the data/io intact
760 * Otherwise if lockcnt is still 0 it is possible for it to become
761 * non-zero and race, but since we hold the core->lock exclusively
762 * all that will happen is that the chain will be reloaded after we
765 ostate = hammer2_mtx_upgrade(&chain->core.lock);
766 if (chain->lockcnt) {
767 hammer2_mtx_unlock(&chain->core.lock);
772 * Shortcut the case if the data is embedded or not resolved.
774 * Do NOT NULL out chain->data (e.g. inode data), it might be
777 if (chain->dio == NULL) {
778 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
779 hammer2_chain_drop_data(chain, 0);
780 hammer2_mtx_unlock(&chain->core.lock);
787 if (hammer2_io_isdirty(chain->dio) == 0) {
789 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
790 switch(chain->bref.type) {
791 case HAMMER2_BREF_TYPE_DATA:
792 counterp = &hammer2_ioa_file_write;
794 case HAMMER2_BREF_TYPE_INODE:
795 counterp = &hammer2_ioa_meta_write;
797 case HAMMER2_BREF_TYPE_INDIRECT:
798 counterp = &hammer2_ioa_indr_write;
800 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
801 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
802 counterp = &hammer2_ioa_fmap_write;
805 counterp = &hammer2_ioa_volu_write;
808 *counterp += chain->bytes;
810 switch(chain->bref.type) {
811 case HAMMER2_BREF_TYPE_DATA:
812 counterp = &hammer2_iod_file_write;
814 case HAMMER2_BREF_TYPE_INODE:
815 counterp = &hammer2_iod_meta_write;
817 case HAMMER2_BREF_TYPE_INDIRECT:
818 counterp = &hammer2_iod_indr_write;
820 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
821 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
822 counterp = &hammer2_iod_fmap_write;
825 counterp = &hammer2_iod_volu_write;
828 *counterp += chain->bytes;
834 * If a device buffer was used for data be sure to destroy the
835 * buffer when we are done to avoid aliases (XXX what about the
836 * underlying VM pages?).
838 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
841 * NOTE: The isdirty check tracks whether we have to bdwrite() the
842 * buffer or not. The buffer might already be dirty. The
843 * flag is re-set when chain_modify() is called, even if
844 * MODIFIED is already set, allowing the OS to retire the
845 * buffer independent of a hammer2 flush.
848 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
849 hammer2_io_isdirty(chain->dio)) {
850 hammer2_io_bawrite(&chain->dio);
852 hammer2_io_bqrelse(&chain->dio);
854 hammer2_mtx_unlock(&chain->core.lock);
858 * This counts the number of live blockrefs in a block array and
859 * also calculates the point at which all remaining blockrefs are empty.
860 * This routine can only be called on a live chain (DUPLICATED flag not set).
862 * NOTE: Flag is not set until after the count is complete, allowing
863 * callers to test the flag without holding the spinlock.
865 * NOTE: If base is NULL the related chain is still in the INITIAL
866 * state and there are no blockrefs to count.
868 * NOTE: live_count may already have some counts accumulated due to
869 * creation and deletion and could even be initially negative.
872 hammer2_chain_countbrefs(hammer2_chain_t *chain,
873 hammer2_blockref_t *base, int count)
875 hammer2_spin_ex(&chain->core.spin);
876 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
878 while (--count >= 0) {
879 if (base[count].type)
882 chain->core.live_zero = count + 1;
884 if (base[count].type)
885 atomic_add_int(&chain->core.live_count,
890 chain->core.live_zero = 0;
892 /* else do not modify live_count */
893 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
895 hammer2_spin_unex(&chain->core.spin);
899 * Resize the chain's physical storage allocation in-place. This function does
900 * not adjust the data pointer and must be followed by (typically) a
901 * hammer2_chain_modify() call to copy any old data over and adjust the
904 * Chains can be resized smaller without reallocating the storage. Resizing
905 * larger will reallocate the storage. Excess or prior storage is reclaimed
906 * asynchronously at a later time.
908 * Must be passed an exclusively locked parent and chain.
910 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
911 * to avoid instantiating a device buffer that conflicts with the vnode data
912 * buffer. However, because H2 can compress or encrypt data, the chain may
913 * have a dio assigned to it in those situations, and they do not conflict.
915 * XXX return error if cannot resize.
918 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
919 hammer2_chain_t *parent, hammer2_chain_t *chain,
920 int nradix, int flags)
929 * Only data and indirect blocks can be resized for now.
930 * (The volu root, inodes, and freemap elements use a fixed size).
932 KKASSERT(chain != &hmp->vchain);
933 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
934 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
937 * Nothing to do if the element is already the proper size
939 obytes = chain->bytes;
940 nbytes = 1U << nradix;
941 if (obytes == nbytes)
943 chain->data_count += (ssize_t)(nbytes - obytes);
946 * Make sure the old data is instantiated so we can copy it. If this
947 * is a data block, the device data may be superfluous since the data
948 * might be in a logical block, but compressed or encrypted data is
951 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
953 hammer2_chain_modify(trans, chain, 0);
956 * Relocate the block, even if making it smaller (because different
957 * block sizes may be in different regions).
959 * (data blocks only, we aren't copying the storage here).
961 hammer2_freemap_alloc(trans, chain, nbytes);
962 chain->bytes = nbytes;
963 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
966 * We don't want the followup chain_modify() to try to copy data
967 * from the old (wrong-sized) buffer. It won't know how much to
968 * copy. This case should only occur during writes when the
969 * originator already has the data to write in-hand.
972 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
973 hammer2_io_brelse(&chain->dio);
979 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
981 hammer2_blockref_t obref;
991 KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
994 * Data is not optional for freemap chains (we must always be sure
995 * to copy the data on COW storage allocations).
997 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
998 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
999 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1000 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1004 * Data must be resolved if already assigned unless explicitly
1005 * flagged otherwise.
1007 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1008 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1009 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1010 hammer2_chain_unlock(chain);
1014 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1015 * that the chain has been modified. Set UPDATE to ensure that
1016 * the blockref is updated in the parent.
1018 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1019 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1020 hammer2_chain_ref(chain);
1021 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1026 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1027 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1028 hammer2_chain_ref(chain);
1032 * The modification or re-modification requires an allocation and
1035 * We normally always allocate new storage here. If storage exists
1036 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1038 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1039 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1040 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1042 hammer2_freemap_alloc(trans, chain, chain->bytes);
1043 /* XXX failed allocation */
1048 * Update mirror_tid and modify_tid.
1050 * NOTE: modify_tid updates can be suppressed with a flag. This is
1051 * used by the slave synchronization code to delay updating
1052 * modify_tid in higher-level objects until lower-level objects
1053 * have been synchronized.
1055 * NOTE: chain->pmp could be the device spmp.
1057 chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1058 if (chain->pmp && (trans->flags & HAMMER2_TRANS_KEEPMODIFY) == 0)
1059 chain->bref.modify_tid = chain->pmp->modify_tid + 1;
1062 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1063 * requires updating as well as to tell the delete code that the
1064 * chain's blockref might not exactly match (in terms of physical size
1065 * or block offset) the one in the parent's blocktable. The base key
1066 * of course will still match.
1068 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1069 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1072 * Short-cut data blocks which the caller does not need an actual
1073 * data reference to (aka OPTDATA), as long as the chain does not
1074 * already have a data pointer to the data. This generally means
1075 * that the modifications are being done via the logical buffer cache.
1076 * The INITIAL flag relates only to the device data buffer and thus
1077 * remains unchange in this situation.
1079 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1080 (flags & HAMMER2_MODIFY_OPTDATA) &&
1081 chain->data == NULL) {
1086 * Clearing the INITIAL flag (for indirect blocks) indicates that
1087 * we've processed the uninitialized storage allocation.
1089 * If this flag is already clear we are likely in a copy-on-write
1090 * situation but we have to be sure NOT to bzero the storage if
1091 * no data is present.
1093 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1094 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1101 * Instantiate data buffer and possibly execute COW operation
1103 switch(chain->bref.type) {
1104 case HAMMER2_BREF_TYPE_VOLUME:
1105 case HAMMER2_BREF_TYPE_FREEMAP:
1107 * The data is embedded, no copy-on-write operation is
1110 KKASSERT(chain->dio == NULL);
1112 case HAMMER2_BREF_TYPE_INODE:
1113 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1114 case HAMMER2_BREF_TYPE_DATA:
1115 case HAMMER2_BREF_TYPE_INDIRECT:
1116 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1118 * Perform the copy-on-write operation
1120 * zero-fill or copy-on-write depending on whether
1121 * chain->data exists or not and set the dirty state for
1122 * the new buffer. hammer2_io_new() will handle the
1125 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1128 error = hammer2_io_new(hmp, chain->bref.data_off,
1129 chain->bytes, &dio);
1131 error = hammer2_io_bread(hmp, chain->bref.data_off,
1132 chain->bytes, &dio);
1134 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1137 * If an I/O error occurs make sure callers cannot accidently
1138 * modify the old buffer's contents and corrupt the filesystem.
1141 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1143 chain->error = HAMMER2_ERROR_IO;
1144 hammer2_io_brelse(&dio);
1145 hammer2_io_brelse(&chain->dio);
1150 bdata = hammer2_io_data(dio, chain->bref.data_off);
1153 KKASSERT(chain->dio != NULL);
1154 if (chain->data != (void *)bdata) {
1155 bcopy(chain->data, bdata, chain->bytes);
1157 } else if (wasinitial == 0) {
1159 * We have a problem. We were asked to COW but
1160 * we don't have any data to COW with!
1162 panic("hammer2_chain_modify: having a COW %p\n",
1167 * Retire the old buffer, replace with the new. Dirty or
1168 * redirty the new buffer.
1170 * WARNING! The system buffer cache may have already flushed
1171 * the buffer, so we must be sure to [re]dirty it
1172 * for further modification.
1175 hammer2_io_brelse(&chain->dio);
1176 chain->data = (void *)bdata;
1178 hammer2_io_setdirty(dio); /* modified by bcopy above */
1181 panic("hammer2_chain_modify: illegal non-embedded type %d",
1188 * setflush on parent indicating that the parent must recurse down
1189 * to us. Do not call on chain itself which might already have it
1193 hammer2_chain_setflush(trans, chain->parent);
1197 * Volume header data locks
1200 hammer2_voldata_lock(hammer2_dev_t *hmp)
1202 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1206 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1208 lockmgr(&hmp->vollk, LK_RELEASE);
1212 hammer2_voldata_modify(hammer2_dev_t *hmp)
1214 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1215 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1216 hammer2_chain_ref(&hmp->vchain);
1217 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1222 * This function returns the chain at the nearest key within the specified
1223 * range. The returned chain will be referenced but not locked.
1225 * This function will recurse through chain->rbtree as necessary and will
1226 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1227 * the iteration value is less than the current value of *key_nextp.
1229 * The caller should use (*key_nextp) to calculate the actual range of
1230 * the returned element, which will be (key_beg to *key_nextp - 1), because
1231 * there might be another element which is superior to the returned element
1234 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1235 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1236 * it will wind up being (key_end + 1).
1238 * WARNING! Must be called with child's spinlock held. Spinlock remains
1239 * held through the operation.
1241 struct hammer2_chain_find_info {
1242 hammer2_chain_t *best;
1243 hammer2_key_t key_beg;
1244 hammer2_key_t key_end;
1245 hammer2_key_t key_next;
1248 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1249 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1253 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1254 hammer2_key_t key_beg, hammer2_key_t key_end)
1256 struct hammer2_chain_find_info info;
1259 info.key_beg = key_beg;
1260 info.key_end = key_end;
1261 info.key_next = *key_nextp;
1263 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1264 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1266 *key_nextp = info.key_next;
1268 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1269 parent, key_beg, key_end, *key_nextp);
1277 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1279 struct hammer2_chain_find_info *info = data;
1280 hammer2_key_t child_beg;
1281 hammer2_key_t child_end;
1283 child_beg = child->bref.key;
1284 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1286 if (child_end < info->key_beg)
1288 if (child_beg > info->key_end)
1295 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1297 struct hammer2_chain_find_info *info = data;
1298 hammer2_chain_t *best;
1299 hammer2_key_t child_end;
1302 * WARNING! Do not discard DUPLICATED chains, it is possible that
1303 * we are catching an insertion half-way done. If a
1304 * duplicated chain turns out to be the best choice the
1305 * caller will re-check its flags after locking it.
1307 * WARNING! Layerq is scanned forwards, exact matches should keep
1308 * the existing info->best.
1310 if ((best = info->best) == NULL) {
1312 * No previous best. Assign best
1315 } else if (best->bref.key <= info->key_beg &&
1316 child->bref.key <= info->key_beg) {
1321 /*info->best = child;*/
1322 } else if (child->bref.key < best->bref.key) {
1324 * Child has a nearer key and best is not flush with key_beg.
1325 * Set best to child. Truncate key_next to the old best key.
1328 if (info->key_next > best->bref.key || info->key_next == 0)
1329 info->key_next = best->bref.key;
1330 } else if (child->bref.key == best->bref.key) {
1332 * If our current best is flush with the child then this
1333 * is an illegal overlap.
1335 * key_next will automatically be limited to the smaller of
1336 * the two end-points.
1342 * Keep the current best but truncate key_next to the child's
1345 * key_next will also automatically be limited to the smaller
1346 * of the two end-points (probably not necessary for this case
1347 * but we do it anyway).
1349 if (info->key_next > child->bref.key || info->key_next == 0)
1350 info->key_next = child->bref.key;
1354 * Always truncate key_next based on child's end-of-range.
1356 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1357 if (child_end && (info->key_next > child_end || info->key_next == 0))
1358 info->key_next = child_end;
1364 * Retrieve the specified chain from a media blockref, creating the
1365 * in-memory chain structure which reflects it.
1367 * To handle insertion races pass the INSERT_RACE flag along with the
1368 * generation number of the core. NULL will be returned if the generation
1369 * number changes before we have a chance to insert the chain. Insert
1370 * races can occur because the parent might be held shared.
1372 * Caller must hold the parent locked shared or exclusive since we may
1373 * need the parent's bref array to find our block.
1375 * WARNING! chain->pmp is always set to NULL for any chain representing
1376 * part of the super-root topology.
1379 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1380 hammer2_blockref_t *bref)
1382 hammer2_dev_t *hmp = parent->hmp;
1383 hammer2_chain_t *chain;
1387 * Allocate a chain structure representing the existing media
1388 * entry. Resulting chain has one ref and is not locked.
1390 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1391 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1393 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1394 /* ref'd chain returned */
1397 * Flag that the chain is in the parent's blockmap so delete/flush
1398 * knows what to do with it.
1400 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1403 * Link the chain into its parent. A spinlock is required to safely
1404 * access the RBTREE, and it is possible to collide with another
1405 * hammer2_chain_get() operation because the caller might only hold
1406 * a shared lock on the parent.
1408 KKASSERT(parent->refs > 0);
1409 error = hammer2_chain_insert(parent, chain,
1410 HAMMER2_CHAIN_INSERT_SPIN |
1411 HAMMER2_CHAIN_INSERT_RACE,
1414 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1415 kprintf("chain %p get race\n", chain);
1416 hammer2_chain_drop(chain);
1419 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1423 * Return our new chain referenced but not locked, or NULL if
1430 * Lookup initialization/completion API
1433 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1435 hammer2_chain_ref(parent);
1436 if (flags & HAMMER2_LOOKUP_SHARED) {
1437 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1438 HAMMER2_RESOLVE_SHARED);
1440 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1446 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1449 hammer2_chain_unlock(parent);
1450 hammer2_chain_drop(parent);
1456 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1458 hammer2_chain_t *oparent;
1459 hammer2_chain_t *nparent;
1462 * Be careful of order, oparent must be unlocked before nparent
1463 * is locked below to avoid a deadlock.
1466 hammer2_spin_ex(&oparent->core.spin);
1467 nparent = oparent->parent;
1468 hammer2_chain_ref(nparent);
1469 hammer2_spin_unex(&oparent->core.spin);
1471 hammer2_chain_unlock(oparent);
1472 hammer2_chain_drop(oparent);
1476 hammer2_chain_lock(nparent, how);
1483 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1484 * (*parentp) typically points to an inode but can also point to a related
1485 * indirect block and this function will recurse upwards and find the inode
1488 * (*parentp) must be exclusively locked and referenced and can be an inode
1489 * or an existing indirect block within the inode.
1491 * On return (*parentp) will be modified to point at the deepest parent chain
1492 * element encountered during the search, as a helper for an insertion or
1493 * deletion. The new (*parentp) will be locked and referenced and the old
1494 * will be unlocked and dereferenced (no change if they are both the same).
1496 * The matching chain will be returned exclusively locked. If NOLOCK is
1497 * requested the chain will be returned only referenced. Note that the
1498 * parent chain must always be locked shared or exclusive, matching the
1499 * HAMMER2_LOOKUP_SHARED flag. We can conceivably lock it SHARED temporarily
1500 * when NOLOCK is specified but that complicates matters if *parentp must
1501 * inherit the chain.
1503 * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1504 * data pointer or can otherwise be in flux.
1506 * NULL is returned if no match was found, but (*parentp) will still
1507 * potentially be adjusted.
1509 * If a fatal error occurs (typically an I/O error), a dummy chain is
1510 * returned with chain->error and error-identifying information set. This
1511 * chain will assert if you try to do anything fancy with it.
1513 * XXX Depending on where the error occurs we should allow continued iteration.
1515 * On return (*key_nextp) will point to an iterative value for key_beg.
1516 * (If NULL is returned (*key_nextp) is set to key_end).
1518 * This function will also recurse up the chain if the key is not within the
1519 * current parent's range. (*parentp) can never be set to NULL. An iteration
1520 * can simply allow (*parentp) to float inside the loop.
1522 * NOTE! chain->data is not always resolved. By default it will not be
1523 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1524 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1525 * BREF_TYPE_DATA as the device buffer can alias the logical file
1529 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1530 hammer2_key_t key_beg, hammer2_key_t key_end,
1531 int *cache_indexp, int flags)
1534 hammer2_chain_t *parent;
1535 hammer2_chain_t *chain;
1536 hammer2_blockref_t *base;
1537 hammer2_blockref_t *bref;
1538 hammer2_blockref_t bcopy;
1539 hammer2_key_t scan_beg;
1540 hammer2_key_t scan_end;
1542 int how_always = HAMMER2_RESOLVE_ALWAYS;
1543 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1546 int maxloops = 300000;
1548 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1549 how_maybe = how_always;
1550 how = HAMMER2_RESOLVE_ALWAYS;
1551 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1552 how = HAMMER2_RESOLVE_NEVER;
1554 how = HAMMER2_RESOLVE_MAYBE;
1556 if (flags & HAMMER2_LOOKUP_SHARED) {
1557 how_maybe |= HAMMER2_RESOLVE_SHARED;
1558 how_always |= HAMMER2_RESOLVE_SHARED;
1559 how |= HAMMER2_RESOLVE_SHARED;
1563 * Recurse (*parentp) upward if necessary until the parent completely
1564 * encloses the key range or we hit the inode.
1566 * This function handles races against the flusher doing a delete-
1567 * duplicate above us and re-homes the parent to the duplicate in
1568 * that case, otherwise we'd wind up recursing down a stale chain.
1573 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1574 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1575 scan_beg = parent->bref.key;
1576 scan_end = scan_beg +
1577 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1578 if (key_beg >= scan_beg && key_end <= scan_end)
1580 parent = hammer2_chain_getparent(parentp, how_maybe);
1584 if (--maxloops == 0)
1585 panic("hammer2_chain_lookup: maxloops");
1587 * Locate the blockref array. Currently we do a fully associative
1588 * search through the array.
1590 switch(parent->bref.type) {
1591 case HAMMER2_BREF_TYPE_INODE:
1593 * Special shortcut for embedded data returns the inode
1594 * itself. Callers must detect this condition and access
1595 * the embedded data (the strategy code does this for us).
1597 * This is only applicable to regular files and softlinks.
1599 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1600 hammer2_chain_ref(parent);
1601 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1602 hammer2_chain_lock(parent, how_always);
1603 *key_nextp = key_end + 1;
1606 base = &parent->data->ipdata.u.blockset.blockref[0];
1607 count = HAMMER2_SET_COUNT;
1609 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1610 case HAMMER2_BREF_TYPE_INDIRECT:
1612 * Handle MATCHIND on the parent
1614 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1615 scan_beg = parent->bref.key;
1616 scan_end = scan_beg +
1617 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1618 if (key_beg == scan_beg && key_end == scan_end) {
1620 hammer2_chain_ref(chain);
1621 hammer2_chain_lock(chain, how_maybe);
1622 *key_nextp = scan_end + 1;
1627 * Optimize indirect blocks in the INITIAL state to avoid
1630 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1633 if (parent->data == NULL)
1634 panic("parent->data is NULL");
1635 base = &parent->data->npdata[0];
1637 count = parent->bytes / sizeof(hammer2_blockref_t);
1639 case HAMMER2_BREF_TYPE_VOLUME:
1640 base = &hmp->voldata.sroot_blockset.blockref[0];
1641 count = HAMMER2_SET_COUNT;
1643 case HAMMER2_BREF_TYPE_FREEMAP:
1644 base = &hmp->voldata.freemap_blockset.blockref[0];
1645 count = HAMMER2_SET_COUNT;
1648 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1650 base = NULL; /* safety */
1651 count = 0; /* safety */
1655 * Merged scan to find next candidate.
1657 * hammer2_base_*() functions require the parent->core.live_* fields
1658 * to be synchronized.
1660 * We need to hold the spinlock to access the block array and RB tree
1661 * and to interlock chain creation.
1663 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1664 hammer2_chain_countbrefs(parent, base, count);
1669 hammer2_spin_ex(&parent->core.spin);
1670 chain = hammer2_combined_find(parent, base, count,
1671 cache_indexp, key_nextp,
1674 generation = parent->core.generation;
1677 * Exhausted parent chain, iterate.
1680 hammer2_spin_unex(&parent->core.spin);
1681 if (key_beg == key_end) /* short cut single-key case */
1685 * Stop if we reached the end of the iteration.
1687 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1688 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1693 * Calculate next key, stop if we reached the end of the
1694 * iteration, otherwise go up one level and loop.
1696 key_beg = parent->bref.key +
1697 ((hammer2_key_t)1 << parent->bref.keybits);
1698 if (key_beg == 0 || key_beg > key_end)
1700 parent = hammer2_chain_getparent(parentp, how_maybe);
1705 * Selected from blockref or in-memory chain.
1707 if (chain == NULL) {
1709 hammer2_spin_unex(&parent->core.spin);
1710 chain = hammer2_chain_get(parent, generation,
1712 if (chain == NULL) {
1713 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1714 parent, key_beg, key_end);
1717 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1718 hammer2_chain_drop(chain);
1722 hammer2_chain_ref(chain);
1723 hammer2_spin_unex(&parent->core.spin);
1727 * chain is referenced but not locked. We must lock the chain
1728 * to obtain definitive DUPLICATED/DELETED state
1730 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1731 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1732 hammer2_chain_lock(chain, how_maybe);
1734 hammer2_chain_lock(chain, how);
1738 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1740 * NOTE: Chain's key range is not relevant as there might be
1741 * one-offs within the range that are not deleted.
1743 * NOTE: Lookups can race delete-duplicate because
1744 * delete-duplicate does not lock the parent's core
1745 * (they just use the spinlock on the core). We must
1746 * check for races by comparing the DUPLICATED flag before
1747 * releasing the spinlock with the flag after locking the
1750 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1751 hammer2_chain_unlock(chain);
1752 hammer2_chain_drop(chain);
1753 key_beg = *key_nextp;
1754 if (key_beg == 0 || key_beg > key_end)
1760 * If the chain element is an indirect block it becomes the new
1761 * parent and we loop on it. We must maintain our top-down locks
1762 * to prevent the flusher from interfering (i.e. doing a
1763 * delete-duplicate and leaving us recursing down a deleted chain).
1765 * The parent always has to be locked with at least RESOLVE_MAYBE
1766 * so we can access its data. It might need a fixup if the caller
1767 * passed incompatible flags. Be careful not to cause a deadlock
1768 * as a data-load requires an exclusive lock.
1770 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1771 * range is within the requested key range we return the indirect
1772 * block and do NOT loop. This is usually only used to acquire
1775 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1776 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1777 hammer2_chain_unlock(parent);
1778 hammer2_chain_drop(parent);
1779 *parentp = parent = chain;
1784 * All done, return the chain.
1786 * If the caller does not want a locked chain, replace the lock with
1787 * a ref. Perhaps this can eventually be optimized to not obtain the
1788 * lock in the first place for situations where the data does not
1789 * need to be resolved.
1792 if (flags & HAMMER2_LOOKUP_NOLOCK)
1793 hammer2_chain_unlock(chain);
1800 * After having issued a lookup we can iterate all matching keys.
1802 * If chain is non-NULL we continue the iteration from just after it's index.
1804 * If chain is NULL we assume the parent was exhausted and continue the
1805 * iteration at the next parent.
1807 * If a fatal error occurs (typically an I/O error), a dummy chain is
1808 * returned with chain->error and error-identifying information set. This
1809 * chain will assert if you try to do anything fancy with it.
1811 * XXX Depending on where the error occurs we should allow continued iteration.
1813 * parent must be locked on entry and remains locked throughout. chain's
1814 * lock status must match flags. Chain is always at least referenced.
1816 * WARNING! The MATCHIND flag does not apply to this function.
1819 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1820 hammer2_key_t *key_nextp,
1821 hammer2_key_t key_beg, hammer2_key_t key_end,
1822 int *cache_indexp, int flags)
1824 hammer2_chain_t *parent;
1828 * Calculate locking flags for upward recursion.
1830 how_maybe = HAMMER2_RESOLVE_MAYBE;
1831 if (flags & HAMMER2_LOOKUP_SHARED)
1832 how_maybe |= HAMMER2_RESOLVE_SHARED;
1837 * Calculate the next index and recalculate the parent if necessary.
1840 key_beg = chain->bref.key +
1841 ((hammer2_key_t)1 << chain->bref.keybits);
1842 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1843 hammer2_chain_unlock(chain);
1844 hammer2_chain_drop(chain);
1847 * chain invalid past this point, but we can still do a
1848 * pointer comparison w/parent.
1850 * Any scan where the lookup returned degenerate data embedded
1851 * in the inode has an invalid index and must terminate.
1853 if (chain == parent)
1855 if (key_beg == 0 || key_beg > key_end)
1858 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1859 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1861 * We reached the end of the iteration.
1866 * Continue iteration with next parent unless the current
1867 * parent covers the range.
1869 key_beg = parent->bref.key +
1870 ((hammer2_key_t)1 << parent->bref.keybits);
1871 if (key_beg == 0 || key_beg > key_end)
1873 parent = hammer2_chain_getparent(parentp, how_maybe);
1879 return (hammer2_chain_lookup(parentp, key_nextp,
1881 cache_indexp, flags));
1885 * The raw scan function is similar to lookup/next but does not seek to a key.
1886 * Blockrefs are iterated via first_chain = (parent, NULL) and
1887 * next_chain = (parent, chain).
1889 * The passed-in parent must be locked and its data resolved. The returned
1890 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1891 * under parent and then iterate with the passed-in chain (which this
1892 * function will unlock).
1895 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1896 int *cache_indexp, int flags)
1899 hammer2_blockref_t *base;
1900 hammer2_blockref_t *bref;
1901 hammer2_blockref_t bcopy;
1903 hammer2_key_t next_key;
1905 int how_always = HAMMER2_RESOLVE_ALWAYS;
1906 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1909 int maxloops = 300000;
1914 * Scan flags borrowed from lookup.
1916 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1917 how_maybe = how_always;
1918 how = HAMMER2_RESOLVE_ALWAYS;
1919 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1920 how = HAMMER2_RESOLVE_NEVER;
1922 how = HAMMER2_RESOLVE_MAYBE;
1924 if (flags & HAMMER2_LOOKUP_SHARED) {
1925 how_maybe |= HAMMER2_RESOLVE_SHARED;
1926 how_always |= HAMMER2_RESOLVE_SHARED;
1927 how |= HAMMER2_RESOLVE_SHARED;
1931 * Calculate key to locate first/next element, unlocking the previous
1932 * element as we go. Be careful, the key calculation can overflow.
1935 key = chain->bref.key +
1936 ((hammer2_key_t)1 << chain->bref.keybits);
1937 hammer2_chain_unlock(chain);
1938 hammer2_chain_drop(chain);
1947 KKASSERT(parent->error == 0); /* XXX case not handled yet */
1948 if (--maxloops == 0)
1949 panic("hammer2_chain_scan: maxloops");
1951 * Locate the blockref array. Currently we do a fully associative
1952 * search through the array.
1954 switch(parent->bref.type) {
1955 case HAMMER2_BREF_TYPE_INODE:
1957 * An inode with embedded data has no sub-chains.
1959 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1961 base = &parent->data->ipdata.u.blockset.blockref[0];
1962 count = HAMMER2_SET_COUNT;
1964 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1965 case HAMMER2_BREF_TYPE_INDIRECT:
1967 * Optimize indirect blocks in the INITIAL state to avoid
1970 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1973 if (parent->data == NULL)
1974 panic("parent->data is NULL");
1975 base = &parent->data->npdata[0];
1977 count = parent->bytes / sizeof(hammer2_blockref_t);
1979 case HAMMER2_BREF_TYPE_VOLUME:
1980 base = &hmp->voldata.sroot_blockset.blockref[0];
1981 count = HAMMER2_SET_COUNT;
1983 case HAMMER2_BREF_TYPE_FREEMAP:
1984 base = &hmp->voldata.freemap_blockset.blockref[0];
1985 count = HAMMER2_SET_COUNT;
1988 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1990 base = NULL; /* safety */
1991 count = 0; /* safety */
1995 * Merged scan to find next candidate.
1997 * hammer2_base_*() functions require the parent->core.live_* fields
1998 * to be synchronized.
2000 * We need to hold the spinlock to access the block array and RB tree
2001 * and to interlock chain creation.
2003 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2004 hammer2_chain_countbrefs(parent, base, count);
2007 hammer2_spin_ex(&parent->core.spin);
2008 chain = hammer2_combined_find(parent, base, count,
2009 cache_indexp, &next_key,
2010 key, HAMMER2_KEY_MAX,
2012 generation = parent->core.generation;
2015 * Exhausted parent chain, we're done.
2018 hammer2_spin_unex(&parent->core.spin);
2019 KKASSERT(chain == NULL);
2024 * Selected from blockref or in-memory chain.
2026 if (chain == NULL) {
2028 hammer2_spin_unex(&parent->core.spin);
2029 chain = hammer2_chain_get(parent, generation, &bcopy);
2030 if (chain == NULL) {
2031 kprintf("retry scan parent %p keys %016jx\n",
2035 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2036 hammer2_chain_drop(chain);
2041 hammer2_chain_ref(chain);
2042 hammer2_spin_unex(&parent->core.spin);
2046 * chain is referenced but not locked. We must lock the chain
2047 * to obtain definitive DUPLICATED/DELETED state
2049 hammer2_chain_lock(chain, how);
2052 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2054 * NOTE: chain's key range is not relevant as there might be
2055 * one-offs within the range that are not deleted.
2057 * NOTE: XXX this could create problems with scans used in
2058 * situations other than mount-time recovery.
2060 * NOTE: Lookups can race delete-duplicate because
2061 * delete-duplicate does not lock the parent's core
2062 * (they just use the spinlock on the core). We must
2063 * check for races by comparing the DUPLICATED flag before
2064 * releasing the spinlock with the flag after locking the
2067 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2068 hammer2_chain_unlock(chain);
2069 hammer2_chain_drop(chain);
2080 * All done, return the chain or NULL
2086 * Create and return a new hammer2 system memory structure of the specified
2087 * key, type and size and insert it under (*parentp). This is a full
2088 * insertion, based on the supplied key/keybits, and may involve creating
2089 * indirect blocks and moving other chains around via delete/duplicate.
2091 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2092 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2093 * FULL. This typically means that the caller is creating the chain after
2094 * doing a hammer2_chain_lookup().
2096 * (*parentp) must be exclusive locked and may be replaced on return
2097 * depending on how much work the function had to do.
2099 * (*parentp) must not be errored or this function will assert.
2101 * (*chainp) usually starts out NULL and returns the newly created chain,
2102 * but if the caller desires the caller may allocate a disconnected chain
2103 * and pass it in instead.
2105 * This function should NOT be used to insert INDIRECT blocks. It is
2106 * typically used to create/insert inodes and data blocks.
2108 * Caller must pass-in an exclusively locked parent the new chain is to
2109 * be inserted under, and optionally pass-in a disconnected, exclusively
2110 * locked chain to insert (else we create a new chain). The function will
2111 * adjust (*parentp) as necessary, create or connect the chain, and
2112 * return an exclusively locked chain in *chainp.
2114 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2115 * and will be reassigned.
2118 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2119 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2120 hammer2_key_t key, int keybits, int type, size_t bytes,
2124 hammer2_chain_t *chain;
2125 hammer2_chain_t *parent;
2126 hammer2_blockref_t *base;
2127 hammer2_blockref_t dummy;
2131 int maxloops = 300000;
2134 * Topology may be crossing a PFS boundary.
2137 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2138 KKASSERT(parent->error == 0);
2142 if (chain == NULL) {
2144 * First allocate media space and construct the dummy bref,
2145 * then allocate the in-memory chain structure. Set the
2146 * INITIAL flag for fresh chains which do not have embedded
2149 bzero(&dummy, sizeof(dummy));
2152 dummy.keybits = keybits;
2153 dummy.data_off = hammer2_getradix(bytes);
2154 dummy.methods = parent->bref.methods;
2155 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2158 * Lock the chain manually, chain_lock will load the chain
2159 * which we do NOT want to do. (note: chain->refs is set
2160 * to 1 by chain_alloc() for us, but lockcnt is not).
2163 hammer2_mtx_ex(&chain->core.lock);
2167 * We do NOT set INITIAL here (yet). INITIAL is only
2168 * used for indirect blocks.
2170 * Recalculate bytes to reflect the actual media block
2173 bytes = (hammer2_off_t)1 <<
2174 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2175 chain->bytes = bytes;
2178 case HAMMER2_BREF_TYPE_VOLUME:
2179 case HAMMER2_BREF_TYPE_FREEMAP:
2180 panic("hammer2_chain_create: called with volume type");
2182 case HAMMER2_BREF_TYPE_INDIRECT:
2183 panic("hammer2_chain_create: cannot be used to"
2184 "create indirect block");
2186 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2187 panic("hammer2_chain_create: cannot be used to"
2188 "create freemap root or node");
2190 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2191 KKASSERT(bytes == sizeof(chain->data->bmdata));
2193 case HAMMER2_BREF_TYPE_INODE:
2194 case HAMMER2_BREF_TYPE_DATA:
2197 * leave chain->data NULL, set INITIAL
2199 KKASSERT(chain->data == NULL);
2200 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2205 * Set statistics for pending updates. These will be
2206 * synchronized by the flush code.
2209 case HAMMER2_BREF_TYPE_INODE:
2210 chain->inode_count = 1;
2212 case HAMMER2_BREF_TYPE_DATA:
2213 case HAMMER2_BREF_TYPE_INDIRECT:
2214 chain->data_count = chain->bytes;
2219 * We are reattaching a previously deleted chain, possibly
2220 * under a new parent and possibly with a new key/keybits.
2221 * The chain does not have to be in a modified state. The
2222 * UPDATE flag will be set later on in this routine.
2224 * Do NOT mess with the current state of the INITIAL flag.
2226 chain->bref.key = key;
2227 chain->bref.keybits = keybits;
2228 if (chain->flags & HAMMER2_CHAIN_DELETED)
2229 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2230 KKASSERT(chain->parent == NULL);
2232 if (flags & HAMMER2_INSERT_PFSROOT)
2233 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2235 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2238 * Calculate how many entries we have in the blockref array and
2239 * determine if an indirect block is required.
2242 if (--maxloops == 0)
2243 panic("hammer2_chain_create: maxloops");
2245 switch(parent->bref.type) {
2246 case HAMMER2_BREF_TYPE_INODE:
2247 KKASSERT((parent->data->ipdata.op_flags &
2248 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2249 KKASSERT(parent->data != NULL);
2250 base = &parent->data->ipdata.u.blockset.blockref[0];
2251 count = HAMMER2_SET_COUNT;
2253 case HAMMER2_BREF_TYPE_INDIRECT:
2254 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2255 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2258 base = &parent->data->npdata[0];
2259 count = parent->bytes / sizeof(hammer2_blockref_t);
2261 case HAMMER2_BREF_TYPE_VOLUME:
2262 KKASSERT(parent->data != NULL);
2263 base = &hmp->voldata.sroot_blockset.blockref[0];
2264 count = HAMMER2_SET_COUNT;
2266 case HAMMER2_BREF_TYPE_FREEMAP:
2267 KKASSERT(parent->data != NULL);
2268 base = &hmp->voldata.freemap_blockset.blockref[0];
2269 count = HAMMER2_SET_COUNT;
2272 panic("hammer2_chain_create: unrecognized blockref type: %d",
2280 * Make sure we've counted the brefs
2282 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2283 hammer2_chain_countbrefs(parent, base, count);
2285 KKASSERT(parent->core.live_count >= 0 &&
2286 parent->core.live_count <= count);
2289 * If no free blockref could be found we must create an indirect
2290 * block and move a number of blockrefs into it. With the parent
2291 * locked we can safely lock each child in order to delete+duplicate
2292 * it without causing a deadlock.
2294 * This may return the new indirect block or the old parent depending
2295 * on where the key falls. NULL is returned on error.
2297 if (parent->core.live_count == count) {
2298 hammer2_chain_t *nparent;
2300 nparent = hammer2_chain_create_indirect(trans, parent,
2303 if (nparent == NULL) {
2305 hammer2_chain_drop(chain);
2309 if (parent != nparent) {
2310 hammer2_chain_unlock(parent);
2311 hammer2_chain_drop(parent);
2312 parent = *parentp = nparent;
2318 * Link the chain into its parent.
2320 if (chain->parent != NULL)
2321 panic("hammer2: hammer2_chain_create: chain already connected");
2322 KKASSERT(chain->parent == NULL);
2323 hammer2_chain_insert(parent, chain,
2324 HAMMER2_CHAIN_INSERT_SPIN |
2325 HAMMER2_CHAIN_INSERT_LIVE,
2330 * Mark the newly created chain modified. This will cause
2333 * Device buffers are not instantiated for DATA elements
2334 * as these are handled by logical buffers.
2336 * Indirect and freemap node indirect blocks are handled
2337 * by hammer2_chain_create_indirect() and not by this
2340 * Data for all other bref types is expected to be
2341 * instantiated (INODE, LEAF).
2343 switch(chain->bref.type) {
2344 case HAMMER2_BREF_TYPE_DATA:
2345 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2346 case HAMMER2_BREF_TYPE_INODE:
2347 hammer2_chain_modify(trans, chain,
2348 HAMMER2_MODIFY_OPTDATA);
2352 * Remaining types are not supported by this function.
2353 * In particular, INDIRECT and LEAF_NODE types are
2354 * handled by create_indirect().
2356 panic("hammer2_chain_create: bad type: %d",
2363 * When reconnecting a chain we must set UPDATE and
2364 * setflush so the flush recognizes that it must update
2365 * the bref in the parent.
2367 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2368 hammer2_chain_ref(chain);
2369 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2371 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2372 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2373 KKASSERT(chain->data);
2374 chain->inode_count_up +=
2375 chain->data->ipdata.inode_count;
2376 chain->data_count_up +=
2377 chain->data->ipdata.data_count;
2382 * We must setflush(parent) to ensure that it recurses through to
2383 * chain. setflush(chain) might not work because ONFLUSH is possibly
2384 * already set in the chain (so it won't recurse up to set it in the
2387 hammer2_chain_setflush(trans, parent);
2396 * Move the chain from its old parent to a new parent. The chain must have
2397 * already been deleted or already disconnected (or never associated) with
2398 * a parent. The chain is reassociated with the new parent and the deleted
2399 * flag will be cleared (no longer deleted). The chain's modification state
2402 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2403 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2404 * FULL. This typically means that the caller is creating the chain after
2405 * doing a hammer2_chain_lookup().
2407 * A non-NULL bref is typically passed when key and keybits must be overridden.
2408 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2409 * from a passed-in bref and uses the old chain's bref for everything else.
2411 * Neither (parent) or (chain) can be errored.
2413 * If (parent) is non-NULL then the new duplicated chain is inserted under
2416 * If (parent) is NULL then the newly duplicated chain is not inserted
2417 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2418 * passing into hammer2_chain_create() after this function returns).
2420 * WARNING! This function calls create which means it can insert indirect
2421 * blocks. This can cause other unrelated chains in the parent to
2422 * be moved to a newly inserted indirect block in addition to the
2426 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2427 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2431 hammer2_chain_t *parent;
2435 * WARNING! We should never resolve DATA to device buffers
2436 * (XXX allow it if the caller did?), and since
2437 * we currently do not have the logical buffer cache
2438 * buffer in-hand to fix its cached physical offset
2439 * we also force the modify code to not COW it. XXX
2442 KKASSERT(chain->parent == NULL);
2443 KKASSERT(chain->error == 0);
2446 * Now create a duplicate of the chain structure, associating
2447 * it with the same core, making it the same size, pointing it
2448 * to the same bref (the same media block).
2451 bref = &chain->bref;
2452 bytes = (hammer2_off_t)1 <<
2453 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2456 * If parent is not NULL the duplicated chain will be entered under
2457 * the parent and the UPDATE bit set to tell flush to update
2460 * We must setflush(parent) to ensure that it recurses through to
2461 * chain. setflush(chain) might not work because ONFLUSH is possibly
2462 * already set in the chain (so it won't recurse up to set it in the
2465 * Having both chains locked is extremely important for atomicy.
2467 if (parentp && (parent = *parentp) != NULL) {
2468 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2469 KKASSERT(parent->refs > 0);
2470 KKASSERT(parent->error == 0);
2472 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2473 bref->key, bref->keybits, bref->type,
2474 chain->bytes, flags);
2475 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2476 hammer2_chain_setflush(trans, *parentp);
2481 * Helper function for deleting chains.
2483 * The chain is removed from the live view (the RBTREE) as well as the parent's
2484 * blockmap. Both chain and its parent must be locked.
2486 * parent may not be errored. chain can be errored.
2489 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2490 hammer2_chain_t *parent, hammer2_chain_t *chain,
2495 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2496 HAMMER2_CHAIN_FICTITIOUS)) == 0);
2499 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2501 * Chain is blockmapped, so there must be a parent.
2502 * Atomically remove the chain from the parent and remove
2503 * the blockmap entry.
2505 hammer2_blockref_t *base;
2508 KKASSERT(parent != NULL);
2509 KKASSERT(parent->error == 0);
2510 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2511 hammer2_chain_modify(trans, parent,
2512 HAMMER2_MODIFY_OPTDATA);
2515 * Calculate blockmap pointer
2517 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2518 hammer2_spin_ex(&parent->core.spin);
2520 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2521 atomic_add_int(&parent->core.live_count, -1);
2522 ++parent->core.generation;
2523 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2524 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2525 --parent->core.chain_count;
2526 chain->parent = NULL;
2528 switch(parent->bref.type) {
2529 case HAMMER2_BREF_TYPE_INODE:
2531 * Access the inode's block array. However, there
2532 * is no block array if the inode is flagged
2533 * DIRECTDATA. The DIRECTDATA case typicaly only
2534 * occurs when a hardlink has been shifted up the
2535 * tree and the original inode gets replaced with
2536 * an OBJTYPE_HARDLINK placeholding inode.
2539 (parent->data->ipdata.op_flags &
2540 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2542 &parent->data->ipdata.u.blockset.blockref[0];
2546 count = HAMMER2_SET_COUNT;
2548 case HAMMER2_BREF_TYPE_INDIRECT:
2549 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2551 base = &parent->data->npdata[0];
2554 count = parent->bytes / sizeof(hammer2_blockref_t);
2556 case HAMMER2_BREF_TYPE_VOLUME:
2557 base = &hmp->voldata.sroot_blockset.blockref[0];
2558 count = HAMMER2_SET_COUNT;
2560 case HAMMER2_BREF_TYPE_FREEMAP:
2561 base = &parent->data->npdata[0];
2562 count = HAMMER2_SET_COUNT;
2567 panic("hammer2_flush_pass2: "
2568 "unrecognized blockref type: %d",
2573 * delete blockmapped chain from its parent.
2575 * The parent is not affected by any statistics in chain
2576 * which are pending synchronization. That is, there is
2577 * nothing to undo in the parent since they have not yet
2578 * been incorporated into the parent.
2580 * The parent is affected by statistics stored in inodes.
2581 * Those have already been synchronized, so they must be
2582 * undone. XXX split update possible w/delete in middle?
2585 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2586 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2587 KKASSERT(chain->data != NULL);
2588 parent->data_count -=
2589 chain->data->ipdata.data_count;
2590 parent->inode_count -=
2591 chain->data->ipdata.inode_count;
2594 int cache_index = -1;
2595 hammer2_base_delete(trans, parent, base, count,
2596 &cache_index, chain);
2598 hammer2_spin_unex(&parent->core.spin);
2599 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2601 * Chain is not blockmapped but a parent is present.
2602 * Atomically remove the chain from the parent. There is
2603 * no blockmap entry to remove.
2605 * Because chain was associated with a parent but not
2606 * synchronized, the chain's *_count_up fields contain
2607 * inode adjustment statistics which must be undone.
2609 hammer2_spin_ex(&parent->core.spin);
2610 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2611 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2612 KKASSERT(chain->data != NULL);
2613 chain->data_count_up -=
2614 chain->data->ipdata.data_count;
2615 chain->inode_count_up -=
2616 chain->data->ipdata.inode_count;
2618 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2619 atomic_add_int(&parent->core.live_count, -1);
2620 ++parent->core.generation;
2621 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2622 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2623 --parent->core.chain_count;
2624 chain->parent = NULL;
2625 hammer2_spin_unex(&parent->core.spin);
2628 * Chain is not blockmapped and has no parent. This
2629 * is a degenerate case.
2631 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2636 * If the deletion is permanent (i.e. the chain is not simply being
2637 * moved within the topology), adjust the freemap to indicate that
2638 * the block *might* be freeable. bulkfree must still determine
2639 * that it is actually freeable.
2641 * We no longer do this in the normal filesystem operations path
2642 * as it interferes with the bulkfree algorithm.
2644 if ((flags & HAMMER2_DELETE_PERMANENT) &&
2645 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2646 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
2647 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
2648 hammer2_freemap_adjust(trans, hmp, &chain->bref,
2649 HAMMER2_FREEMAP_DOMAYFREE);
2655 * Create an indirect block that covers one or more of the elements in the
2656 * current parent. Either returns the existing parent with no locking or
2657 * ref changes or returns the new indirect block locked and referenced
2658 * and leaving the original parent lock/ref intact as well.
2660 * If an error occurs, NULL is returned and *errorp is set to the error.
2662 * The returned chain depends on where the specified key falls.
2664 * The key/keybits for the indirect mode only needs to follow three rules:
2666 * (1) That all elements underneath it fit within its key space and
2668 * (2) That all elements outside it are outside its key space.
2670 * (3) When creating the new indirect block any elements in the current
2671 * parent that fit within the new indirect block's keyspace must be
2672 * moved into the new indirect block.
2674 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2675 * keyspace the the current parent, but lookup/iteration rules will
2676 * ensure (and must ensure) that rule (2) for all parents leading up
2677 * to the nearest inode or the root volume header is adhered to. This
2678 * is accomplished by always recursing through matching keyspaces in
2679 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2681 * The current implementation calculates the current worst-case keyspace by
2682 * iterating the current parent and then divides it into two halves, choosing
2683 * whichever half has the most elements (not necessarily the half containing
2684 * the requested key).
2686 * We can also opt to use the half with the least number of elements. This
2687 * causes lower-numbered keys (aka logical file offsets) to recurse through
2688 * fewer indirect blocks and higher-numbered keys to recurse through more.
2689 * This also has the risk of not moving enough elements to the new indirect
2690 * block and being forced to create several indirect blocks before the element
2693 * Must be called with an exclusively locked parent.
2695 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2696 hammer2_key_t *keyp, int keybits,
2697 hammer2_blockref_t *base, int count);
2698 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2699 hammer2_key_t *keyp, int keybits,
2700 hammer2_blockref_t *base, int count);
2703 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2704 hammer2_key_t create_key, int create_bits,
2705 int for_type, int *errorp)
2708 hammer2_blockref_t *base;
2709 hammer2_blockref_t *bref;
2710 hammer2_blockref_t bcopy;
2711 hammer2_chain_t *chain;
2712 hammer2_chain_t *ichain;
2713 hammer2_chain_t dummy;
2714 hammer2_key_t key = create_key;
2715 hammer2_key_t key_beg;
2716 hammer2_key_t key_end;
2717 hammer2_key_t key_next;
2718 int keybits = create_bits;
2725 int maxloops = 300000;
2728 * Calculate the base blockref pointer or NULL if the chain
2729 * is known to be empty. We need to calculate the array count
2730 * for RB lookups either way.
2734 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2736 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2737 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2740 switch(parent->bref.type) {
2741 case HAMMER2_BREF_TYPE_INODE:
2742 count = HAMMER2_SET_COUNT;
2744 case HAMMER2_BREF_TYPE_INDIRECT:
2745 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2746 count = parent->bytes / sizeof(hammer2_blockref_t);
2748 case HAMMER2_BREF_TYPE_VOLUME:
2749 count = HAMMER2_SET_COUNT;
2751 case HAMMER2_BREF_TYPE_FREEMAP:
2752 count = HAMMER2_SET_COUNT;
2755 panic("hammer2_chain_create_indirect: "
2756 "unrecognized blockref type: %d",
2762 switch(parent->bref.type) {
2763 case HAMMER2_BREF_TYPE_INODE:
2764 base = &parent->data->ipdata.u.blockset.blockref[0];
2765 count = HAMMER2_SET_COUNT;
2767 case HAMMER2_BREF_TYPE_INDIRECT:
2768 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2769 base = &parent->data->npdata[0];
2770 count = parent->bytes / sizeof(hammer2_blockref_t);
2772 case HAMMER2_BREF_TYPE_VOLUME:
2773 base = &hmp->voldata.sroot_blockset.blockref[0];
2774 count = HAMMER2_SET_COUNT;
2776 case HAMMER2_BREF_TYPE_FREEMAP:
2777 base = &hmp->voldata.freemap_blockset.blockref[0];
2778 count = HAMMER2_SET_COUNT;
2781 panic("hammer2_chain_create_indirect: "
2782 "unrecognized blockref type: %d",
2790 * dummy used in later chain allocation (no longer used for lookups).
2792 bzero(&dummy, sizeof(dummy));
2795 * When creating an indirect block for a freemap node or leaf
2796 * the key/keybits must be fitted to static radix levels because
2797 * particular radix levels use particular reserved blocks in the
2800 * This routine calculates the key/radix of the indirect block
2801 * we need to create, and whether it is on the high-side or the
2804 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2805 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2806 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2809 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2814 * Normalize the key for the radix being represented, keeping the
2815 * high bits and throwing away the low bits.
2817 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2820 * How big should our new indirect block be? It has to be at least
2821 * as large as its parent.
2823 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2824 nbytes = HAMMER2_IND_BYTES_MIN;
2826 nbytes = HAMMER2_IND_BYTES_MAX;
2827 if (nbytes < count * sizeof(hammer2_blockref_t))
2828 nbytes = count * sizeof(hammer2_blockref_t);
2831 * Ok, create our new indirect block
2833 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2834 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2835 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2837 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2839 dummy.bref.key = key;
2840 dummy.bref.keybits = keybits;
2841 dummy.bref.data_off = hammer2_getradix(nbytes);
2842 dummy.bref.methods = parent->bref.methods;
2844 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2845 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2846 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2847 /* ichain has one ref at this point */
2850 * We have to mark it modified to allocate its block, but use
2851 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2852 * it won't be acted upon by the flush code.
2854 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2857 * Iterate the original parent and move the matching brefs into
2858 * the new indirect block.
2860 * XXX handle flushes.
2863 key_end = HAMMER2_KEY_MAX;
2865 hammer2_spin_ex(&parent->core.spin);
2870 if (++loops > 100000) {
2871 hammer2_spin_unex(&parent->core.spin);
2872 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2873 reason, parent, base, count, key_next);
2877 * NOTE: spinlock stays intact, returned chain (if not NULL)
2878 * is not referenced or locked which means that we
2879 * cannot safely check its flagged / deletion status
2882 chain = hammer2_combined_find(parent, base, count,
2883 &cache_index, &key_next,
2886 generation = parent->core.generation;
2889 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2892 * Skip keys that are not within the key/radix of the new
2893 * indirect block. They stay in the parent.
2895 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2896 (key ^ bref->key)) != 0) {
2897 goto next_key_spinlocked;
2901 * Load the new indirect block by acquiring the related
2902 * chains (potentially from media as it might not be
2903 * in-memory). Then move it to the new parent (ichain)
2904 * via DELETE-DUPLICATE.
2906 * chain is referenced but not locked. We must lock the
2907 * chain to obtain definitive DUPLICATED/DELETED state
2911 * Use chain already present in the RBTREE
2913 hammer2_chain_ref(chain);
2914 hammer2_spin_unex(&parent->core.spin);
2915 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2918 * Get chain for blockref element. _get returns NULL
2919 * on insertion race.
2922 hammer2_spin_unex(&parent->core.spin);
2923 chain = hammer2_chain_get(parent, generation, &bcopy);
2924 if (chain == NULL) {
2926 hammer2_spin_ex(&parent->core.spin);
2929 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2930 kprintf("REASON 2\n");
2932 hammer2_chain_drop(chain);
2933 hammer2_spin_ex(&parent->core.spin);
2936 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2940 * This is always live so if the chain has been deleted
2941 * we raced someone and we have to retry.
2943 * NOTE: Lookups can race delete-duplicate because
2944 * delete-duplicate does not lock the parent's core
2945 * (they just use the spinlock on the core). We must
2946 * check for races by comparing the DUPLICATED flag before
2947 * releasing the spinlock with the flag after locking the
2950 * (note reversed logic for this one)
2952 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2953 hammer2_chain_unlock(chain);
2954 hammer2_chain_drop(chain);
2959 * Shift the chain to the indirect block.
2961 * WARNING! No reason for us to load chain data, pass NOSTATS
2962 * to prevent delete/insert from trying to access
2963 * inode stats (and thus asserting if there is no
2964 * chain->data loaded).
2966 hammer2_chain_delete(trans, parent, chain,
2967 HAMMER2_DELETE_NOSTATS);
2968 hammer2_chain_rename(trans, NULL, &ichain, chain,
2969 HAMMER2_INSERT_NOSTATS);
2970 hammer2_chain_unlock(chain);
2971 hammer2_chain_drop(chain);
2972 KKASSERT(parent->refs > 0);
2975 hammer2_spin_ex(&parent->core.spin);
2976 next_key_spinlocked:
2977 if (--maxloops == 0)
2978 panic("hammer2_chain_create_indirect: maxloops");
2980 if (key_next == 0 || key_next > key_end)
2985 hammer2_spin_unex(&parent->core.spin);
2988 * Insert the new indirect block into the parent now that we've
2989 * cleared out some entries in the parent. We calculated a good
2990 * insertion index in the loop above (ichain->index).
2992 * We don't have to set UPDATE here because we mark ichain
2993 * modified down below (so the normal modified -> flush -> set-moved
2994 * sequence applies).
2996 * The insertion shouldn't race as this is a completely new block
2997 * and the parent is locked.
2999 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3000 hammer2_chain_insert(parent, ichain,
3001 HAMMER2_CHAIN_INSERT_SPIN |
3002 HAMMER2_CHAIN_INSERT_LIVE,
3006 * Make sure flushes propogate after our manual insertion.
3008 hammer2_chain_setflush(trans, ichain);
3009 hammer2_chain_setflush(trans, parent);
3012 * Figure out what to return.
3014 if (~(((hammer2_key_t)1 << keybits) - 1) &
3015 (create_key ^ key)) {
3017 * Key being created is outside the key range,
3018 * return the original parent.
3020 hammer2_chain_unlock(ichain);
3021 hammer2_chain_drop(ichain);
3024 * Otherwise its in the range, return the new parent.
3025 * (leave both the new and old parent locked).
3034 * Calculate the keybits and highside/lowside of the freemap node the
3035 * caller is creating.
3037 * This routine will specify the next higher-level freemap key/radix
3038 * representing the lowest-ordered set. By doing so, eventually all
3039 * low-ordered sets will be moved one level down.
3041 * We have to be careful here because the freemap reserves a limited
3042 * number of blocks for a limited number of levels. So we can't just
3043 * push indiscriminately.
3046 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3047 int keybits, hammer2_blockref_t *base, int count)
3049 hammer2_chain_t *chain;
3050 hammer2_blockref_t *bref;
3052 hammer2_key_t key_beg;
3053 hammer2_key_t key_end;
3054 hammer2_key_t key_next;
3058 int maxloops = 300000;
3066 * Calculate the range of keys in the array being careful to skip
3067 * slots which are overridden with a deletion.
3070 key_end = HAMMER2_KEY_MAX;
3072 hammer2_spin_ex(&parent->core.spin);
3075 if (--maxloops == 0) {
3076 panic("indkey_freemap shit %p %p:%d\n",
3077 parent, base, count);
3079 chain = hammer2_combined_find(parent, base, count,
3080 &cache_index, &key_next,
3091 * Skip deleted chains.
3093 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3094 if (key_next == 0 || key_next > key_end)
3101 * Use the full live (not deleted) element for the scan
3102 * iteration. HAMMER2 does not allow partial replacements.
3104 * XXX should be built into hammer2_combined_find().
3106 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3108 if (keybits > bref->keybits) {
3110 keybits = bref->keybits;
3111 } else if (keybits == bref->keybits && bref->key < key) {
3118 hammer2_spin_unex(&parent->core.spin);
3121 * Return the keybits for a higher-level FREEMAP_NODE covering
3125 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3126 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3128 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3129 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3131 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3132 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3134 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3135 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3137 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3138 panic("hammer2_chain_indkey_freemap: level too high");
3141 panic("hammer2_chain_indkey_freemap: bad radix");
3150 * Calculate the keybits and highside/lowside of the indirect block the
3151 * caller is creating.
3154 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3155 int keybits, hammer2_blockref_t *base, int count)
3157 hammer2_blockref_t *bref;
3158 hammer2_chain_t *chain;
3159 hammer2_key_t key_beg;
3160 hammer2_key_t key_end;
3161 hammer2_key_t key_next;
3167 int maxloops = 300000;
3174 * Calculate the range of keys in the array being careful to skip
3175 * slots which are overridden with a deletion. Once the scan
3176 * completes we will cut the key range in half and shift half the
3177 * range into the new indirect block.
3180 key_end = HAMMER2_KEY_MAX;
3182 hammer2_spin_ex(&parent->core.spin);
3185 if (--maxloops == 0) {
3186 panic("indkey_freemap shit %p %p:%d\n",
3187 parent, base, count);
3189 chain = hammer2_combined_find(parent, base, count,
3190 &cache_index, &key_next,
3201 * NOTE: No need to check DUPLICATED here because we do
3202 * not release the spinlock.
3204 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3205 if (key_next == 0 || key_next > key_end)
3212 * Use the full live (not deleted) element for the scan
3213 * iteration. HAMMER2 does not allow partial replacements.
3215 * XXX should be built into hammer2_combined_find().
3217 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3220 * Expand our calculated key range (key, keybits) to fit
3221 * the scanned key. nkeybits represents the full range
3222 * that we will later cut in half (two halves @ nkeybits - 1).
3225 if (nkeybits < bref->keybits) {
3226 if (bref->keybits > 64) {
3227 kprintf("bad bref chain %p bref %p\n",
3231 nkeybits = bref->keybits;
3233 while (nkeybits < 64 &&
3234 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3235 (key ^ bref->key)) != 0) {
3240 * If the new key range is larger we have to determine
3241 * which side of the new key range the existing keys fall
3242 * under by checking the high bit, then collapsing the
3243 * locount into the hicount or vise-versa.
3245 if (keybits != nkeybits) {
3246 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3257 * The newly scanned key will be in the lower half or the
3258 * upper half of the (new) key range.
3260 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3269 hammer2_spin_unex(&parent->core.spin);
3270 bref = NULL; /* now invalid (safety) */
3273 * Adjust keybits to represent half of the full range calculated
3274 * above (radix 63 max)
3279 * Select whichever half contains the most elements. Theoretically
3280 * we can select either side as long as it contains at least one
3281 * element (in order to ensure that a free slot is present to hold
3282 * the indirect block).
3284 if (hammer2_indirect_optimize) {
3286 * Insert node for least number of keys, this will arrange
3287 * the first few blocks of a large file or the first few
3288 * inodes in a directory with fewer indirect blocks when
3291 if (hicount < locount && hicount != 0)
3292 key |= (hammer2_key_t)1 << keybits;
3294 key &= ~(hammer2_key_t)1 << keybits;
3297 * Insert node for most number of keys, best for heavily
3300 if (hicount > locount)
3301 key |= (hammer2_key_t)1 << keybits;
3303 key &= ~(hammer2_key_t)1 << keybits;
3311 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3314 * Both parent and chain must be locked exclusively.
3316 * This function will modify the parent if the blockref requires removal
3317 * from the parent's block table.
3319 * This function is NOT recursive. Any entity already pushed into the
3320 * chain (such as an inode) may still need visibility into its contents,
3321 * as well as the ability to read and modify the contents. For example,
3322 * for an unlinked file which is still open.
3325 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3326 hammer2_chain_t *chain, int flags)
3328 KKASSERT(hammer2_mtx_owned(&chain->core.lock));
3331 * Nothing to do if already marked.
3333 * We need the spinlock on the core whos RBTREE contains chain
3334 * to protect against races.
3336 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3337 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3338 chain->parent == parent);
3339 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3343 * NOTE: Special case call to hammer2_flush(). We are not in a FLUSH
3344 * transaction, so we can't pass a mirror_tid for the volume.
3345 * But since we are destroying the chain we can just pass 0
3346 * and use the flush call to clean out the subtopology.
3348 * XXX not the best way to destroy the sub-topology.
3350 if (flags & HAMMER2_DELETE_PERMANENT) {
3351 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3352 hammer2_flush(trans, chain);
3354 /* XXX might not be needed */
3355 hammer2_chain_setflush(trans, chain);
3360 * Returns the index of the nearest element in the blockref array >= elm.
3361 * Returns (count) if no element could be found.
3363 * Sets *key_nextp to the next key for loop purposes but does not modify
3364 * it if the next key would be higher than the current value of *key_nextp.
3365 * Note that *key_nexp can overflow to 0, which should be tested by the
3368 * (*cache_indexp) is a heuristic and can be any value without effecting
3371 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3372 * held through the operation.
3375 hammer2_base_find(hammer2_chain_t *parent,
3376 hammer2_blockref_t *base, int count,
3377 int *cache_indexp, hammer2_key_t *key_nextp,
3378 hammer2_key_t key_beg, hammer2_key_t key_end)
3380 hammer2_blockref_t *scan;
3381 hammer2_key_t scan_end;
3386 * Require the live chain's already have their core's counted
3387 * so we can optimize operations.
3389 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3394 if (count == 0 || base == NULL)
3398 * Sequential optimization using *cache_indexp. This is the most
3401 * We can avoid trailing empty entries on live chains, otherwise
3402 * we might have to check the whole block array.
3406 limit = parent->core.live_zero;
3411 KKASSERT(i < count);
3417 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3424 * Search forwards, stop when we find a scan element which
3425 * encloses the key or until we know that there are no further
3429 if (scan->type != 0) {
3430 scan_end = scan->key +
3431 ((hammer2_key_t)1 << scan->keybits) - 1;
3432 if (scan->key > key_beg || scan_end >= key_beg)
3445 scan_end = scan->key +
3446 ((hammer2_key_t)1 << scan->keybits);
3447 if (scan_end && (*key_nextp > scan_end ||
3449 *key_nextp = scan_end;
3457 * Do a combined search and return the next match either from the blockref
3458 * array or from the in-memory chain. Sets *bresp to the returned bref in
3459 * both cases, or sets it to NULL if the search exhausted. Only returns
3460 * a non-NULL chain if the search matched from the in-memory chain.
3462 * When no in-memory chain has been found and a non-NULL bref is returned
3466 * The returned chain is not locked or referenced. Use the returned bref
3467 * to determine if the search exhausted or not. Iterate if the base find
3468 * is chosen but matches a deleted chain.
3470 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3471 * held through the operation.
3473 static hammer2_chain_t *
3474 hammer2_combined_find(hammer2_chain_t *parent,
3475 hammer2_blockref_t *base, int count,
3476 int *cache_indexp, hammer2_key_t *key_nextp,
3477 hammer2_key_t key_beg, hammer2_key_t key_end,
3478 hammer2_blockref_t **bresp)
3480 hammer2_blockref_t *bref;
3481 hammer2_chain_t *chain;
3485 * Lookup in block array and in rbtree.
3487 *key_nextp = key_end + 1;
3488 i = hammer2_base_find(parent, base, count, cache_indexp,
3489 key_nextp, key_beg, key_end);
3490 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3495 if (i == count && chain == NULL) {
3501 * Only chain matched.
3504 bref = &chain->bref;
3509 * Only blockref matched.
3511 if (chain == NULL) {
3517 * Both in-memory and blockref matched, select the nearer element.
3519 * If both are flush with the left-hand side or both are the
3520 * same distance away, select the chain. In this situation the
3521 * chain must have been loaded from the matching blockmap.
3523 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3524 chain->bref.key == base[i].key) {
3525 KKASSERT(chain->bref.key == base[i].key);
3526 bref = &chain->bref;
3531 * Select the nearer key
3533 if (chain->bref.key < base[i].key) {
3534 bref = &chain->bref;
3541 * If the bref is out of bounds we've exhausted our search.
3544 if (bref->key > key_end) {
3554 * Locate the specified block array element and delete it. The element
3557 * The spin lock on the related chain must be held.
3559 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3560 * need to be adjusted when we commit the media change.
3563 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3564 hammer2_blockref_t *base, int count,
3565 int *cache_indexp, hammer2_chain_t *chain)
3567 hammer2_blockref_t *elm = &chain->bref;
3568 hammer2_key_t key_next;
3572 * Delete element. Expect the element to exist.
3574 * XXX see caller, flush code not yet sophisticated enough to prevent
3575 * re-flushed in some cases.
3577 key_next = 0; /* max range */
3578 i = hammer2_base_find(parent, base, count, cache_indexp,
3579 &key_next, elm->key, elm->key);
3580 if (i == count || base[i].type == 0 ||
3581 base[i].key != elm->key ||
3582 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3583 base[i].keybits != elm->keybits)) {
3584 hammer2_spin_unex(&parent->core.spin);
3585 panic("delete base %p element not found at %d/%d elm %p\n",
3586 base, i, count, elm);
3589 bzero(&base[i], sizeof(*base));
3592 * We can only optimize parent->core.live_zero for live chains.
3594 if (parent->core.live_zero == i + 1) {
3595 while (--i >= 0 && base[i].type == 0)
3597 parent->core.live_zero = i + 1;
3601 * Clear appropriate blockmap flags in chain.
3603 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3604 HAMMER2_CHAIN_BMAPUPD);
3608 * Insert the specified element. The block array must not already have the
3609 * element and must have space available for the insertion.
3611 * The spin lock on the related chain must be held.
3613 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3614 * need to be adjusted when we commit the media change.
3617 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3618 hammer2_blockref_t *base, int count,
3619 int *cache_indexp, hammer2_chain_t *chain)
3621 hammer2_blockref_t *elm = &chain->bref;
3622 hammer2_key_t key_next;
3631 * Insert new element. Expect the element to not already exist
3632 * unless we are replacing it.
3634 * XXX see caller, flush code not yet sophisticated enough to prevent
3635 * re-flushed in some cases.
3637 key_next = 0; /* max range */
3638 i = hammer2_base_find(parent, base, count, cache_indexp,
3639 &key_next, elm->key, elm->key);
3642 * Shortcut fill optimization, typical ordered insertion(s) may not
3645 KKASSERT(i >= 0 && i <= count);
3648 * Set appropriate blockmap flags in chain.
3650 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3653 * We can only optimize parent->core.live_zero for live chains.
3655 if (i == count && parent->core.live_zero < count) {
3656 i = parent->core.live_zero++;
3661 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3662 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3663 hammer2_spin_unex(&parent->core.spin);
3664 panic("insert base %p overlapping elements at %d elm %p\n",
3669 * Try to find an empty slot before or after.
3673 while (j > 0 || k < count) {
3675 if (j >= 0 && base[j].type == 0) {
3679 bcopy(&base[j+1], &base[j],
3680 (i - j - 1) * sizeof(*base));
3686 if (k < count && base[k].type == 0) {
3687 bcopy(&base[i], &base[i+1],
3688 (k - i) * sizeof(hammer2_blockref_t));
3692 * We can only update parent->core.live_zero for live
3695 if (parent->core.live_zero <= k)
3696 parent->core.live_zero = k + 1;
3701 panic("hammer2_base_insert: no room!");
3708 for (l = 0; l < count; ++l) {
3710 key_next = base[l].key +
3711 ((hammer2_key_t)1 << base[l].keybits) - 1;
3715 while (++l < count) {
3717 if (base[l].key <= key_next)
3718 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3719 key_next = base[l].key +
3720 ((hammer2_key_t)1 << base[l].keybits) - 1;
3730 * Sort the blockref array for the chain. Used by the flush code to
3731 * sort the blockref[] array.
3733 * The chain must be exclusively locked AND spin-locked.
3735 typedef hammer2_blockref_t *hammer2_blockref_p;
3739 hammer2_base_sort_callback(const void *v1, const void *v2)
3741 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3742 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3745 * Make sure empty elements are placed at the end of the array
3747 if (bref1->type == 0) {
3748 if (bref2->type == 0)
3751 } else if (bref2->type == 0) {
3758 if (bref1->key < bref2->key)
3760 if (bref1->key > bref2->key)
3766 hammer2_base_sort(hammer2_chain_t *chain)
3768 hammer2_blockref_t *base;
3771 switch(chain->bref.type) {
3772 case HAMMER2_BREF_TYPE_INODE:
3774 * Special shortcut for embedded data returns the inode
3775 * itself. Callers must detect this condition and access
3776 * the embedded data (the strategy code does this for us).
3778 * This is only applicable to regular files and softlinks.
3780 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3782 base = &chain->data->ipdata.u.blockset.blockref[0];
3783 count = HAMMER2_SET_COUNT;
3785 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3786 case HAMMER2_BREF_TYPE_INDIRECT:
3788 * Optimize indirect blocks in the INITIAL state to avoid
3791 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3792 base = &chain->data->npdata[0];
3793 count = chain->bytes / sizeof(hammer2_blockref_t);
3795 case HAMMER2_BREF_TYPE_VOLUME:
3796 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3797 count = HAMMER2_SET_COUNT;
3799 case HAMMER2_BREF_TYPE_FREEMAP:
3800 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3801 count = HAMMER2_SET_COUNT;
3804 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3806 base = NULL; /* safety */
3807 count = 0; /* safety */
3809 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3815 * Chain memory management
3818 hammer2_chain_wait(hammer2_chain_t *chain)
3820 tsleep(chain, 0, "chnflw", 1);
3823 const hammer2_media_data_t *
3824 hammer2_chain_rdata(hammer2_chain_t *chain)
3826 KKASSERT(chain->data != NULL);
3827 return (chain->data);
3830 hammer2_media_data_t *
3831 hammer2_chain_wdata(hammer2_chain_t *chain)
3833 KKASSERT(chain->data != NULL);
3834 return (chain->data);
3838 * Set the check data for a chain. This can be a heavy-weight operation
3839 * and typically only runs on-flush. For file data check data is calculated
3840 * when the logical buffers are flushed.
3843 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3845 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3847 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3848 case HAMMER2_CHECK_NONE:
3850 case HAMMER2_CHECK_DISABLED:
3852 case HAMMER2_CHECK_ISCSI32:
3853 chain->bref.check.iscsi32.value =
3854 hammer2_icrc32(bdata, chain->bytes);
3856 case HAMMER2_CHECK_CRC64:
3857 chain->bref.check.crc64.value = 0;
3860 case HAMMER2_CHECK_SHA192:
3862 SHA256_CTX hash_ctx;
3864 uint8_t digest[SHA256_DIGEST_LENGTH];
3865 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3868 SHA256_Init(&hash_ctx);
3869 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3870 SHA256_Final(u.digest, &hash_ctx);
3871 u.digest64[2] ^= u.digest64[3];
3873 chain->bref.check.sha192.data,
3874 sizeof(chain->bref.check.sha192.data));
3877 case HAMMER2_CHECK_FREEMAP:
3878 chain->bref.check.freemap.icrc32 =
3879 hammer2_icrc32(bdata, chain->bytes);
3882 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3883 chain->bref.methods);
3889 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3893 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3896 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3897 case HAMMER2_CHECK_NONE:
3900 case HAMMER2_CHECK_DISABLED:
3903 case HAMMER2_CHECK_ISCSI32:
3904 r = (chain->bref.check.iscsi32.value ==
3905 hammer2_icrc32(bdata, chain->bytes));
3907 case HAMMER2_CHECK_CRC64:
3908 r = (chain->bref.check.crc64.value == 0);
3911 case HAMMER2_CHECK_SHA192:
3913 SHA256_CTX hash_ctx;
3915 uint8_t digest[SHA256_DIGEST_LENGTH];
3916 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3919 SHA256_Init(&hash_ctx);
3920 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3921 SHA256_Final(u.digest, &hash_ctx);
3922 u.digest64[2] ^= u.digest64[3];
3924 chain->bref.check.sha192.data,
3925 sizeof(chain->bref.check.sha192.data)) == 0) {
3932 case HAMMER2_CHECK_FREEMAP:
3933 r = (chain->bref.check.freemap.icrc32 ==
3934 hammer2_icrc32(bdata, chain->bytes));
3936 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3937 chain->bref.check.freemap.icrc32,
3938 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3940 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3941 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3946 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3947 chain->bref.methods);