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 * Ref and lock a chain element, acquiring its data with I/O if necessary,
509 * and specify how you would like the data to be resolved.
511 * Returns 0 on success or an error code if the data could not be acquired.
512 * The chain element is locked on return regardless of whether an error
515 * The lock is allowed to recurse, multiple locking ops will aggregate
516 * the requested resolve types. Once data is assigned it will not be
517 * removed until the last unlock.
519 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
520 * (typically used to avoid device/logical buffer
523 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
524 * the INITIAL-create state (indirect blocks only).
526 * Do not resolve data elements for DATA chains.
527 * (typically used to avoid device/logical buffer
530 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
532 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
533 * it will be locked exclusive.
535 * NOTE: Embedded elements (volume header, inodes) are always resolved
538 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
539 * element will instantiate and zero its buffer, and flush it on
542 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
543 * so as not to instantiate a device buffer, which could alias against
544 * a logical file buffer. However, if ALWAYS is specified the
545 * device buffer will be instantiated anyway.
547 * WARNING! If data must be fetched a shared lock will temporarily be
548 * upgraded to exclusive. However, a deadlock can occur if
549 * the caller owns more than one shared lock.
552 hammer2_chain_lock(hammer2_chain_t *chain, int how)
555 hammer2_blockref_t *bref;
556 hammer2_mtx_state_t ostate;
561 * Ref and lock the element. Recursive locks are allowed.
563 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
564 hammer2_chain_ref(chain);
565 atomic_add_int(&chain->lockcnt, 1);
568 KKASSERT(hmp != NULL);
571 * Get the appropriate lock.
573 if (how & HAMMER2_RESOLVE_SHARED)
574 hammer2_mtx_sh(&chain->core.lock);
576 hammer2_mtx_ex(&chain->core.lock);
579 * If we already have a valid data pointer no further action is
586 * Do we have to resolve the data?
588 switch(how & HAMMER2_RESOLVE_MASK) {
589 case HAMMER2_RESOLVE_NEVER:
591 case HAMMER2_RESOLVE_MAYBE:
592 if (chain->flags & HAMMER2_CHAIN_INITIAL)
594 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
597 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
599 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
603 case HAMMER2_RESOLVE_ALWAYS:
608 * Upgrade to an exclusive lock so we can safely manipulate the
609 * buffer cache. If another thread got to it before us we
612 ostate = hammer2_mtx_upgrade(&chain->core.lock);
614 hammer2_mtx_downgrade(&chain->core.lock, ostate);
619 * We must resolve to a device buffer, either by issuing I/O or
620 * by creating a zero-fill element. We do not mark the buffer
621 * dirty when creating a zero-fill element (the hammer2_chain_modify()
622 * API must still be used to do that).
624 * The device buffer is variable-sized in powers of 2 down
625 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
626 * chunk always contains buffers of the same size. (XXX)
628 * The minimum physical IO size may be larger than the variable
634 * The getblk() optimization can only be used on newly created
635 * elements if the physical block size matches the request.
637 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
638 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
641 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
643 hammer2_adjreadcounter(&chain->bref, chain->bytes);
646 chain->error = HAMMER2_ERROR_IO;
647 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
648 (intmax_t)bref->data_off, error);
649 hammer2_io_bqrelse(&chain->dio);
650 hammer2_mtx_downgrade(&chain->core.lock, ostate);
656 * NOTE: A locked chain's data cannot be modified without first
657 * calling hammer2_chain_modify().
661 * Clear INITIAL. In this case we used io_new() and the buffer has
662 * been zero'd and marked dirty.
664 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
665 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
666 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
667 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
668 } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
670 * check data not currently synchronized due to
671 * modification. XXX assumes data stays in the buffer
672 * cache, which might not be true (need biodep on flush
673 * to calculate crc? or simple crc?).
676 if (hammer2_chain_testcheck(chain, bdata) == 0) {
677 kprintf("chain %016jx.%02x meth=%02x "
678 "CHECK FAIL %08x (flags=%08x)\n",
679 chain->bref.data_off,
682 hammer2_icrc32(bdata, chain->bytes),
684 chain->error = HAMMER2_ERROR_CHECK;
689 * Setup the data pointer, either pointing it to an embedded data
690 * structure and copying the data from the buffer, or pointing it
693 * The buffer is not retained when copying to an embedded data
694 * structure in order to avoid potential deadlocks or recursions
695 * on the same physical buffer.
697 switch (bref->type) {
698 case HAMMER2_BREF_TYPE_VOLUME:
699 case HAMMER2_BREF_TYPE_FREEMAP:
701 * Copy data from bp to embedded buffer
703 panic("hammer2_chain_lock: called on unresolved volume header");
705 case HAMMER2_BREF_TYPE_INODE:
706 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
707 case HAMMER2_BREF_TYPE_INDIRECT:
708 case HAMMER2_BREF_TYPE_DATA:
709 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
712 * Point data at the device buffer and leave dio intact.
714 chain->data = (void *)bdata;
717 hammer2_mtx_downgrade(&chain->core.lock, ostate);
721 * Unlock and deref a chain element.
723 * On the last lock release any non-embedded data (chain->dio) will be
727 hammer2_chain_unlock(hammer2_chain_t *chain)
729 hammer2_mtx_state_t ostate;
734 * If multiple locks are present (or being attempted) on this
735 * particular chain we can just unlock, drop refs, and return.
737 * Otherwise fall-through on the 1->0 transition.
740 lockcnt = chain->lockcnt;
741 KKASSERT(lockcnt > 0);
744 if (atomic_cmpset_int(&chain->lockcnt,
745 lockcnt, lockcnt - 1)) {
746 hammer2_mtx_unlock(&chain->core.lock);
747 hammer2_chain_drop(chain);
751 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
758 * On the 1->0 transition we upgrade the core lock (if necessary)
759 * to exclusive for terminal processing. If after upgrading we find
760 * that lockcnt is non-zero, another thread is racing us and will
761 * handle the unload for us later on, so just cleanup and return
762 * leaving the data/io intact
764 * Otherwise if lockcnt is still 0 it is possible for it to become
765 * non-zero and race, but since we hold the core->lock exclusively
766 * all that will happen is that the chain will be reloaded after we
769 ostate = hammer2_mtx_upgrade(&chain->core.lock);
770 if (chain->lockcnt) {
771 hammer2_mtx_unlock(&chain->core.lock);
772 hammer2_chain_drop(chain);
777 * Shortcut the case if the data is embedded or not resolved.
779 * Do NOT NULL out chain->data (e.g. inode data), it might be
782 if (chain->dio == NULL) {
783 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
784 hammer2_chain_drop_data(chain, 0);
785 hammer2_mtx_unlock(&chain->core.lock);
786 hammer2_chain_drop(chain);
793 if (hammer2_io_isdirty(chain->dio) == 0) {
795 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
796 switch(chain->bref.type) {
797 case HAMMER2_BREF_TYPE_DATA:
798 counterp = &hammer2_ioa_file_write;
800 case HAMMER2_BREF_TYPE_INODE:
801 counterp = &hammer2_ioa_meta_write;
803 case HAMMER2_BREF_TYPE_INDIRECT:
804 counterp = &hammer2_ioa_indr_write;
806 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
807 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
808 counterp = &hammer2_ioa_fmap_write;
811 counterp = &hammer2_ioa_volu_write;
814 *counterp += chain->bytes;
816 switch(chain->bref.type) {
817 case HAMMER2_BREF_TYPE_DATA:
818 counterp = &hammer2_iod_file_write;
820 case HAMMER2_BREF_TYPE_INODE:
821 counterp = &hammer2_iod_meta_write;
823 case HAMMER2_BREF_TYPE_INDIRECT:
824 counterp = &hammer2_iod_indr_write;
826 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
827 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
828 counterp = &hammer2_iod_fmap_write;
831 counterp = &hammer2_iod_volu_write;
834 *counterp += chain->bytes;
840 * If a device buffer was used for data be sure to destroy the
841 * buffer when we are done to avoid aliases (XXX what about the
842 * underlying VM pages?).
844 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
847 * NOTE: The isdirty check tracks whether we have to bdwrite() the
848 * buffer or not. The buffer might already be dirty. The
849 * flag is re-set when chain_modify() is called, even if
850 * MODIFIED is already set, allowing the OS to retire the
851 * buffer independent of a hammer2 flush.
854 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
855 hammer2_io_isdirty(chain->dio)) {
856 hammer2_io_bawrite(&chain->dio);
858 hammer2_io_bqrelse(&chain->dio);
860 hammer2_mtx_unlock(&chain->core.lock);
861 hammer2_chain_drop(chain);
865 * This counts the number of live blockrefs in a block array and
866 * also calculates the point at which all remaining blockrefs are empty.
867 * This routine can only be called on a live chain (DUPLICATED flag not set).
869 * NOTE: Flag is not set until after the count is complete, allowing
870 * callers to test the flag without holding the spinlock.
872 * NOTE: If base is NULL the related chain is still in the INITIAL
873 * state and there are no blockrefs to count.
875 * NOTE: live_count may already have some counts accumulated due to
876 * creation and deletion and could even be initially negative.
879 hammer2_chain_countbrefs(hammer2_chain_t *chain,
880 hammer2_blockref_t *base, int count)
882 hammer2_spin_ex(&chain->core.spin);
883 if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
885 while (--count >= 0) {
886 if (base[count].type)
889 chain->core.live_zero = count + 1;
891 if (base[count].type)
892 atomic_add_int(&chain->core.live_count,
897 chain->core.live_zero = 0;
899 /* else do not modify live_count */
900 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
902 hammer2_spin_unex(&chain->core.spin);
906 * Resize the chain's physical storage allocation in-place. This function does
907 * not adjust the data pointer and must be followed by (typically) a
908 * hammer2_chain_modify() call to copy any old data over and adjust the
911 * Chains can be resized smaller without reallocating the storage. Resizing
912 * larger will reallocate the storage. Excess or prior storage is reclaimed
913 * asynchronously at a later time.
915 * Must be passed an exclusively locked parent and chain.
917 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
918 * to avoid instantiating a device buffer that conflicts with the vnode data
919 * buffer. However, because H2 can compress or encrypt data, the chain may
920 * have a dio assigned to it in those situations, and they do not conflict.
922 * XXX return error if cannot resize.
925 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
926 hammer2_chain_t *parent, hammer2_chain_t *chain,
927 int nradix, int flags)
936 * Only data and indirect blocks can be resized for now.
937 * (The volu root, inodes, and freemap elements use a fixed size).
939 KKASSERT(chain != &hmp->vchain);
940 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
941 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
944 * Nothing to do if the element is already the proper size
946 obytes = chain->bytes;
947 nbytes = 1U << nradix;
948 if (obytes == nbytes)
950 chain->data_count += (ssize_t)(nbytes - obytes);
953 * Make sure the old data is instantiated so we can copy it. If this
954 * is a data block, the device data may be superfluous since the data
955 * might be in a logical block, but compressed or encrypted data is
958 * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
960 hammer2_chain_modify(trans, chain, 0);
963 * Relocate the block, even if making it smaller (because different
964 * block sizes may be in different regions).
966 * (data blocks only, we aren't copying the storage here).
968 hammer2_freemap_alloc(trans, chain, nbytes);
969 chain->bytes = nbytes;
970 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
973 * We don't want the followup chain_modify() to try to copy data
974 * from the old (wrong-sized) buffer. It won't know how much to
975 * copy. This case should only occur during writes when the
976 * originator already has the data to write in-hand.
979 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
980 hammer2_io_brelse(&chain->dio);
986 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
988 hammer2_blockref_t obref;
1000 * Data is not optional for freemap chains (we must always be sure
1001 * to copy the data on COW storage allocations).
1003 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1004 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1005 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1006 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1010 * Data must be resolved if already assigned unless explicitly
1011 * flagged otherwise.
1013 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1014 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1015 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1016 hammer2_chain_unlock(chain);
1020 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1021 * that the chain has been modified. Set UPDATE to ensure that
1022 * the blockref is updated in the parent.
1024 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1025 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1026 hammer2_chain_ref(chain);
1027 hammer2_pfs_memory_inc(chain->pmp); /* can be NULL */
1032 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1033 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1034 hammer2_chain_ref(chain);
1038 * The modification or re-modification requires an allocation and
1041 * We normally always allocate new storage here. If storage exists
1042 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1044 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1045 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1046 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1048 hammer2_freemap_alloc(trans, chain, chain->bytes);
1049 /* XXX failed allocation */
1054 * Set BMAPUPD to tell the flush code that an existing blockmap entry
1055 * requires updating as well as to tell the delete code that the
1056 * chain's blockref might not exactly match (in terms of physical size
1057 * or block offset) the one in the parent's blocktable. The base key
1058 * of course will still match.
1060 if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1061 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1064 * Short-cut data blocks which the caller does not need an actual
1065 * data reference to (aka OPTDATA), as long as the chain does not
1066 * already have a data pointer to the data. This generally means
1067 * that the modifications are being done via the logical buffer cache.
1068 * The INITIAL flag relates only to the device data buffer and thus
1069 * remains unchange in this situation.
1071 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1072 (flags & HAMMER2_MODIFY_OPTDATA) &&
1073 chain->data == NULL) {
1078 * Clearing the INITIAL flag (for indirect blocks) indicates that
1079 * we've processed the uninitialized storage allocation.
1081 * If this flag is already clear we are likely in a copy-on-write
1082 * situation but we have to be sure NOT to bzero the storage if
1083 * no data is present.
1085 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1086 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1093 * Instantiate data buffer and possibly execute COW operation
1095 switch(chain->bref.type) {
1096 case HAMMER2_BREF_TYPE_VOLUME:
1097 case HAMMER2_BREF_TYPE_FREEMAP:
1099 * The data is embedded, no copy-on-write operation is
1102 KKASSERT(chain->dio == NULL);
1104 case HAMMER2_BREF_TYPE_INODE:
1105 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1106 case HAMMER2_BREF_TYPE_DATA:
1107 case HAMMER2_BREF_TYPE_INDIRECT:
1108 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1110 * Perform the copy-on-write operation
1112 * zero-fill or copy-on-write depending on whether
1113 * chain->data exists or not and set the dirty state for
1114 * the new buffer. hammer2_io_new() will handle the
1117 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1120 error = hammer2_io_new(hmp, chain->bref.data_off,
1121 chain->bytes, &dio);
1123 error = hammer2_io_bread(hmp, chain->bref.data_off,
1124 chain->bytes, &dio);
1126 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1129 * If an I/O error occurs make sure callers cannot accidently
1130 * modify the old buffer's contents and corrupt the filesystem.
1133 kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1135 chain->error = HAMMER2_ERROR_IO;
1136 hammer2_io_brelse(&dio);
1137 hammer2_io_brelse(&chain->dio);
1142 bdata = hammer2_io_data(dio, chain->bref.data_off);
1145 KKASSERT(chain->dio != NULL);
1146 if (chain->data != (void *)bdata) {
1147 bcopy(chain->data, bdata, chain->bytes);
1149 } else if (wasinitial == 0) {
1151 * We have a problem. We were asked to COW but
1152 * we don't have any data to COW with!
1154 panic("hammer2_chain_modify: having a COW %p\n",
1159 * Retire the old buffer, replace with the new. Dirty or
1160 * redirty the new buffer.
1162 * WARNING! The system buffer cache may have already flushed
1163 * the buffer, so we must be sure to [re]dirty it
1164 * for further modification.
1167 hammer2_io_brelse(&chain->dio);
1168 chain->data = (void *)bdata;
1170 hammer2_io_setdirty(dio); /* modified by bcopy above */
1173 panic("hammer2_chain_modify: illegal non-embedded type %d",
1180 * setflush on parent indicating that the parent must recurse down
1181 * to us. Do not call on chain itself which might already have it
1185 hammer2_chain_setflush(trans, chain->parent);
1189 * Volume header data locks
1192 hammer2_voldata_lock(hammer2_dev_t *hmp)
1194 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1198 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1200 lockmgr(&hmp->vollk, LK_RELEASE);
1204 hammer2_voldata_modify(hammer2_dev_t *hmp)
1206 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1207 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1208 hammer2_chain_ref(&hmp->vchain);
1209 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1214 * This function returns the chain at the nearest key within the specified
1215 * range. The returned chain will be referenced but not locked.
1217 * This function will recurse through chain->rbtree as necessary and will
1218 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1219 * the iteration value is less than the current value of *key_nextp.
1221 * The caller should use (*key_nextp) to calculate the actual range of
1222 * the returned element, which will be (key_beg to *key_nextp - 1), because
1223 * there might be another element which is superior to the returned element
1226 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1227 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1228 * it will wind up being (key_end + 1).
1230 * WARNING! Must be called with child's spinlock held. Spinlock remains
1231 * held through the operation.
1233 struct hammer2_chain_find_info {
1234 hammer2_chain_t *best;
1235 hammer2_key_t key_beg;
1236 hammer2_key_t key_end;
1237 hammer2_key_t key_next;
1240 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1241 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1245 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1246 hammer2_key_t key_beg, hammer2_key_t key_end)
1248 struct hammer2_chain_find_info info;
1251 info.key_beg = key_beg;
1252 info.key_end = key_end;
1253 info.key_next = *key_nextp;
1255 RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1256 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1258 *key_nextp = info.key_next;
1260 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1261 parent, key_beg, key_end, *key_nextp);
1269 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1271 struct hammer2_chain_find_info *info = data;
1272 hammer2_key_t child_beg;
1273 hammer2_key_t child_end;
1275 child_beg = child->bref.key;
1276 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1278 if (child_end < info->key_beg)
1280 if (child_beg > info->key_end)
1287 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1289 struct hammer2_chain_find_info *info = data;
1290 hammer2_chain_t *best;
1291 hammer2_key_t child_end;
1294 * WARNING! Do not discard DUPLICATED chains, it is possible that
1295 * we are catching an insertion half-way done. If a
1296 * duplicated chain turns out to be the best choice the
1297 * caller will re-check its flags after locking it.
1299 * WARNING! Layerq is scanned forwards, exact matches should keep
1300 * the existing info->best.
1302 if ((best = info->best) == NULL) {
1304 * No previous best. Assign best
1307 } else if (best->bref.key <= info->key_beg &&
1308 child->bref.key <= info->key_beg) {
1313 /*info->best = child;*/
1314 } else if (child->bref.key < best->bref.key) {
1316 * Child has a nearer key and best is not flush with key_beg.
1317 * Set best to child. Truncate key_next to the old best key.
1320 if (info->key_next > best->bref.key || info->key_next == 0)
1321 info->key_next = best->bref.key;
1322 } else if (child->bref.key == best->bref.key) {
1324 * If our current best is flush with the child then this
1325 * is an illegal overlap.
1327 * key_next will automatically be limited to the smaller of
1328 * the two end-points.
1334 * Keep the current best but truncate key_next to the child's
1337 * key_next will also automatically be limited to the smaller
1338 * of the two end-points (probably not necessary for this case
1339 * but we do it anyway).
1341 if (info->key_next > child->bref.key || info->key_next == 0)
1342 info->key_next = child->bref.key;
1346 * Always truncate key_next based on child's end-of-range.
1348 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1349 if (child_end && (info->key_next > child_end || info->key_next == 0))
1350 info->key_next = child_end;
1356 * Retrieve the specified chain from a media blockref, creating the
1357 * in-memory chain structure which reflects it.
1359 * To handle insertion races pass the INSERT_RACE flag along with the
1360 * generation number of the core. NULL will be returned if the generation
1361 * number changes before we have a chance to insert the chain. Insert
1362 * races can occur because the parent might be held shared.
1364 * Caller must hold the parent locked shared or exclusive since we may
1365 * need the parent's bref array to find our block.
1367 * WARNING! chain->pmp is always set to NULL for any chain representing
1368 * part of the super-root topology.
1371 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1372 hammer2_blockref_t *bref)
1374 hammer2_dev_t *hmp = parent->hmp;
1375 hammer2_chain_t *chain;
1379 * Allocate a chain structure representing the existing media
1380 * entry. Resulting chain has one ref and is not locked.
1382 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1383 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1385 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1386 /* ref'd chain returned */
1389 * Flag that the chain is in the parent's blockmap so delete/flush
1390 * knows what to do with it.
1392 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1395 * Link the chain into its parent. A spinlock is required to safely
1396 * access the RBTREE, and it is possible to collide with another
1397 * hammer2_chain_get() operation because the caller might only hold
1398 * a shared lock on the parent.
1400 KKASSERT(parent->refs > 0);
1401 error = hammer2_chain_insert(parent, chain,
1402 HAMMER2_CHAIN_INSERT_SPIN |
1403 HAMMER2_CHAIN_INSERT_RACE,
1406 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1407 kprintf("chain %p get race\n", chain);
1408 hammer2_chain_drop(chain);
1411 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1415 * Return our new chain referenced but not locked, or NULL if
1422 * Lookup initialization/completion API
1425 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1427 if (flags & HAMMER2_LOOKUP_SHARED) {
1428 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1429 HAMMER2_RESOLVE_SHARED);
1431 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1437 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1440 hammer2_chain_unlock(parent);
1445 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1447 hammer2_chain_t *oparent;
1448 hammer2_chain_t *nparent;
1451 * Be careful of order, oparent must be unlocked before nparent
1452 * is locked below to avoid a deadlock.
1455 hammer2_spin_ex(&oparent->core.spin);
1456 nparent = oparent->parent;
1457 hammer2_chain_ref(nparent);
1458 hammer2_spin_unex(&oparent->core.spin);
1460 hammer2_chain_unlock(oparent);
1464 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1471 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1472 * (*parentp) typically points to an inode but can also point to a related
1473 * indirect block and this function will recurse upwards and find the inode
1476 * (*parentp) must be exclusively locked and referenced and can be an inode
1477 * or an existing indirect block within the inode.
1479 * On return (*parentp) will be modified to point at the deepest parent chain
1480 * element encountered during the search, as a helper for an insertion or
1481 * deletion. The new (*parentp) will be locked and referenced and the old
1482 * will be unlocked and dereferenced (no change if they are both the same).
1484 * The matching chain will be returned exclusively locked. If NOLOCK is
1485 * requested the chain will be returned only referenced.
1487 * NULL is returned if no match was found, but (*parentp) will still
1488 * potentially be adjusted.
1490 * On return (*key_nextp) will point to an iterative value for key_beg.
1491 * (If NULL is returned (*key_nextp) is set to key_end).
1493 * This function will also recurse up the chain if the key is not within the
1494 * current parent's range. (*parentp) can never be set to NULL. An iteration
1495 * can simply allow (*parentp) to float inside the loop.
1497 * NOTE! chain->data is not always resolved. By default it will not be
1498 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1499 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1500 * BREF_TYPE_DATA as the device buffer can alias the logical file
1504 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1505 hammer2_key_t key_beg, hammer2_key_t key_end,
1506 int *cache_indexp, int flags)
1509 hammer2_chain_t *parent;
1510 hammer2_chain_t *chain;
1511 hammer2_blockref_t *base;
1512 hammer2_blockref_t *bref;
1513 hammer2_blockref_t bcopy;
1514 hammer2_key_t scan_beg;
1515 hammer2_key_t scan_end;
1517 int how_always = HAMMER2_RESOLVE_ALWAYS;
1518 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1521 int maxloops = 300000;
1523 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1524 how_maybe = how_always;
1525 how = HAMMER2_RESOLVE_ALWAYS;
1526 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1527 how = HAMMER2_RESOLVE_NEVER;
1529 how = HAMMER2_RESOLVE_MAYBE;
1531 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1532 how_maybe |= HAMMER2_RESOLVE_SHARED;
1533 how_always |= HAMMER2_RESOLVE_SHARED;
1534 how |= HAMMER2_RESOLVE_SHARED;
1538 * Recurse (*parentp) upward if necessary until the parent completely
1539 * encloses the key range or we hit the inode.
1541 * This function handles races against the flusher doing a delete-
1542 * duplicate above us and re-homes the parent to the duplicate in
1543 * that case, otherwise we'd wind up recursing down a stale chain.
1548 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1549 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1550 scan_beg = parent->bref.key;
1551 scan_end = scan_beg +
1552 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1553 if (key_beg >= scan_beg && key_end <= scan_end)
1555 parent = hammer2_chain_getparent(parentp, how_maybe);
1559 if (--maxloops == 0)
1560 panic("hammer2_chain_lookup: maxloops");
1562 * Locate the blockref array. Currently we do a fully associative
1563 * search through the array.
1565 switch(parent->bref.type) {
1566 case HAMMER2_BREF_TYPE_INODE:
1568 * Special shortcut for embedded data returns the inode
1569 * itself. Callers must detect this condition and access
1570 * the embedded data (the strategy code does this for us).
1572 * This is only applicable to regular files and softlinks.
1574 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1575 if (flags & HAMMER2_LOOKUP_NOLOCK)
1576 hammer2_chain_ref(parent);
1578 hammer2_chain_lock(parent, how_always);
1579 *key_nextp = key_end + 1;
1582 base = &parent->data->ipdata.u.blockset.blockref[0];
1583 count = HAMMER2_SET_COUNT;
1585 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1586 case HAMMER2_BREF_TYPE_INDIRECT:
1588 * Handle MATCHIND on the parent
1590 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1591 scan_beg = parent->bref.key;
1592 scan_end = scan_beg +
1593 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1594 if (key_beg == scan_beg && key_end == scan_end) {
1596 hammer2_chain_lock(chain, how_maybe);
1597 *key_nextp = scan_end + 1;
1602 * Optimize indirect blocks in the INITIAL state to avoid
1605 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1608 if (parent->data == NULL)
1609 panic("parent->data is NULL");
1610 base = &parent->data->npdata[0];
1612 count = parent->bytes / sizeof(hammer2_blockref_t);
1614 case HAMMER2_BREF_TYPE_VOLUME:
1615 base = &hmp->voldata.sroot_blockset.blockref[0];
1616 count = HAMMER2_SET_COUNT;
1618 case HAMMER2_BREF_TYPE_FREEMAP:
1619 base = &hmp->voldata.freemap_blockset.blockref[0];
1620 count = HAMMER2_SET_COUNT;
1623 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1625 base = NULL; /* safety */
1626 count = 0; /* safety */
1630 * Merged scan to find next candidate.
1632 * hammer2_base_*() functions require the parent->core.live_* fields
1633 * to be synchronized.
1635 * We need to hold the spinlock to access the block array and RB tree
1636 * and to interlock chain creation.
1638 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1639 hammer2_chain_countbrefs(parent, base, count);
1644 hammer2_spin_ex(&parent->core.spin);
1645 chain = hammer2_combined_find(parent, base, count,
1646 cache_indexp, key_nextp,
1649 generation = parent->core.generation;
1652 * Exhausted parent chain, iterate.
1655 hammer2_spin_unex(&parent->core.spin);
1656 if (key_beg == key_end) /* short cut single-key case */
1660 * Stop if we reached the end of the iteration.
1662 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1663 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1668 * Calculate next key, stop if we reached the end of the
1669 * iteration, otherwise go up one level and loop.
1671 key_beg = parent->bref.key +
1672 ((hammer2_key_t)1 << parent->bref.keybits);
1673 if (key_beg == 0 || key_beg > key_end)
1675 parent = hammer2_chain_getparent(parentp, how_maybe);
1680 * Selected from blockref or in-memory chain.
1682 if (chain == NULL) {
1684 hammer2_spin_unex(&parent->core.spin);
1685 chain = hammer2_chain_get(parent, generation,
1687 if (chain == NULL) {
1688 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1689 parent, key_beg, key_end);
1692 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1693 hammer2_chain_drop(chain);
1697 hammer2_chain_ref(chain);
1698 hammer2_spin_unex(&parent->core.spin);
1702 * chain is referenced but not locked. We must lock the chain
1703 * to obtain definitive DUPLICATED/DELETED state
1705 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1706 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1707 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1709 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1713 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1715 * NOTE: Chain's key range is not relevant as there might be
1716 * one-offs within the range that are not deleted.
1718 * NOTE: Lookups can race delete-duplicate because
1719 * delete-duplicate does not lock the parent's core
1720 * (they just use the spinlock on the core). We must
1721 * check for races by comparing the DUPLICATED flag before
1722 * releasing the spinlock with the flag after locking the
1725 if (chain->flags & HAMMER2_CHAIN_DELETED) {
1726 hammer2_chain_unlock(chain);
1727 key_beg = *key_nextp;
1728 if (key_beg == 0 || key_beg > key_end)
1734 * If the chain element is an indirect block it becomes the new
1735 * parent and we loop on it. We must maintain our top-down locks
1736 * to prevent the flusher from interfering (i.e. doing a
1737 * delete-duplicate and leaving us recursing down a deleted chain).
1739 * The parent always has to be locked with at least RESOLVE_MAYBE
1740 * so we can access its data. It might need a fixup if the caller
1741 * passed incompatible flags. Be careful not to cause a deadlock
1742 * as a data-load requires an exclusive lock.
1744 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1745 * range is within the requested key range we return the indirect
1746 * block and do NOT loop. This is usually only used to acquire
1749 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1750 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1751 hammer2_chain_unlock(parent);
1752 *parentp = parent = chain;
1757 * All done, return the chain
1763 * After having issued a lookup we can iterate all matching keys.
1765 * If chain is non-NULL we continue the iteration from just after it's index.
1767 * If chain is NULL we assume the parent was exhausted and continue the
1768 * iteration at the next parent.
1770 * parent must be locked on entry and remains locked throughout. chain's
1771 * lock status must match flags. Chain is always at least referenced.
1773 * WARNING! The MATCHIND flag does not apply to this function.
1776 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1777 hammer2_key_t *key_nextp,
1778 hammer2_key_t key_beg, hammer2_key_t key_end,
1779 int *cache_indexp, int flags)
1781 hammer2_chain_t *parent;
1785 * Calculate locking flags for upward recursion.
1787 how_maybe = HAMMER2_RESOLVE_MAYBE;
1788 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1789 how_maybe |= HAMMER2_RESOLVE_SHARED;
1794 * Calculate the next index and recalculate the parent if necessary.
1797 key_beg = chain->bref.key +
1798 ((hammer2_key_t)1 << chain->bref.keybits);
1799 if (flags & HAMMER2_LOOKUP_NOLOCK)
1800 hammer2_chain_drop(chain);
1802 hammer2_chain_unlock(chain);
1805 * Any scan where the lookup returned degenerate data embedded
1806 * in the inode has an invalid index and must terminate.
1808 if (chain == parent)
1810 if (key_beg == 0 || key_beg > key_end)
1813 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1814 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1816 * We reached the end of the iteration.
1821 * Continue iteration with next parent unless the current
1822 * parent covers the range.
1824 key_beg = parent->bref.key +
1825 ((hammer2_key_t)1 << parent->bref.keybits);
1826 if (key_beg == 0 || key_beg > key_end)
1828 parent = hammer2_chain_getparent(parentp, how_maybe);
1834 return (hammer2_chain_lookup(parentp, key_nextp,
1836 cache_indexp, flags));
1840 * The raw scan function is similar to lookup/next but does not seek to a key.
1841 * Blockrefs are iterated via first_chain = (parent, NULL) and
1842 * next_chain = (parent, chain).
1844 * The passed-in parent must be locked and its data resolved. The returned
1845 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
1846 * under parent and then iterate with the passed-in chain (which this
1847 * function will unlock).
1850 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1851 int *cache_indexp, int flags)
1854 hammer2_blockref_t *base;
1855 hammer2_blockref_t *bref;
1856 hammer2_blockref_t bcopy;
1858 hammer2_key_t next_key;
1860 int how_always = HAMMER2_RESOLVE_ALWAYS;
1861 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1864 int maxloops = 300000;
1869 * Scan flags borrowed from lookup
1871 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1872 how_maybe = how_always;
1873 how = HAMMER2_RESOLVE_ALWAYS;
1874 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1875 how = HAMMER2_RESOLVE_NEVER;
1877 how = HAMMER2_RESOLVE_MAYBE;
1879 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1880 how_maybe |= HAMMER2_RESOLVE_SHARED;
1881 how_always |= HAMMER2_RESOLVE_SHARED;
1882 how |= HAMMER2_RESOLVE_SHARED;
1886 * Calculate key to locate first/next element, unlocking the previous
1887 * element as we go. Be careful, the key calculation can overflow.
1890 key = chain->bref.key +
1891 ((hammer2_key_t)1 << chain->bref.keybits);
1892 hammer2_chain_unlock(chain);
1901 if (--maxloops == 0)
1902 panic("hammer2_chain_scan: maxloops");
1904 * Locate the blockref array. Currently we do a fully associative
1905 * search through the array.
1907 switch(parent->bref.type) {
1908 case HAMMER2_BREF_TYPE_INODE:
1910 * An inode with embedded data has no sub-chains.
1912 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1914 base = &parent->data->ipdata.u.blockset.blockref[0];
1915 count = HAMMER2_SET_COUNT;
1917 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1918 case HAMMER2_BREF_TYPE_INDIRECT:
1920 * Optimize indirect blocks in the INITIAL state to avoid
1923 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1926 if (parent->data == NULL)
1927 panic("parent->data is NULL");
1928 base = &parent->data->npdata[0];
1930 count = parent->bytes / sizeof(hammer2_blockref_t);
1932 case HAMMER2_BREF_TYPE_VOLUME:
1933 base = &hmp->voldata.sroot_blockset.blockref[0];
1934 count = HAMMER2_SET_COUNT;
1936 case HAMMER2_BREF_TYPE_FREEMAP:
1937 base = &hmp->voldata.freemap_blockset.blockref[0];
1938 count = HAMMER2_SET_COUNT;
1941 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1943 base = NULL; /* safety */
1944 count = 0; /* safety */
1948 * Merged scan to find next candidate.
1950 * hammer2_base_*() functions require the parent->core.live_* fields
1951 * to be synchronized.
1953 * We need to hold the spinlock to access the block array and RB tree
1954 * and to interlock chain creation.
1956 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1957 hammer2_chain_countbrefs(parent, base, count);
1960 hammer2_spin_ex(&parent->core.spin);
1961 chain = hammer2_combined_find(parent, base, count,
1962 cache_indexp, &next_key,
1963 key, HAMMER2_KEY_MAX,
1965 generation = parent->core.generation;
1968 * Exhausted parent chain, we're done.
1971 hammer2_spin_unex(&parent->core.spin);
1972 KKASSERT(chain == NULL);
1977 * Selected from blockref or in-memory chain.
1979 if (chain == NULL) {
1981 hammer2_spin_unex(&parent->core.spin);
1982 chain = hammer2_chain_get(parent, generation, &bcopy);
1983 if (chain == NULL) {
1984 kprintf("retry scan parent %p keys %016jx\n",
1988 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1989 hammer2_chain_drop(chain);
1994 hammer2_chain_ref(chain);
1995 hammer2_spin_unex(&parent->core.spin);
1999 * chain is referenced but not locked. We must lock the chain
2000 * to obtain definitive DUPLICATED/DELETED state
2002 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2005 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2007 * NOTE: chain's key range is not relevant as there might be
2008 * one-offs within the range that are not deleted.
2010 * NOTE: XXX this could create problems with scans used in
2011 * situations other than mount-time recovery.
2013 * NOTE: Lookups can race delete-duplicate because
2014 * delete-duplicate does not lock the parent's core
2015 * (they just use the spinlock on the core). We must
2016 * check for races by comparing the DUPLICATED flag before
2017 * releasing the spinlock with the flag after locking the
2020 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2021 hammer2_chain_unlock(chain);
2032 * All done, return the chain or NULL
2038 * Create and return a new hammer2 system memory structure of the specified
2039 * key, type and size and insert it under (*parentp). This is a full
2040 * insertion, based on the supplied key/keybits, and may involve creating
2041 * indirect blocks and moving other chains around via delete/duplicate.
2043 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2044 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2045 * FULL. This typically means that the caller is creating the chain after
2046 * doing a hammer2_chain_lookup().
2048 * (*parentp) must be exclusive locked and may be replaced on return
2049 * depending on how much work the function had to do.
2051 * (*chainp) usually starts out NULL and returns the newly created chain,
2052 * but if the caller desires the caller may allocate a disconnected chain
2053 * and pass it in instead.
2055 * This function should NOT be used to insert INDIRECT blocks. It is
2056 * typically used to create/insert inodes and data blocks.
2058 * Caller must pass-in an exclusively locked parent the new chain is to
2059 * be inserted under, and optionally pass-in a disconnected, exclusively
2060 * locked chain to insert (else we create a new chain). The function will
2061 * adjust (*parentp) as necessary, create or connect the chain, and
2062 * return an exclusively locked chain in *chainp.
2064 * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2065 * and will be reassigned.
2068 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2069 hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2070 hammer2_key_t key, int keybits, int type, size_t bytes,
2074 hammer2_chain_t *chain;
2075 hammer2_chain_t *parent;
2076 hammer2_blockref_t *base;
2077 hammer2_blockref_t dummy;
2081 int maxloops = 300000;
2084 * Topology may be crossing a PFS boundary.
2087 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2091 if (chain == NULL) {
2093 * First allocate media space and construct the dummy bref,
2094 * then allocate the in-memory chain structure. Set the
2095 * INITIAL flag for fresh chains which do not have embedded
2098 bzero(&dummy, sizeof(dummy));
2101 dummy.keybits = keybits;
2102 dummy.data_off = hammer2_getradix(bytes);
2103 dummy.methods = parent->bref.methods;
2104 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2107 * Lock the chain manually, chain_lock will load the chain
2108 * which we do NOT want to do. (note: chain->refs is set
2109 * to 1 by chain_alloc() for us, but lockcnt is not).
2112 hammer2_mtx_ex(&chain->core.lock);
2116 * We do NOT set INITIAL here (yet). INITIAL is only
2117 * used for indirect blocks.
2119 * Recalculate bytes to reflect the actual media block
2122 bytes = (hammer2_off_t)1 <<
2123 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2124 chain->bytes = bytes;
2127 case HAMMER2_BREF_TYPE_VOLUME:
2128 case HAMMER2_BREF_TYPE_FREEMAP:
2129 panic("hammer2_chain_create: called with volume type");
2131 case HAMMER2_BREF_TYPE_INDIRECT:
2132 panic("hammer2_chain_create: cannot be used to"
2133 "create indirect block");
2135 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2136 panic("hammer2_chain_create: cannot be used to"
2137 "create freemap root or node");
2139 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2140 KKASSERT(bytes == sizeof(chain->data->bmdata));
2142 case HAMMER2_BREF_TYPE_INODE:
2143 case HAMMER2_BREF_TYPE_DATA:
2146 * leave chain->data NULL, set INITIAL
2148 KKASSERT(chain->data == NULL);
2149 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2154 * Set statistics for pending updates. These will be
2155 * synchronized by the flush code.
2158 case HAMMER2_BREF_TYPE_INODE:
2159 chain->inode_count = 1;
2161 case HAMMER2_BREF_TYPE_DATA:
2162 case HAMMER2_BREF_TYPE_INDIRECT:
2163 chain->data_count = chain->bytes;
2168 * We are reattaching a previously deleted chain, possibly
2169 * under a new parent and possibly with a new key/keybits.
2170 * The chain does not have to be in a modified state. The
2171 * UPDATE flag will be set later on in this routine.
2173 * Do NOT mess with the current state of the INITIAL flag.
2175 chain->bref.key = key;
2176 chain->bref.keybits = keybits;
2177 if (chain->flags & HAMMER2_CHAIN_DELETED)
2178 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2179 KKASSERT(chain->parent == NULL);
2181 if (flags & HAMMER2_INSERT_PFSROOT)
2182 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2184 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2187 * Calculate how many entries we have in the blockref array and
2188 * determine if an indirect block is required.
2191 if (--maxloops == 0)
2192 panic("hammer2_chain_create: maxloops");
2194 switch(parent->bref.type) {
2195 case HAMMER2_BREF_TYPE_INODE:
2196 KKASSERT((parent->data->ipdata.op_flags &
2197 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2198 KKASSERT(parent->data != NULL);
2199 base = &parent->data->ipdata.u.blockset.blockref[0];
2200 count = HAMMER2_SET_COUNT;
2202 case HAMMER2_BREF_TYPE_INDIRECT:
2203 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2204 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2207 base = &parent->data->npdata[0];
2208 count = parent->bytes / sizeof(hammer2_blockref_t);
2210 case HAMMER2_BREF_TYPE_VOLUME:
2211 KKASSERT(parent->data != NULL);
2212 base = &hmp->voldata.sroot_blockset.blockref[0];
2213 count = HAMMER2_SET_COUNT;
2215 case HAMMER2_BREF_TYPE_FREEMAP:
2216 KKASSERT(parent->data != NULL);
2217 base = &hmp->voldata.freemap_blockset.blockref[0];
2218 count = HAMMER2_SET_COUNT;
2221 panic("hammer2_chain_create: unrecognized blockref type: %d",
2229 * Make sure we've counted the brefs
2231 if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2232 hammer2_chain_countbrefs(parent, base, count);
2234 KKASSERT(parent->core.live_count >= 0 &&
2235 parent->core.live_count <= count);
2238 * If no free blockref could be found we must create an indirect
2239 * block and move a number of blockrefs into it. With the parent
2240 * locked we can safely lock each child in order to delete+duplicate
2241 * it without causing a deadlock.
2243 * This may return the new indirect block or the old parent depending
2244 * on where the key falls. NULL is returned on error.
2246 if (parent->core.live_count == count) {
2247 hammer2_chain_t *nparent;
2249 nparent = hammer2_chain_create_indirect(trans, parent,
2252 if (nparent == NULL) {
2254 hammer2_chain_drop(chain);
2258 if (parent != nparent) {
2259 hammer2_chain_unlock(parent);
2260 parent = *parentp = nparent;
2266 * Link the chain into its parent.
2268 if (chain->parent != NULL)
2269 panic("hammer2: hammer2_chain_create: chain already connected");
2270 KKASSERT(chain->parent == NULL);
2271 hammer2_chain_insert(parent, chain,
2272 HAMMER2_CHAIN_INSERT_SPIN |
2273 HAMMER2_CHAIN_INSERT_LIVE,
2278 * Mark the newly created chain modified. This will cause
2281 * Device buffers are not instantiated for DATA elements
2282 * as these are handled by logical buffers.
2284 * Indirect and freemap node indirect blocks are handled
2285 * by hammer2_chain_create_indirect() and not by this
2288 * Data for all other bref types is expected to be
2289 * instantiated (INODE, LEAF).
2291 switch(chain->bref.type) {
2292 case HAMMER2_BREF_TYPE_DATA:
2293 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2294 case HAMMER2_BREF_TYPE_INODE:
2295 hammer2_chain_modify(trans, chain,
2296 HAMMER2_MODIFY_OPTDATA);
2300 * Remaining types are not supported by this function.
2301 * In particular, INDIRECT and LEAF_NODE types are
2302 * handled by create_indirect().
2304 panic("hammer2_chain_create: bad type: %d",
2311 * When reconnecting a chain we must set UPDATE and
2312 * setflush so the flush recognizes that it must update
2313 * the bref in the parent.
2315 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2316 hammer2_chain_ref(chain);
2317 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2319 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2320 (flags & HAMMER2_INSERT_NOSTATS) == 0) {
2321 KKASSERT(chain->data);
2322 chain->inode_count_up +=
2323 chain->data->ipdata.inode_count;
2324 chain->data_count_up +=
2325 chain->data->ipdata.data_count;
2330 * We must setflush(parent) to ensure that it recurses through to
2331 * chain. setflush(chain) might not work because ONFLUSH is possibly
2332 * already set in the chain (so it won't recurse up to set it in the
2335 hammer2_chain_setflush(trans, parent);
2344 * Move the chain from its old parent to a new parent. The chain must have
2345 * already been deleted or already disconnected (or never associated) with
2346 * a parent. The chain is reassociated with the new parent and the deleted
2347 * flag will be cleared (no longer deleted). The chain's modification state
2350 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2351 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2352 * FULL. This typically means that the caller is creating the chain after
2353 * doing a hammer2_chain_lookup().
2355 * A non-NULL bref is typically passed when key and keybits must be overridden.
2356 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2357 * from a passed-in bref and uses the old chain's bref for everything else.
2359 * If (parent) is non-NULL then the new duplicated chain is inserted under
2362 * If (parent) is NULL then the newly duplicated chain is not inserted
2363 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2364 * passing into hammer2_chain_create() after this function returns).
2366 * WARNING! This function calls create which means it can insert indirect
2367 * blocks. This can cause other unrelated chains in the parent to
2368 * be moved to a newly inserted indirect block in addition to the
2372 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2373 hammer2_chain_t **parentp, hammer2_chain_t *chain,
2377 hammer2_chain_t *parent;
2381 * WARNING! We should never resolve DATA to device buffers
2382 * (XXX allow it if the caller did?), and since
2383 * we currently do not have the logical buffer cache
2384 * buffer in-hand to fix its cached physical offset
2385 * we also force the modify code to not COW it. XXX
2388 KKASSERT(chain->parent == NULL);
2391 * Now create a duplicate of the chain structure, associating
2392 * it with the same core, making it the same size, pointing it
2393 * to the same bref (the same media block).
2396 bref = &chain->bref;
2397 bytes = (hammer2_off_t)1 <<
2398 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2401 * If parent is not NULL the duplicated chain will be entered under
2402 * the parent and the UPDATE bit set to tell flush to update
2405 * We must setflush(parent) to ensure that it recurses through to
2406 * chain. setflush(chain) might not work because ONFLUSH is possibly
2407 * already set in the chain (so it won't recurse up to set it in the
2410 * Having both chains locked is extremely important for atomicy.
2412 if (parentp && (parent = *parentp) != NULL) {
2413 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2414 KKASSERT(parent->refs > 0);
2416 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2417 bref->key, bref->keybits, bref->type,
2418 chain->bytes, flags);
2419 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2420 hammer2_chain_setflush(trans, *parentp);
2425 * Helper function for deleting chains.
2427 * The chain is removed from the live view (the RBTREE) as well as the parent's
2428 * blockmap. Both chain and its parent must be locked.
2431 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2432 hammer2_chain_t *parent, hammer2_chain_t *chain,
2437 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2440 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2442 * Chain is blockmapped, so there must be a parent.
2443 * Atomically remove the chain from the parent and remove
2444 * the blockmap entry.
2446 hammer2_blockref_t *base;
2449 KKASSERT(parent != NULL);
2450 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2451 hammer2_chain_modify(trans, parent,
2452 HAMMER2_MODIFY_OPTDATA);
2455 * Calculate blockmap pointer
2457 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2458 hammer2_spin_ex(&parent->core.spin);
2460 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2461 atomic_add_int(&parent->core.live_count, -1);
2462 ++parent->core.generation;
2463 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2464 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2465 --parent->core.chain_count;
2466 chain->parent = NULL;
2468 switch(parent->bref.type) {
2469 case HAMMER2_BREF_TYPE_INODE:
2471 * Access the inode's block array. However, there
2472 * is no block array if the inode is flagged
2473 * DIRECTDATA. The DIRECTDATA case typicaly only
2474 * occurs when a hardlink has been shifted up the
2475 * tree and the original inode gets replaced with
2476 * an OBJTYPE_HARDLINK placeholding inode.
2479 (parent->data->ipdata.op_flags &
2480 HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2482 &parent->data->ipdata.u.blockset.blockref[0];
2486 count = HAMMER2_SET_COUNT;
2488 case HAMMER2_BREF_TYPE_INDIRECT:
2489 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2491 base = &parent->data->npdata[0];
2494 count = parent->bytes / sizeof(hammer2_blockref_t);
2496 case HAMMER2_BREF_TYPE_VOLUME:
2497 base = &hmp->voldata.sroot_blockset.blockref[0];
2498 count = HAMMER2_SET_COUNT;
2500 case HAMMER2_BREF_TYPE_FREEMAP:
2501 base = &parent->data->npdata[0];
2502 count = HAMMER2_SET_COUNT;
2507 panic("hammer2_flush_pass2: "
2508 "unrecognized blockref type: %d",
2513 * delete blockmapped chain from its parent.
2515 * The parent is not affected by any statistics in chain
2516 * which are pending synchronization. That is, there is
2517 * nothing to undo in the parent since they have not yet
2518 * been incorporated into the parent.
2520 * The parent is affected by statistics stored in inodes.
2521 * Those have already been synchronized, so they must be
2522 * undone. XXX split update possible w/delete in middle?
2525 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2526 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2527 KKASSERT(chain->data != NULL);
2528 parent->data_count -=
2529 chain->data->ipdata.data_count;
2530 parent->inode_count -=
2531 chain->data->ipdata.inode_count;
2534 int cache_index = -1;
2535 hammer2_base_delete(trans, parent, base, count,
2536 &cache_index, chain);
2538 hammer2_spin_unex(&parent->core.spin);
2539 } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2541 * Chain is not blockmapped but a parent is present.
2542 * Atomically remove the chain from the parent. There is
2543 * no blockmap entry to remove.
2545 * Because chain was associated with a parent but not
2546 * synchronized, the chain's *_count_up fields contain
2547 * inode adjustment statistics which must be undone.
2549 hammer2_spin_ex(&parent->core.spin);
2550 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE &&
2551 (flags & HAMMER2_DELETE_NOSTATS) == 0) {
2552 KKASSERT(chain->data != NULL);
2553 chain->data_count_up -=
2554 chain->data->ipdata.data_count;
2555 chain->inode_count_up -=
2556 chain->data->ipdata.inode_count;
2558 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2559 atomic_add_int(&parent->core.live_count, -1);
2560 ++parent->core.generation;
2561 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2562 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2563 --parent->core.chain_count;
2564 chain->parent = NULL;
2565 hammer2_spin_unex(&parent->core.spin);
2568 * Chain is not blockmapped and has no parent. This
2569 * is a degenerate case.
2571 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2576 * If the deletion is permanent (i.e. the chain is not simply being
2577 * moved within the topology), adjust the freemap to indicate that
2578 * the block *might* be freeable. bulkfree must still determine
2579 * that it is actually freeable.
2581 * We no longer do this in the normal filesystem operations path
2582 * as it interferes with the bulkfree algorithm.
2584 if ((flags & HAMMER2_DELETE_PERMANENT) &&
2585 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2586 chain->bref.type != HAMMER2_BREF_TYPE_FREEMAP_LEAF &&
2587 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
2588 hammer2_freemap_adjust(trans, hmp, &chain->bref,
2589 HAMMER2_FREEMAP_DOMAYFREE);
2595 * Create an indirect block that covers one or more of the elements in the
2596 * current parent. Either returns the existing parent with no locking or
2597 * ref changes or returns the new indirect block locked and referenced
2598 * and leaving the original parent lock/ref intact as well.
2600 * If an error occurs, NULL is returned and *errorp is set to the error.
2602 * The returned chain depends on where the specified key falls.
2604 * The key/keybits for the indirect mode only needs to follow three rules:
2606 * (1) That all elements underneath it fit within its key space and
2608 * (2) That all elements outside it are outside its key space.
2610 * (3) When creating the new indirect block any elements in the current
2611 * parent that fit within the new indirect block's keyspace must be
2612 * moved into the new indirect block.
2614 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2615 * keyspace the the current parent, but lookup/iteration rules will
2616 * ensure (and must ensure) that rule (2) for all parents leading up
2617 * to the nearest inode or the root volume header is adhered to. This
2618 * is accomplished by always recursing through matching keyspaces in
2619 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2621 * The current implementation calculates the current worst-case keyspace by
2622 * iterating the current parent and then divides it into two halves, choosing
2623 * whichever half has the most elements (not necessarily the half containing
2624 * the requested key).
2626 * We can also opt to use the half with the least number of elements. This
2627 * causes lower-numbered keys (aka logical file offsets) to recurse through
2628 * fewer indirect blocks and higher-numbered keys to recurse through more.
2629 * This also has the risk of not moving enough elements to the new indirect
2630 * block and being forced to create several indirect blocks before the element
2633 * Must be called with an exclusively locked parent.
2635 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2636 hammer2_key_t *keyp, int keybits,
2637 hammer2_blockref_t *base, int count);
2638 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2639 hammer2_key_t *keyp, int keybits,
2640 hammer2_blockref_t *base, int count);
2643 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2644 hammer2_key_t create_key, int create_bits,
2645 int for_type, int *errorp)
2648 hammer2_blockref_t *base;
2649 hammer2_blockref_t *bref;
2650 hammer2_blockref_t bcopy;
2651 hammer2_chain_t *chain;
2652 hammer2_chain_t *ichain;
2653 hammer2_chain_t dummy;
2654 hammer2_key_t key = create_key;
2655 hammer2_key_t key_beg;
2656 hammer2_key_t key_end;
2657 hammer2_key_t key_next;
2658 int keybits = create_bits;
2665 int maxloops = 300000;
2668 * Calculate the base blockref pointer or NULL if the chain
2669 * is known to be empty. We need to calculate the array count
2670 * for RB lookups either way.
2674 KKASSERT(hammer2_mtx_owned(&parent->core.lock));
2676 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2677 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2680 switch(parent->bref.type) {
2681 case HAMMER2_BREF_TYPE_INODE:
2682 count = HAMMER2_SET_COUNT;
2684 case HAMMER2_BREF_TYPE_INDIRECT:
2685 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2686 count = parent->bytes / sizeof(hammer2_blockref_t);
2688 case HAMMER2_BREF_TYPE_VOLUME:
2689 count = HAMMER2_SET_COUNT;
2691 case HAMMER2_BREF_TYPE_FREEMAP:
2692 count = HAMMER2_SET_COUNT;
2695 panic("hammer2_chain_create_indirect: "
2696 "unrecognized blockref type: %d",
2702 switch(parent->bref.type) {
2703 case HAMMER2_BREF_TYPE_INODE:
2704 base = &parent->data->ipdata.u.blockset.blockref[0];
2705 count = HAMMER2_SET_COUNT;
2707 case HAMMER2_BREF_TYPE_INDIRECT:
2708 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2709 base = &parent->data->npdata[0];
2710 count = parent->bytes / sizeof(hammer2_blockref_t);
2712 case HAMMER2_BREF_TYPE_VOLUME:
2713 base = &hmp->voldata.sroot_blockset.blockref[0];
2714 count = HAMMER2_SET_COUNT;
2716 case HAMMER2_BREF_TYPE_FREEMAP:
2717 base = &hmp->voldata.freemap_blockset.blockref[0];
2718 count = HAMMER2_SET_COUNT;
2721 panic("hammer2_chain_create_indirect: "
2722 "unrecognized blockref type: %d",
2730 * dummy used in later chain allocation (no longer used for lookups).
2732 bzero(&dummy, sizeof(dummy));
2735 * When creating an indirect block for a freemap node or leaf
2736 * the key/keybits must be fitted to static radix levels because
2737 * particular radix levels use particular reserved blocks in the
2740 * This routine calculates the key/radix of the indirect block
2741 * we need to create, and whether it is on the high-side or the
2744 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2745 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2746 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2749 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2754 * Normalize the key for the radix being represented, keeping the
2755 * high bits and throwing away the low bits.
2757 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2760 * How big should our new indirect block be? It has to be at least
2761 * as large as its parent.
2763 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2764 nbytes = HAMMER2_IND_BYTES_MIN;
2766 nbytes = HAMMER2_IND_BYTES_MAX;
2767 if (nbytes < count * sizeof(hammer2_blockref_t))
2768 nbytes = count * sizeof(hammer2_blockref_t);
2771 * Ok, create our new indirect block
2773 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2774 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2775 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2777 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2779 dummy.bref.key = key;
2780 dummy.bref.keybits = keybits;
2781 dummy.bref.data_off = hammer2_getradix(nbytes);
2782 dummy.bref.methods = parent->bref.methods;
2784 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2785 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2786 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2787 hammer2_chain_drop(ichain); /* excess ref from alloc */
2790 * We have to mark it modified to allocate its block, but use
2791 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2792 * it won't be acted upon by the flush code.
2794 hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2797 * Iterate the original parent and move the matching brefs into
2798 * the new indirect block.
2800 * XXX handle flushes.
2803 key_end = HAMMER2_KEY_MAX;
2805 hammer2_spin_ex(&parent->core.spin);
2810 if (++loops > 100000) {
2811 hammer2_spin_unex(&parent->core.spin);
2812 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2813 reason, parent, base, count, key_next);
2817 * NOTE: spinlock stays intact, returned chain (if not NULL)
2818 * is not referenced or locked which means that we
2819 * cannot safely check its flagged / deletion status
2822 chain = hammer2_combined_find(parent, base, count,
2823 &cache_index, &key_next,
2826 generation = parent->core.generation;
2829 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2832 * Skip keys that are not within the key/radix of the new
2833 * indirect block. They stay in the parent.
2835 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2836 (key ^ bref->key)) != 0) {
2837 goto next_key_spinlocked;
2841 * Load the new indirect block by acquiring the related
2842 * chains (potentially from media as it might not be
2843 * in-memory). Then move it to the new parent (ichain)
2844 * via DELETE-DUPLICATE.
2846 * chain is referenced but not locked. We must lock the
2847 * chain to obtain definitive DUPLICATED/DELETED state
2851 * Use chain already present in the RBTREE
2853 hammer2_chain_ref(chain);
2854 hammer2_spin_unex(&parent->core.spin);
2855 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2856 HAMMER2_RESOLVE_NOREF);
2859 * Get chain for blockref element. _get returns NULL
2860 * on insertion race.
2863 hammer2_spin_unex(&parent->core.spin);
2864 chain = hammer2_chain_get(parent, generation, &bcopy);
2865 if (chain == NULL) {
2867 hammer2_spin_ex(&parent->core.spin);
2870 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2871 kprintf("REASON 2\n");
2873 hammer2_chain_drop(chain);
2874 hammer2_spin_ex(&parent->core.spin);
2877 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2878 HAMMER2_RESOLVE_NOREF);
2882 * This is always live so if the chain has been deleted
2883 * we raced someone and we have to retry.
2885 * NOTE: Lookups can race delete-duplicate because
2886 * delete-duplicate does not lock the parent's core
2887 * (they just use the spinlock on the core). We must
2888 * check for races by comparing the DUPLICATED flag before
2889 * releasing the spinlock with the flag after locking the
2892 * (note reversed logic for this one)
2894 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2895 hammer2_chain_unlock(chain);
2900 * Shift the chain to the indirect block.
2902 * WARNING! No reason for us to load chain data, pass NOSTATS
2903 * to prevent delete/insert from trying to access
2904 * inode stats (and thus asserting if there is no
2905 * chain->data loaded).
2907 hammer2_chain_delete(trans, parent, chain,
2908 HAMMER2_DELETE_NOSTATS);
2909 hammer2_chain_rename(trans, NULL, &ichain, chain,
2910 HAMMER2_INSERT_NOSTATS);
2911 hammer2_chain_unlock(chain);
2912 KKASSERT(parent->refs > 0);
2915 hammer2_spin_ex(&parent->core.spin);
2916 next_key_spinlocked:
2917 if (--maxloops == 0)
2918 panic("hammer2_chain_create_indirect: maxloops");
2920 if (key_next == 0 || key_next > key_end)
2925 hammer2_spin_unex(&parent->core.spin);
2928 * Insert the new indirect block into the parent now that we've
2929 * cleared out some entries in the parent. We calculated a good
2930 * insertion index in the loop above (ichain->index).
2932 * We don't have to set UPDATE here because we mark ichain
2933 * modified down below (so the normal modified -> flush -> set-moved
2934 * sequence applies).
2936 * The insertion shouldn't race as this is a completely new block
2937 * and the parent is locked.
2939 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2940 hammer2_chain_insert(parent, ichain,
2941 HAMMER2_CHAIN_INSERT_SPIN |
2942 HAMMER2_CHAIN_INSERT_LIVE,
2946 * Make sure flushes propogate after our manual insertion.
2948 hammer2_chain_setflush(trans, ichain);
2949 hammer2_chain_setflush(trans, parent);
2952 * Figure out what to return.
2954 if (~(((hammer2_key_t)1 << keybits) - 1) &
2955 (create_key ^ key)) {
2957 * Key being created is outside the key range,
2958 * return the original parent.
2960 hammer2_chain_unlock(ichain);
2963 * Otherwise its in the range, return the new parent.
2964 * (leave both the new and old parent locked).
2973 * Calculate the keybits and highside/lowside of the freemap node the
2974 * caller is creating.
2976 * This routine will specify the next higher-level freemap key/radix
2977 * representing the lowest-ordered set. By doing so, eventually all
2978 * low-ordered sets will be moved one level down.
2980 * We have to be careful here because the freemap reserves a limited
2981 * number of blocks for a limited number of levels. So we can't just
2982 * push indiscriminately.
2985 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2986 int keybits, hammer2_blockref_t *base, int count)
2988 hammer2_chain_t *chain;
2989 hammer2_blockref_t *bref;
2991 hammer2_key_t key_beg;
2992 hammer2_key_t key_end;
2993 hammer2_key_t key_next;
2997 int maxloops = 300000;
3005 * Calculate the range of keys in the array being careful to skip
3006 * slots which are overridden with a deletion.
3009 key_end = HAMMER2_KEY_MAX;
3011 hammer2_spin_ex(&parent->core.spin);
3014 if (--maxloops == 0) {
3015 panic("indkey_freemap shit %p %p:%d\n",
3016 parent, base, count);
3018 chain = hammer2_combined_find(parent, base, count,
3019 &cache_index, &key_next,
3030 * Skip deleted chains.
3032 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3033 if (key_next == 0 || key_next > key_end)
3040 * Use the full live (not deleted) element for the scan
3041 * iteration. HAMMER2 does not allow partial replacements.
3043 * XXX should be built into hammer2_combined_find().
3045 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3047 if (keybits > bref->keybits) {
3049 keybits = bref->keybits;
3050 } else if (keybits == bref->keybits && bref->key < key) {
3057 hammer2_spin_unex(&parent->core.spin);
3060 * Return the keybits for a higher-level FREEMAP_NODE covering
3064 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3065 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3067 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3068 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3070 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3071 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3073 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3074 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3076 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3077 panic("hammer2_chain_indkey_freemap: level too high");
3080 panic("hammer2_chain_indkey_freemap: bad radix");
3089 * Calculate the keybits and highside/lowside of the indirect block the
3090 * caller is creating.
3093 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3094 int keybits, hammer2_blockref_t *base, int count)
3096 hammer2_blockref_t *bref;
3097 hammer2_chain_t *chain;
3098 hammer2_key_t key_beg;
3099 hammer2_key_t key_end;
3100 hammer2_key_t key_next;
3106 int maxloops = 300000;
3113 * Calculate the range of keys in the array being careful to skip
3114 * slots which are overridden with a deletion. Once the scan
3115 * completes we will cut the key range in half and shift half the
3116 * range into the new indirect block.
3119 key_end = HAMMER2_KEY_MAX;
3121 hammer2_spin_ex(&parent->core.spin);
3124 if (--maxloops == 0) {
3125 panic("indkey_freemap shit %p %p:%d\n",
3126 parent, base, count);
3128 chain = hammer2_combined_find(parent, base, count,
3129 &cache_index, &key_next,
3140 * NOTE: No need to check DUPLICATED here because we do
3141 * not release the spinlock.
3143 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3144 if (key_next == 0 || key_next > key_end)
3151 * Use the full live (not deleted) element for the scan
3152 * iteration. HAMMER2 does not allow partial replacements.
3154 * XXX should be built into hammer2_combined_find().
3156 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3159 * Expand our calculated key range (key, keybits) to fit
3160 * the scanned key. nkeybits represents the full range
3161 * that we will later cut in half (two halves @ nkeybits - 1).
3164 if (nkeybits < bref->keybits) {
3165 if (bref->keybits > 64) {
3166 kprintf("bad bref chain %p bref %p\n",
3170 nkeybits = bref->keybits;
3172 while (nkeybits < 64 &&
3173 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3174 (key ^ bref->key)) != 0) {
3179 * If the new key range is larger we have to determine
3180 * which side of the new key range the existing keys fall
3181 * under by checking the high bit, then collapsing the
3182 * locount into the hicount or vise-versa.
3184 if (keybits != nkeybits) {
3185 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3196 * The newly scanned key will be in the lower half or the
3197 * upper half of the (new) key range.
3199 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3208 hammer2_spin_unex(&parent->core.spin);
3209 bref = NULL; /* now invalid (safety) */
3212 * Adjust keybits to represent half of the full range calculated
3213 * above (radix 63 max)
3218 * Select whichever half contains the most elements. Theoretically
3219 * we can select either side as long as it contains at least one
3220 * element (in order to ensure that a free slot is present to hold
3221 * the indirect block).
3223 if (hammer2_indirect_optimize) {
3225 * Insert node for least number of keys, this will arrange
3226 * the first few blocks of a large file or the first few
3227 * inodes in a directory with fewer indirect blocks when
3230 if (hicount < locount && hicount != 0)
3231 key |= (hammer2_key_t)1 << keybits;
3233 key &= ~(hammer2_key_t)1 << keybits;
3236 * Insert node for most number of keys, best for heavily
3239 if (hicount > locount)
3240 key |= (hammer2_key_t)1 << keybits;
3242 key &= ~(hammer2_key_t)1 << keybits;
3250 * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3253 * Both parent and chain must be locked exclusively.
3255 * This function will modify the parent if the blockref requires removal
3256 * from the parent's block table.
3258 * This function is NOT recursive. Any entity already pushed into the
3259 * chain (such as an inode) may still need visibility into its contents,
3260 * as well as the ability to read and modify the contents. For example,
3261 * for an unlinked file which is still open.
3264 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3265 hammer2_chain_t *chain, int flags)
3267 KKASSERT(hammer2_mtx_owned(&chain->core.lock));
3270 * Nothing to do if already marked.
3272 * We need the spinlock on the core whos RBTREE contains chain
3273 * to protect against races.
3275 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3276 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3277 chain->parent == parent);
3278 _hammer2_chain_delete_helper(trans, parent, chain, flags);
3281 if (flags & HAMMER2_DELETE_PERMANENT) {
3282 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3283 hammer2_flush(trans, chain);
3285 /* XXX might not be needed */
3286 hammer2_chain_setflush(trans, chain);
3291 * Returns the index of the nearest element in the blockref array >= elm.
3292 * Returns (count) if no element could be found.
3294 * Sets *key_nextp to the next key for loop purposes but does not modify
3295 * it if the next key would be higher than the current value of *key_nextp.
3296 * Note that *key_nexp can overflow to 0, which should be tested by the
3299 * (*cache_indexp) is a heuristic and can be any value without effecting
3302 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3303 * held through the operation.
3306 hammer2_base_find(hammer2_chain_t *parent,
3307 hammer2_blockref_t *base, int count,
3308 int *cache_indexp, hammer2_key_t *key_nextp,
3309 hammer2_key_t key_beg, hammer2_key_t key_end)
3311 hammer2_blockref_t *scan;
3312 hammer2_key_t scan_end;
3317 * Require the live chain's already have their core's counted
3318 * so we can optimize operations.
3320 KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3325 if (count == 0 || base == NULL)
3329 * Sequential optimization using *cache_indexp. This is the most
3332 * We can avoid trailing empty entries on live chains, otherwise
3333 * we might have to check the whole block array.
3337 limit = parent->core.live_zero;
3342 KKASSERT(i < count);
3348 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3355 * Search forwards, stop when we find a scan element which
3356 * encloses the key or until we know that there are no further
3360 if (scan->type != 0) {
3361 scan_end = scan->key +
3362 ((hammer2_key_t)1 << scan->keybits) - 1;
3363 if (scan->key > key_beg || scan_end >= key_beg)
3376 scan_end = scan->key +
3377 ((hammer2_key_t)1 << scan->keybits);
3378 if (scan_end && (*key_nextp > scan_end ||
3380 *key_nextp = scan_end;
3388 * Do a combined search and return the next match either from the blockref
3389 * array or from the in-memory chain. Sets *bresp to the returned bref in
3390 * both cases, or sets it to NULL if the search exhausted. Only returns
3391 * a non-NULL chain if the search matched from the in-memory chain.
3393 * When no in-memory chain has been found and a non-NULL bref is returned
3397 * The returned chain is not locked or referenced. Use the returned bref
3398 * to determine if the search exhausted or not. Iterate if the base find
3399 * is chosen but matches a deleted chain.
3401 * WARNING! Must be called with parent's spinlock held. Spinlock remains
3402 * held through the operation.
3404 static hammer2_chain_t *
3405 hammer2_combined_find(hammer2_chain_t *parent,
3406 hammer2_blockref_t *base, int count,
3407 int *cache_indexp, hammer2_key_t *key_nextp,
3408 hammer2_key_t key_beg, hammer2_key_t key_end,
3409 hammer2_blockref_t **bresp)
3411 hammer2_blockref_t *bref;
3412 hammer2_chain_t *chain;
3416 * Lookup in block array and in rbtree.
3418 *key_nextp = key_end + 1;
3419 i = hammer2_base_find(parent, base, count, cache_indexp,
3420 key_nextp, key_beg, key_end);
3421 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3426 if (i == count && chain == NULL) {
3432 * Only chain matched.
3435 bref = &chain->bref;
3440 * Only blockref matched.
3442 if (chain == NULL) {
3448 * Both in-memory and blockref matched, select the nearer element.
3450 * If both are flush with the left-hand side or both are the
3451 * same distance away, select the chain. In this situation the
3452 * chain must have been loaded from the matching blockmap.
3454 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3455 chain->bref.key == base[i].key) {
3456 KKASSERT(chain->bref.key == base[i].key);
3457 bref = &chain->bref;
3462 * Select the nearer key
3464 if (chain->bref.key < base[i].key) {
3465 bref = &chain->bref;
3472 * If the bref is out of bounds we've exhausted our search.
3475 if (bref->key > key_end) {
3485 * Locate the specified block array element and delete it. The element
3488 * The spin lock on the related chain must be held.
3490 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3491 * need to be adjusted when we commit the media change.
3494 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3495 hammer2_blockref_t *base, int count,
3496 int *cache_indexp, hammer2_chain_t *chain)
3498 hammer2_blockref_t *elm = &chain->bref;
3499 hammer2_key_t key_next;
3503 * Delete element. Expect the element to exist.
3505 * XXX see caller, flush code not yet sophisticated enough to prevent
3506 * re-flushed in some cases.
3508 key_next = 0; /* max range */
3509 i = hammer2_base_find(parent, base, count, cache_indexp,
3510 &key_next, elm->key, elm->key);
3511 if (i == count || base[i].type == 0 ||
3512 base[i].key != elm->key ||
3513 ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3514 base[i].keybits != elm->keybits)) {
3515 hammer2_spin_unex(&parent->core.spin);
3516 panic("delete base %p element not found at %d/%d elm %p\n",
3517 base, i, count, elm);
3520 bzero(&base[i], sizeof(*base));
3523 * We can only optimize parent->core.live_zero for live chains.
3525 if (parent->core.live_zero == i + 1) {
3526 while (--i >= 0 && base[i].type == 0)
3528 parent->core.live_zero = i + 1;
3532 * Clear appropriate blockmap flags in chain.
3534 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3535 HAMMER2_CHAIN_BMAPUPD);
3539 * Insert the specified element. The block array must not already have the
3540 * element and must have space available for the insertion.
3542 * The spin lock on the related chain must be held.
3544 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3545 * need to be adjusted when we commit the media change.
3548 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3549 hammer2_blockref_t *base, int count,
3550 int *cache_indexp, hammer2_chain_t *chain)
3552 hammer2_blockref_t *elm = &chain->bref;
3553 hammer2_key_t key_next;
3562 * Insert new element. Expect the element to not already exist
3563 * unless we are replacing it.
3565 * XXX see caller, flush code not yet sophisticated enough to prevent
3566 * re-flushed in some cases.
3568 key_next = 0; /* max range */
3569 i = hammer2_base_find(parent, base, count, cache_indexp,
3570 &key_next, elm->key, elm->key);
3573 * Shortcut fill optimization, typical ordered insertion(s) may not
3576 KKASSERT(i >= 0 && i <= count);
3579 * Set appropriate blockmap flags in chain.
3581 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3584 * We can only optimize parent->core.live_zero for live chains.
3586 if (i == count && parent->core.live_zero < count) {
3587 i = parent->core.live_zero++;
3592 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3593 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3594 hammer2_spin_unex(&parent->core.spin);
3595 panic("insert base %p overlapping elements at %d elm %p\n",
3600 * Try to find an empty slot before or after.
3604 while (j > 0 || k < count) {
3606 if (j >= 0 && base[j].type == 0) {
3610 bcopy(&base[j+1], &base[j],
3611 (i - j - 1) * sizeof(*base));
3617 if (k < count && base[k].type == 0) {
3618 bcopy(&base[i], &base[i+1],
3619 (k - i) * sizeof(hammer2_blockref_t));
3623 * We can only update parent->core.live_zero for live
3626 if (parent->core.live_zero <= k)
3627 parent->core.live_zero = k + 1;
3632 panic("hammer2_base_insert: no room!");
3639 for (l = 0; l < count; ++l) {
3641 key_next = base[l].key +
3642 ((hammer2_key_t)1 << base[l].keybits) - 1;
3646 while (++l < count) {
3648 if (base[l].key <= key_next)
3649 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3650 key_next = base[l].key +
3651 ((hammer2_key_t)1 << base[l].keybits) - 1;
3661 * Sort the blockref array for the chain. Used by the flush code to
3662 * sort the blockref[] array.
3664 * The chain must be exclusively locked AND spin-locked.
3666 typedef hammer2_blockref_t *hammer2_blockref_p;
3670 hammer2_base_sort_callback(const void *v1, const void *v2)
3672 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3673 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3676 * Make sure empty elements are placed at the end of the array
3678 if (bref1->type == 0) {
3679 if (bref2->type == 0)
3682 } else if (bref2->type == 0) {
3689 if (bref1->key < bref2->key)
3691 if (bref1->key > bref2->key)
3697 hammer2_base_sort(hammer2_chain_t *chain)
3699 hammer2_blockref_t *base;
3702 switch(chain->bref.type) {
3703 case HAMMER2_BREF_TYPE_INODE:
3705 * Special shortcut for embedded data returns the inode
3706 * itself. Callers must detect this condition and access
3707 * the embedded data (the strategy code does this for us).
3709 * This is only applicable to regular files and softlinks.
3711 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3713 base = &chain->data->ipdata.u.blockset.blockref[0];
3714 count = HAMMER2_SET_COUNT;
3716 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3717 case HAMMER2_BREF_TYPE_INDIRECT:
3719 * Optimize indirect blocks in the INITIAL state to avoid
3722 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3723 base = &chain->data->npdata[0];
3724 count = chain->bytes / sizeof(hammer2_blockref_t);
3726 case HAMMER2_BREF_TYPE_VOLUME:
3727 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3728 count = HAMMER2_SET_COUNT;
3730 case HAMMER2_BREF_TYPE_FREEMAP:
3731 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3732 count = HAMMER2_SET_COUNT;
3735 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3737 base = NULL; /* safety */
3738 count = 0; /* safety */
3740 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3746 * Chain memory management
3749 hammer2_chain_wait(hammer2_chain_t *chain)
3751 tsleep(chain, 0, "chnflw", 1);
3754 const hammer2_media_data_t *
3755 hammer2_chain_rdata(hammer2_chain_t *chain)
3757 KKASSERT(chain->data != NULL);
3758 return (chain->data);
3761 hammer2_media_data_t *
3762 hammer2_chain_wdata(hammer2_chain_t *chain)
3764 KKASSERT(chain->data != NULL);
3765 return (chain->data);
3769 * Set the check data for a chain. This can be a heavy-weight operation
3770 * and typically only runs on-flush. For file data check data is calculated
3771 * when the logical buffers are flushed.
3774 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3776 chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3778 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3779 case HAMMER2_CHECK_NONE:
3781 case HAMMER2_CHECK_DISABLED:
3783 case HAMMER2_CHECK_ISCSI32:
3784 chain->bref.check.iscsi32.value =
3785 hammer2_icrc32(bdata, chain->bytes);
3787 case HAMMER2_CHECK_CRC64:
3788 chain->bref.check.crc64.value = 0;
3791 case HAMMER2_CHECK_SHA192:
3793 SHA256_CTX hash_ctx;
3795 uint8_t digest[SHA256_DIGEST_LENGTH];
3796 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3799 SHA256_Init(&hash_ctx);
3800 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3801 SHA256_Final(u.digest, &hash_ctx);
3802 u.digest64[2] ^= u.digest64[3];
3804 chain->bref.check.sha192.data,
3805 sizeof(chain->bref.check.sha192.data));
3808 case HAMMER2_CHECK_FREEMAP:
3809 chain->bref.check.freemap.icrc32 =
3810 hammer2_icrc32(bdata, chain->bytes);
3813 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3814 chain->bref.methods);
3820 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3824 if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3827 switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3828 case HAMMER2_CHECK_NONE:
3831 case HAMMER2_CHECK_DISABLED:
3834 case HAMMER2_CHECK_ISCSI32:
3835 r = (chain->bref.check.iscsi32.value ==
3836 hammer2_icrc32(bdata, chain->bytes));
3838 case HAMMER2_CHECK_CRC64:
3839 r = (chain->bref.check.crc64.value == 0);
3842 case HAMMER2_CHECK_SHA192:
3844 SHA256_CTX hash_ctx;
3846 uint8_t digest[SHA256_DIGEST_LENGTH];
3847 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3850 SHA256_Init(&hash_ctx);
3851 SHA256_Update(&hash_ctx, bdata, chain->bytes);
3852 SHA256_Final(u.digest, &hash_ctx);
3853 u.digest64[2] ^= u.digest64[3];
3855 chain->bref.check.sha192.data,
3856 sizeof(chain->bref.check.sha192.data)) == 0) {
3863 case HAMMER2_CHECK_FREEMAP:
3864 r = (chain->bref.check.freemap.icrc32 ==
3865 hammer2_icrc32(bdata, chain->bytes));
3867 kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
3868 chain->bref.check.freemap.icrc32,
3869 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
3871 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
3872 chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
3877 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3878 chain->bref.methods);