2 * Copyright (c) 2011-2013 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 * by 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 * A chain is topologically stable once it has been inserted into the
44 * in-memory topology. Modifications which copy, move, or resize the chain
45 * are handled via the DELETE-DUPLICATE mechanic where the original chain
46 * stays intact but is marked deleted and a new chain is allocated which
47 * shares the old chain's children.
49 * This sharing is handled via the hammer2_chain_core structure.
51 * The DELETE-DUPLICATE mechanism allows the same topological level to contain
52 * many overloadings. However, our RBTREE mechanics require that there be
53 * no overlaps so we accomplish the overloading by moving conflicting chains
54 * with smaller or equal radii into a sub-RBTREE under the chain being
57 * DELETE-DUPLICATE is also used when a modification to a chain crosses a
58 * flush synchronization boundary, allowing the flush code to continue flushing
59 * the older version of the topology and not be disrupted by new frontend
62 #include <sys/cdefs.h>
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/types.h>
67 #include <sys/kern_syscall.h>
72 static int hammer2_indirect_optimize; /* XXX SYSCTL */
74 static hammer2_chain_t *hammer2_chain_create_indirect(
75 hammer2_trans_t *trans, hammer2_chain_t *parent,
76 hammer2_key_t key, int keybits, int for_type, int *errorp);
77 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
78 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
79 static hammer2_chain_t *hammer2_combined_find(
80 hammer2_chain_t *parent,
81 hammer2_blockref_t *base, int count,
82 int *cache_indexp, hammer2_key_t *key_nextp,
83 hammer2_key_t key_beg, hammer2_key_t key_end,
84 hammer2_blockref_t **bresp);
87 * Basic RBTree for chains. Chains cannot overlap within any given
88 * core->rbtree without recursing through chain->rbtree. We effectively
89 * guarantee this by checking the full range rather than just the first
90 * key element. By matching on the full range callers can detect when
91 * recursrion through chain->rbtree is needed.
93 * NOTE: This also means the a delete-duplicate on the same key will
94 * overload by placing the deleted element in the new element's
95 * chain->rbtree (when doing a direct replacement).
97 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
100 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
102 hammer2_key_t c1_beg;
103 hammer2_key_t c1_end;
104 hammer2_key_t c2_beg;
105 hammer2_key_t c2_end;
107 c1_beg = chain1->bref.key;
108 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
109 c2_beg = chain2->bref.key;
110 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
112 if (c1_end < c2_beg) /* fully to the left */
114 if (c1_beg > c2_end) /* fully to the right */
116 return(0); /* overlap (must not cross edge boundary) */
121 hammer2_isclusterable(hammer2_chain_t *chain)
123 if (hammer2_cluster_enable) {
124 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
125 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
126 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
134 * Recursively set the SUBMODIFIED flag up to the root starting at chain's
135 * parent. SUBMODIFIED is not set in chain itself.
137 * This function always runs up the live tree. The flush code can cause
138 * modifications under dead parents which are being flush synchronized
139 * and will handle this flag itself.
142 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
144 hammer2_chain_core_t *above;
146 if (trans->flags & HAMMER2_TRANS_ISFLUSH)
148 while ((above = chain->above) != NULL) {
149 spin_lock(&above->cst.spin);
150 chain = TAILQ_FIRST(&above->ownerq);
151 while (chain->flags & HAMMER2_CHAIN_DUPLICATED)
152 chain = TAILQ_NEXT(chain, core_entry);
153 atomic_set_int(&chain->flags, HAMMER2_CHAIN_SUBMODIFIED);
154 spin_unlock(&above->cst.spin);
159 * Allocate a new disconnected chain element representing the specified
160 * bref. chain->refs is set to 1 and the passed bref is copied to
161 * chain->bref. chain->bytes is derived from the bref.
163 * chain->core is NOT allocated and the media data and bp pointers are left
164 * NULL. The caller must call chain_core_alloc() to allocate or associate
165 * a core with the chain.
167 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
170 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
171 hammer2_trans_t *trans, hammer2_blockref_t *bref)
173 hammer2_chain_t *chain;
174 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
177 * Construct the appropriate system structure.
180 case HAMMER2_BREF_TYPE_INODE:
181 case HAMMER2_BREF_TYPE_INDIRECT:
182 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
183 case HAMMER2_BREF_TYPE_DATA:
184 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
186 * Chain's are really only associated with the hmp but we
187 * maintain a pmp association for per-mount memory tracking
188 * purposes. The pmp can be NULL.
190 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
193 atomic_add_long(&pmp->inmem_chains, 1);
196 case HAMMER2_BREF_TYPE_VOLUME:
197 case HAMMER2_BREF_TYPE_FREEMAP:
199 panic("hammer2_chain_alloc volume type illegal for op");
202 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
208 chain->bytes = bytes;
210 chain->flags = HAMMER2_CHAIN_ALLOCATED;
211 chain->delete_tid = HAMMER2_MAX_TID;
213 chain->modify_tid = trans->sync_tid;
219 * Associate an existing core with the chain or allocate a new core.
221 * The core is not locked. No additional refs on the chain are made.
222 * (trans) must not be NULL if (core) is not NULL.
224 * When chains are delete-duplicated during flushes we insert nchain on
225 * the ownerq after ochain instead of at the end in order to give the
226 * drop code visibility in the correct order, otherwise drops can be missed.
229 hammer2_chain_core_alloc(hammer2_trans_t *trans,
230 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
232 hammer2_chain_core_t *core;
234 KKASSERT(nchain->core == NULL);
236 if (ochain == NULL) {
238 * Fresh core under nchain (no multi-homing of ochain's
241 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
243 TAILQ_INIT(&core->layerq);
244 TAILQ_INIT(&core->ownerq);
248 ccms_cst_init(&core->cst, nchain);
249 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
252 * Propagate the PFSROOT flag which we set on all subdirs
253 * under the super-root.
255 atomic_set_int(&nchain->flags,
256 ochain->flags & HAMMER2_CHAIN_PFSROOT);
259 * Multi-homing (delete-duplicate) sub-tree under ochain.
260 * Set the DUPLICATED flag on ochain but only if this is
261 * not a snapshot. This flag governs forward iterations
262 * for any refactor tests.
264 * It is not legal for the DUPLICATED flag to already be
265 * set. This indicates that the caller is trying to
266 * delete-duplicate a stale chain. The flusher can modify
267 * a stale chain as part of its synchronization point handling
268 * in order to update the block table (and it will
269 * carry-forward such modifications automatically), but it
270 * has no business delete-duplicating it.
272 KKASSERT((ochain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
273 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
274 atomic_set_int(&ochain->flags,
275 HAMMER2_CHAIN_DUPLICATED);
278 atomic_add_int(&core->sharecnt, 1);
280 spin_lock(&core->cst.spin);
284 * Maintain ordering for refactor test so we don't skip over
288 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
290 if (trans->flags & HAMMER2_TRANS_ISFLUSH) {
291 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain,
294 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
297 spin_unlock(&core->cst.spin);
302 * Add a reference to a chain element, preventing its destruction.
305 hammer2_chain_ref(hammer2_chain_t *chain)
307 atomic_add_int(&chain->refs, 1);
311 * Insert the chain in the core rbtree at the first layer
312 * which accepts it (for now we don't sort layers by the transaction tid)
314 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
315 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
316 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
320 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_t *chain,
323 hammer2_chain_layer_t *layer;
324 hammer2_chain_t *xchain;
326 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
327 spin_lock(&above->cst.spin);
328 chain->above = above;
329 layer = TAILQ_FIRST(&above->layerq);
336 (xchain = RB_INSERT(hammer2_chain_tree,
337 &layer->rbtree, chain)) != NULL) {
339 * Either no layers have been allocated or the insertion
340 * failed. This is fatal if the conflicted xchain is not
341 * flagged as deleted. Caller may or may allow the failure.
343 if (xchain && (xchain->flags & HAMMER2_CHAIN_DELETED) == 0) {
344 if (flags & HAMMER2_CHAIN_INSERT_RACE) {
346 chain->inlayer = NULL;
347 kprintf("insertion race against %p\n", xchain);
350 panic("hammer2_chain_insert: collision2 %p", xchain);
354 * Allocate a new layer to resolve the issue.
356 spin_unlock(&above->cst.spin);
357 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
359 RB_INIT(&layer->rbtree);
360 layer->good = 0xABCD;
361 spin_lock(&above->cst.spin);
362 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
363 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
365 chain->inlayer = layer;
366 ++above->chain_count;
368 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
369 atomic_add_int(&above->live_count, 1);
370 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
372 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
373 spin_unlock(&above->cst.spin);
377 * Drop the caller's reference to the chain. When the ref count drops to
378 * zero this function will disassociate the chain from its parent and
379 * deallocate it, then recursely drop the parent using the implied ref
380 * from the chain's chain->parent.
382 * WARNING! Just because we are able to deallocate a chain doesn't mean
383 * that chain->core->rbtree is empty. There can still be a sharecnt
384 * on chain->core and RBTREE entries that refer to different parents.
386 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
389 hammer2_chain_drop(hammer2_chain_t *chain)
395 if (chain->flags & HAMMER2_CHAIN_MOVED)
397 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
399 KKASSERT(chain->refs > need);
407 chain = hammer2_chain_lastdrop(chain);
409 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
411 /* retry the same chain */
417 * Safe handling of the 1->0 transition on chain. Returns a chain for
418 * recursive drop or NULL, possibly returning the same chain if the atomic
421 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
425 hammer2_chain_lastdrop(hammer2_chain_t *chain)
427 hammer2_pfsmount_t *pmp;
428 hammer2_mount_t *hmp;
429 hammer2_chain_core_t *above;
430 hammer2_chain_core_t *core;
431 hammer2_chain_layer_t *layer;
432 hammer2_chain_t *rdrop1;
433 hammer2_chain_t *rdrop2;
436 * Spinlock the core and check to see if it is empty. If it is
437 * not empty we leave chain intact with refs == 0. The elements
438 * in core->rbtree are associated with other chains contemporary
439 * with ours but not with our chain directly.
441 if ((core = chain->core) != NULL) {
442 spin_lock(&core->cst.spin);
445 * We can't drop any chains if they have children because
446 * there might be a flush dependency.
448 * NOTE: We return (chain) on failure to retry.
450 if (core->chain_count) {
451 if (atomic_cmpset_int(&chain->refs, 1, 0))
452 chain = NULL; /* success */
453 spin_unlock(&core->cst.spin);
456 /* no chains left under us */
459 * We can't drop a live chain unless it is a the head
460 * of its ownerq. If we were to then the go-to chain
461 * would revert to the prior deleted chain.
463 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
464 TAILQ_FIRST(&core->ownerq) != chain) {
465 if (atomic_cmpset_int(&chain->refs, 1, 0))
466 chain = NULL; /* success */
467 spin_unlock(&core->cst.spin);
474 pmp = chain->pmp; /* can be NULL */
480 * Spinlock the parent and try to drop the last ref. On success
481 * remove chain from its parent, otherwise return NULL.
483 * (multiple spinlocks on core's are allowed in a bottom-up fashion).
485 if ((above = chain->above) != NULL) {
486 spin_lock(&above->cst.spin);
487 if (!atomic_cmpset_int(&chain->refs, 1, 0)) {
488 /* 1->0 transition failed */
489 spin_unlock(&above->cst.spin);
491 spin_unlock(&core->cst.spin);
492 return(chain); /* retry */
496 * 1->0 transition successful, remove chain from its
497 * above core. Track layer for removal/freeing.
499 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
500 layer = chain->inlayer;
501 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
502 --above->chain_count;
503 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
505 chain->inlayer = NULL;
507 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
508 TAILQ_REMOVE(&above->layerq, layer, entry);
515 * If our chain was the last chain in the parent's core the
516 * core is now empty. Try to drop the first multi-homed
519 if (above->chain_count == 0) {
520 rdrop1 = TAILQ_FIRST(&above->ownerq);
522 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
527 spin_unlock(&above->cst.spin);
528 above = NULL; /* safety */
532 * We still have the core spinlock (if core is non-NULL). The
533 * above spinlock is gone.
535 * Remove chain from ownerq. This may change the first element of
536 * ownerq to something we can remove.
541 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
542 rdrop2 = TAILQ_FIRST(&core->ownerq);
544 atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0) {
547 spin_unlock(&core->cst.spin);
550 * We can do the final 1->0 transition with an atomic op
551 * after releasing core's spinlock.
553 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
555 * On the 1->0 transition of core we can destroy
556 * it. Any remaining layers should no longer be
557 * referenced or visibile to other threads.
559 KKASSERT(TAILQ_EMPTY(&core->ownerq));
561 layer->good = 0xEF00;
562 kfree(layer, hmp->mchain);
564 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
565 KKASSERT(layer->refs == 0 &&
566 RB_EMPTY(&layer->rbtree));
567 TAILQ_REMOVE(&core->layerq, layer, entry);
568 layer->good = 0xEF01;
569 kfree(layer, hmp->mchain);
572 KKASSERT(core->cst.count == 0);
573 KKASSERT(core->cst.upgrade == 0);
575 kfree(core, hmp->mchain);
577 core = NULL; /* safety */
581 * All spin locks are gone, finish freeing stuff.
583 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
584 HAMMER2_CHAIN_MODIFIED)) == 0);
585 hammer2_chain_drop_data(chain, 1);
587 KKASSERT(chain->bp == NULL);
590 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
591 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
592 kfree(chain, hmp->mchain);
594 atomic_add_long(&pmp->inmem_chains, -1);
595 hammer2_chain_memory_wakeup(pmp);
600 * Free saved empty layer and return chained drop.
603 layer->good = 0xEF02;
604 kfree(layer, hmp->mchain);
607 hammer2_chain_drop(rdrop2);
612 * On either last lock release or last drop
615 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
617 hammer2_mount_t *hmp = chain->hmp;
619 switch(chain->bref.type) {
620 case HAMMER2_BREF_TYPE_VOLUME:
621 case HAMMER2_BREF_TYPE_FREEMAP:
625 case HAMMER2_BREF_TYPE_INODE:
627 kfree(chain->data, hmp->mchain);
631 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
633 kfree(chain->data, hmp->mchain);
638 KKASSERT(chain->data == NULL);
644 * Ref and lock a chain element, acquiring its data with I/O if necessary,
645 * and specify how you would like the data to be resolved.
647 * Returns 0 on success or an error code if the data could not be acquired.
648 * The chain element is locked on return regardless of whether an error
651 * The lock is allowed to recurse, multiple locking ops will aggregate
652 * the requested resolve types. Once data is assigned it will not be
653 * removed until the last unlock.
655 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
656 * (typically used to avoid device/logical buffer
659 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
660 * the INITIAL-create state (indirect blocks only).
662 * Do not resolve data elements for DATA chains.
663 * (typically used to avoid device/logical buffer
666 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
668 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
669 * it will be locked exclusive.
671 * NOTE: Embedded elements (volume header, inodes) are always resolved
674 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
675 * element will instantiate and zero its buffer, and flush it on
678 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
679 * so as not to instantiate a device buffer, which could alias against
680 * a logical file buffer. However, if ALWAYS is specified the
681 * device buffer will be instantiated anyway.
683 * WARNING! If data must be fetched a shared lock will temporarily be
684 * upgraded to exclusive. However, a deadlock can occur if
685 * the caller owns more than one shared lock.
688 hammer2_chain_lock(hammer2_chain_t *chain, int how)
690 hammer2_mount_t *hmp;
691 hammer2_chain_core_t *core;
692 hammer2_blockref_t *bref;
703 * Ref and lock the element. Recursive locks are allowed.
705 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
706 hammer2_chain_ref(chain);
707 atomic_add_int(&chain->lockcnt, 1);
710 KKASSERT(hmp != NULL);
713 * Get the appropriate lock.
716 if (how & HAMMER2_RESOLVE_SHARED)
717 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
719 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
722 * If we already have a valid data pointer no further action is
729 * Do we have to resolve the data?
731 switch(how & HAMMER2_RESOLVE_MASK) {
732 case HAMMER2_RESOLVE_NEVER:
734 case HAMMER2_RESOLVE_MAYBE:
735 if (chain->flags & HAMMER2_CHAIN_INITIAL)
737 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
740 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
743 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
746 case HAMMER2_RESOLVE_ALWAYS:
751 * Upgrade to an exclusive lock so we can safely manipulate the
752 * buffer cache. If another thread got to it before us we
755 ostate = ccms_thread_lock_upgrade(&core->cst);
757 ccms_thread_lock_downgrade(&core->cst, ostate);
762 * We must resolve to a device buffer, either by issuing I/O or
763 * by creating a zero-fill element. We do not mark the buffer
764 * dirty when creating a zero-fill element (the hammer2_chain_modify()
765 * API must still be used to do that).
767 * The device buffer is variable-sized in powers of 2 down
768 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
769 * chunk always contains buffers of the same size. (XXX)
771 * The minimum physical IO size may be larger than the variable
776 psize = hammer2_devblksize(chain->bytes);
777 pmask = (hammer2_off_t)psize - 1;
778 pbase = bref->data_off & ~pmask;
779 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
780 KKASSERT(pbase != 0);
781 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
784 * The getblk() optimization can only be used on newly created
785 * elements if the physical block size matches the request.
787 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
788 chain->bytes == psize) {
789 chain->bp = getblk(hmp->devvp, pbase, psize, 0, 0);
791 } else if (hammer2_isclusterable(chain)) {
792 error = cluster_read(hmp->devvp, peof, pbase, psize,
793 psize, HAMMER2_PBUFSIZE*4,
795 adjreadcounter(&chain->bref, chain->bytes);
797 error = bread(hmp->devvp, pbase, psize, &chain->bp);
798 adjreadcounter(&chain->bref, chain->bytes);
802 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
803 (intmax_t)pbase, error);
806 ccms_thread_lock_downgrade(&core->cst, ostate);
811 * Zero the data area if the chain is in the INITIAL-create state.
812 * Mark the buffer for bdwrite(). This clears the INITIAL state
813 * but does not mark the chain modified.
815 bdata = (char *)chain->bp->b_data + boff;
816 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
817 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
818 bzero(bdata, chain->bytes);
819 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
823 * Setup the data pointer, either pointing it to an embedded data
824 * structure and copying the data from the buffer, or pointing it
827 * The buffer is not retained when copying to an embedded data
828 * structure in order to avoid potential deadlocks or recursions
829 * on the same physical buffer.
831 switch (bref->type) {
832 case HAMMER2_BREF_TYPE_VOLUME:
833 case HAMMER2_BREF_TYPE_FREEMAP:
835 * Copy data from bp to embedded buffer
837 panic("hammer2_chain_lock: called on unresolved volume header");
840 KKASSERT(pbase == 0);
841 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
842 bcopy(bdata, &hmp->voldata, chain->bytes);
843 chain->data = (void *)&hmp->voldata;
848 case HAMMER2_BREF_TYPE_INODE:
850 * Copy data from bp to embedded buffer, do not retain the
853 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
854 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
855 chain->data = kmalloc(sizeof(chain->data->ipdata),
856 hmp->mchain, M_WAITOK | M_ZERO);
857 bcopy(bdata, &chain->data->ipdata, chain->bytes);
861 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
862 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
863 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
864 chain->data = kmalloc(sizeof(chain->data->bmdata),
865 hmp->mchain, M_WAITOK | M_ZERO);
866 bcopy(bdata, &chain->data->bmdata, chain->bytes);
870 case HAMMER2_BREF_TYPE_INDIRECT:
871 case HAMMER2_BREF_TYPE_DATA:
872 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
875 * Point data at the device buffer and leave bp intact.
877 chain->data = (void *)bdata;
882 * Make sure the bp is not specifically owned by this thread before
883 * restoring to a possibly shared lock, so another hammer2 thread
887 BUF_KERNPROC(chain->bp);
888 ccms_thread_lock_downgrade(&core->cst, ostate);
893 * Asynchronously read the device buffer (dbp) and execute the specified
894 * callback. The caller should pass-in a locked chain (shared lock is ok).
895 * The function is responsible for unlocking the chain and for disposing
898 * NOTE! A NULL dbp (but non-NULL data) will be passed to the function
899 * if the dbp is integrated into the chain, because we do not want
900 * the caller to dispose of dbp in that situation.
902 static void hammer2_chain_load_async_callback(struct bio *bio);
905 hammer2_chain_load_async(hammer2_chain_t *chain,
906 void (*func)(hammer2_chain_t *, struct buf *, char *, void *),
909 hammer2_cbinfo_t *cbinfo;
910 hammer2_mount_t *hmp;
911 hammer2_blockref_t *bref;
921 func(chain, NULL, (char *)chain->data, arg);
926 * We must resolve to a device buffer, either by issuing I/O or
927 * by creating a zero-fill element. We do not mark the buffer
928 * dirty when creating a zero-fill element (the hammer2_chain_modify()
929 * API must still be used to do that).
931 * The device buffer is variable-sized in powers of 2 down
932 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
933 * chunk always contains buffers of the same size. (XXX)
935 * The minimum physical IO size may be larger than the variable
940 psize = hammer2_devblksize(chain->bytes);
941 pmask = (hammer2_off_t)psize - 1;
942 pbase = bref->data_off & ~pmask;
943 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
944 KKASSERT(pbase != 0);
945 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
950 * The getblk() optimization can only be used on newly created
951 * elements if the physical block size matches the request.
953 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
954 chain->bytes == psize) {
955 dbp = getblk(hmp->devvp, pbase, psize, 0, 0);
956 /*atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);*/
957 bdata = (char *)dbp->b_data + boff;
958 bzero(bdata, chain->bytes);
959 /*atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);*/
960 func(chain, dbp, bdata, arg);
965 adjreadcounter(&chain->bref, chain->bytes);
966 cbinfo = kmalloc(sizeof(*cbinfo), hmp->mchain, M_INTWAIT | M_ZERO);
967 cbinfo->chain = chain;
972 cluster_readcb(hmp->devvp, peof, pbase, psize,
973 HAMMER2_PBUFSIZE*4, HAMMER2_PBUFSIZE*4,
974 hammer2_chain_load_async_callback, cbinfo);
978 hammer2_chain_load_async_callback(struct bio *bio)
980 hammer2_cbinfo_t *cbinfo;
981 hammer2_mount_t *hmp;
986 * Nobody is waiting for bio/dbp to complete, we are
987 * responsible for handling the biowait() equivalent
988 * on dbp which means clearing BIO_DONE and BIO_SYNC
989 * and calling bpdone() if it hasn't already been called
990 * to restore any covered holes in the buffer's backing
994 if ((bio->bio_flags & BIO_DONE) == 0)
996 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
999 * Extract the auxillary info and issue the callback.
1000 * Finish up with the dbp after it returns.
1002 cbinfo = bio->bio_caller_info1.ptr;
1003 /*ccms_thread_lock_setown(cbinfo->chain->core);*/
1004 data = dbp->b_data + cbinfo->boff;
1005 hmp = cbinfo->chain->hmp;
1007 cbinfo = bio->bio_caller_info1.ptr;
1008 if (cbinfo->chain->flags & HAMMER2_CHAIN_INITIAL)
1009 bzero(data, cbinfo->chain->bytes);
1010 cbinfo->func(cbinfo->chain, dbp, data, cbinfo->arg);
1011 /* cbinfo->chain is stale now */
1013 kfree(cbinfo, hmp->mchain);
1017 * Unlock and deref a chain element.
1019 * On the last lock release any non-embedded data (chain->bp) will be
1023 hammer2_chain_unlock(hammer2_chain_t *chain)
1025 hammer2_chain_core_t *core = chain->core;
1026 ccms_state_t ostate;
1031 * The core->cst lock can be shared across several chains so we
1032 * need to track the per-chain lockcnt separately.
1034 * If multiple locks are present (or being attempted) on this
1035 * particular chain we can just unlock, drop refs, and return.
1037 * Otherwise fall-through on the 1->0 transition.
1040 lockcnt = chain->lockcnt;
1041 KKASSERT(lockcnt > 0);
1044 if (atomic_cmpset_int(&chain->lockcnt,
1045 lockcnt, lockcnt - 1)) {
1046 ccms_thread_unlock(&core->cst);
1047 hammer2_chain_drop(chain);
1051 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1058 * On the 1->0 transition we upgrade the core lock (if necessary)
1059 * to exclusive for terminal processing. If after upgrading we find
1060 * that lockcnt is non-zero, another thread is racing us and will
1061 * handle the unload for us later on, so just cleanup and return
1062 * leaving the data/bp intact
1064 * Otherwise if lockcnt is still 0 it is possible for it to become
1065 * non-zero and race, but since we hold the core->cst lock
1066 * exclusively all that will happen is that the chain will be
1067 * reloaded after we unload it.
1069 ostate = ccms_thread_lock_upgrade(&core->cst);
1070 if (chain->lockcnt) {
1071 ccms_thread_unlock_upgraded(&core->cst, ostate);
1072 hammer2_chain_drop(chain);
1077 * Shortcut the case if the data is embedded or not resolved.
1079 * Do NOT NULL out chain->data (e.g. inode data), it might be
1082 * The DIRTYBP flag is non-applicable in this situation and can
1083 * be cleared to keep the flags state clean.
1085 if (chain->bp == NULL) {
1086 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1087 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1088 hammer2_chain_drop_data(chain, 0);
1089 ccms_thread_unlock_upgraded(&core->cst, ostate);
1090 hammer2_chain_drop(chain);
1097 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
1099 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1100 switch(chain->bref.type) {
1101 case HAMMER2_BREF_TYPE_DATA:
1102 counterp = &hammer2_ioa_file_write;
1104 case HAMMER2_BREF_TYPE_INODE:
1105 counterp = &hammer2_ioa_meta_write;
1107 case HAMMER2_BREF_TYPE_INDIRECT:
1108 counterp = &hammer2_ioa_indr_write;
1110 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1111 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1112 counterp = &hammer2_ioa_fmap_write;
1115 counterp = &hammer2_ioa_volu_write;
1118 *counterp += chain->bytes;
1120 switch(chain->bref.type) {
1121 case HAMMER2_BREF_TYPE_DATA:
1122 counterp = &hammer2_iod_file_write;
1124 case HAMMER2_BREF_TYPE_INODE:
1125 counterp = &hammer2_iod_meta_write;
1127 case HAMMER2_BREF_TYPE_INDIRECT:
1128 counterp = &hammer2_iod_indr_write;
1130 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1131 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1132 counterp = &hammer2_iod_fmap_write;
1135 counterp = &hammer2_iod_volu_write;
1138 *counterp += chain->bytes;
1144 * If a device buffer was used for data be sure to destroy the
1145 * buffer when we are done to avoid aliases (XXX what about the
1146 * underlying VM pages?).
1148 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1153 * XXX our primary cache is now the block device, not
1154 * the logical file. don't release the buffer.
1156 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1157 chain->bp->b_flags |= B_RELBUF;
1161 * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
1162 * or not. The flag will get re-set when chain_modify() is called,
1163 * even if MODIFIED is already set, allowing the OS to retire the
1164 * buffer independent of a hammer2 flus.
1167 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1168 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1169 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1170 atomic_clear_int(&chain->flags,
1171 HAMMER2_CHAIN_IOFLUSH);
1172 chain->bp->b_flags |= B_RELBUF;
1173 cluster_awrite(chain->bp);
1175 chain->bp->b_flags |= B_CLUSTEROK;
1179 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1180 atomic_clear_int(&chain->flags,
1181 HAMMER2_CHAIN_IOFLUSH);
1182 chain->bp->b_flags |= B_RELBUF;
1185 /* bp might still be dirty */
1190 ccms_thread_unlock_upgraded(&core->cst, ostate);
1191 hammer2_chain_drop(chain);
1195 * This counts the number of live blockrefs in a block array and
1196 * also calculates the point at which all remaining blockrefs are empty.
1198 * NOTE: Flag is not set until after the count is complete, allowing
1199 * callers to test the flag without holding the spinlock.
1201 * NOTE: If base is NULL the related chain is still in the INITIAL
1202 * state and there are no blockrefs to count.
1204 * NOTE: live_count may already have some counts accumulated due to
1205 * creation and deletion and could even be initially negative.
1208 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1209 hammer2_blockref_t *base, int count)
1211 hammer2_chain_core_t *core = chain->core;
1213 spin_lock(&core->cst.spin);
1214 if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1216 while (--count >= 0) {
1217 if (base[count].type)
1220 chain->live_zero = count + 1;
1221 while (count >= 0) {
1222 if (base[count].type)
1223 atomic_add_int(&core->live_count, 1);
1227 chain->live_zero = 0;
1229 /* else do not modify live_count */
1230 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1232 spin_unlock(&core->cst.spin);
1236 * Resize the chain's physical storage allocation in-place. This may
1237 * replace the passed-in chain with a new chain.
1239 * Chains can be resized smaller without reallocating the storage.
1240 * Resizing larger will reallocate the storage.
1242 * Must be passed an exclusively locked parent and chain, returns a new
1243 * exclusively locked chain at the same index and unlocks the old chain.
1244 * Flushes the buffer if necessary.
1246 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1247 * to avoid instantiating a device buffer that conflicts with the vnode
1248 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1249 * any chain-oriented bp would be a device buffer.
1251 * XXX flags currently ignored, uses chain->bp to detect data/no-data.
1252 * XXX return error if cannot resize.
1255 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1256 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1257 int nradix, int flags)
1259 hammer2_mount_t *hmp;
1260 hammer2_chain_t *chain;
1261 hammer2_off_t pbase;
1271 * Only data and indirect blocks can be resized for now.
1272 * (The volu root, inodes, and freemap elements use a fixed size).
1274 KKASSERT(chain != &hmp->vchain);
1275 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1276 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1279 * Nothing to do if the element is already the proper size
1281 obytes = chain->bytes;
1282 nbytes = 1U << nradix;
1283 if (obytes == nbytes)
1287 * Delete the old chain and duplicate it at the same (parent, index),
1288 * returning a new chain. This allows the old chain to still be
1289 * used by the flush code. Duplication occurs in-place.
1291 * The parent does not have to be locked for the delete/duplicate call,
1292 * but is in this particular code path.
1294 * NOTE: If we are not crossing a synchronization point the
1295 * duplication code will simply reuse the existing chain
1298 hammer2_chain_delete_duplicate(trans, &chain, 0);
1301 * Set MODIFIED and add a chain ref to prevent destruction. Both
1302 * modified flags share the same ref. (duplicated chains do not
1303 * start out MODIFIED unless possibly if the duplication code
1304 * decided to reuse the existing chain as-is).
1306 * If the chain is already marked MODIFIED then we can safely
1307 * return the previous allocation to the pool without having to
1308 * worry about snapshots. XXX check flush synchronization.
1310 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1311 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1312 hammer2_chain_ref(chain);
1316 * Relocate the block, even if making it smaller (because different
1317 * block sizes may be in different regions).
1319 hammer2_freemap_alloc(trans, chain->hmp, &chain->bref, nbytes);
1320 chain->bytes = nbytes;
1321 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1324 * The device buffer may be larger than the allocation size.
1326 bbytes = hammer2_devblksize(chain->bytes);
1327 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1328 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1331 * For now just support it on DATA chains (and not on indirect
1334 KKASSERT(chain->bp == NULL);
1337 * Make sure the chain is marked MOVED and SUBMOD is set in the
1338 * parent(s) so the adjustments are picked up by flush.
1340 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1341 hammer2_chain_ref(chain);
1342 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1344 hammer2_chain_setsubmod(trans, chain);
1349 * Set a chain modified, making it read-write and duplicating it if necessary.
1350 * This function will assign a new physical block to the chain if necessary
1352 * Duplication of already-modified chains is possible when the modification
1353 * crosses a flush synchronization boundary.
1355 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1356 * level or the COW operation will not work.
1358 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1359 * run the data through the device buffers.
1361 * This function may return a different chain than was passed, in which case
1362 * the old chain will be unlocked and the new chain will be locked.
1364 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1366 hammer2_inode_data_t *
1367 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1368 hammer2_chain_t **chainp, int flags)
1370 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1371 hammer2_chain_modify(trans, chainp, flags);
1372 if (ip->chain != *chainp)
1373 hammer2_inode_repoint(ip, NULL, *chainp);
1374 return(&ip->chain->data->ipdata);
1378 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1381 hammer2_mount_t *hmp;
1382 hammer2_chain_t *chain;
1383 hammer2_off_t pbase;
1384 hammer2_off_t pmask;
1386 hammer2_tid_t flush_tid;
1398 * Data must be resolved if already assigned unless explicitly
1399 * flagged otherwise.
1401 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1402 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1403 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1404 hammer2_chain_unlock(chain);
1408 * data is not optional for freemap chains (we must always be sure
1409 * to copy the data on COW storage allocations).
1411 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1412 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1413 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1414 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1418 * If the chain is already marked MODIFIED we can usually just
1419 * return. However, if a modified chain is modified again in
1420 * a synchronization-point-crossing manner we have to issue a
1421 * delete/duplicate on the chain to avoid flush interference.
1423 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1425 * Which flush_tid do we need to check? If the chain is
1426 * related to the freemap we have to use the freemap flush
1427 * tid (free_flush_tid), otherwise we use the normal filesystem
1428 * flush tid (topo_flush_tid). The two flush domains are
1429 * almost completely independent of each other.
1431 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1432 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1433 flush_tid = hmp->topo_flush_tid; /* XXX */
1434 goto skipxx; /* XXX */
1436 flush_tid = hmp->topo_flush_tid;
1442 if (chain->modify_tid <= flush_tid &&
1443 trans->sync_tid > flush_tid) {
1445 * Modifications cross synchronization point,
1446 * requires delete-duplicate.
1448 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1449 hammer2_chain_delete_duplicate(trans, chainp, 0);
1451 /* fall through using duplicate */
1455 * Quick return path, set DIRTYBP to ensure that
1456 * the later retirement of bp will write it out.
1458 * quick return path also needs the modify_tid
1462 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1463 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1464 chain->bref.modify_tid = trans->sync_tid;
1465 chain->modify_tid = trans->sync_tid;
1470 * modify_tid is only update for primary modifications, not for
1471 * propagated brefs. mirror_tid will be updated regardless during
1472 * the flush, no need to set it here.
1474 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1475 chain->bref.modify_tid = trans->sync_tid;
1478 * Set MODIFIED and add a chain ref to prevent destruction. Both
1479 * modified flags share the same ref.
1481 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1482 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1483 hammer2_chain_ref(chain);
1487 * Adjust chain->modify_tid so the flusher knows when the
1488 * modification occurred.
1490 chain->modify_tid = trans->sync_tid;
1493 * The modification or re-modification requires an allocation and
1496 * We normally always allocate new storage here. If storage exists
1497 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1499 if (chain != &hmp->vchain &&
1500 chain != &hmp->fchain &&
1501 ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1502 (flags & HAMMER2_MODIFY_NOREALLOC) == 0)
1504 hammer2_freemap_alloc(trans, chain->hmp,
1505 &chain->bref, chain->bytes);
1506 /* XXX failed allocation */
1510 * Do not COW if OPTDATA is set. INITIAL flag remains unchanged.
1511 * (OPTDATA does not prevent [re]allocation of storage, only the
1512 * related copy-on-write op).
1514 if (flags & HAMMER2_MODIFY_OPTDATA)
1518 * Clearing the INITIAL flag (for indirect blocks) indicates that
1519 * we've processed the uninitialized storage allocation.
1521 * If this flag is already clear we are likely in a copy-on-write
1522 * situation but we have to be sure NOT to bzero the storage if
1523 * no data is present.
1525 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1526 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1534 * We currently should never instantiate a device buffer for a
1535 * file data chain. (We definitely can for a freemap chain).
1537 * XXX we can now do this
1539 KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_DATA);
1543 * Instantiate data buffer and possibly execute COW operation
1545 switch(chain->bref.type) {
1546 case HAMMER2_BREF_TYPE_VOLUME:
1547 case HAMMER2_BREF_TYPE_FREEMAP:
1548 case HAMMER2_BREF_TYPE_INODE:
1549 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1551 * The data is embedded, no copy-on-write operation is
1554 KKASSERT(chain->bp == NULL);
1556 case HAMMER2_BREF_TYPE_DATA:
1557 case HAMMER2_BREF_TYPE_INDIRECT:
1558 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1560 * Perform the copy-on-write operation
1562 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1564 psize = hammer2_devblksize(chain->bytes);
1565 pmask = (hammer2_off_t)psize - 1;
1566 pbase = chain->bref.data_off & ~pmask;
1567 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1568 KKASSERT(pbase != 0);
1569 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1572 * The getblk() optimization can only be used if the
1573 * chain element size matches the physical block size.
1575 if (chain->bp && chain->bp->b_loffset == pbase) {
1578 } else if (chain->bytes == psize) {
1579 nbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1581 } else if (hammer2_isclusterable(chain)) {
1582 error = cluster_read(hmp->devvp, peof, pbase, psize,
1583 psize, HAMMER2_PBUFSIZE*4,
1585 adjreadcounter(&chain->bref, chain->bytes);
1587 error = bread(hmp->devvp, pbase, psize, &nbp);
1588 adjreadcounter(&chain->bref, chain->bytes);
1590 KKASSERT(error == 0);
1591 bdata = (char *)nbp->b_data + boff;
1594 * Copy or zero-fill on write depending on whether
1595 * chain->data exists or not. Retire the existing bp
1596 * based on the DIRTYBP flag. Set the DIRTYBP flag to
1597 * indicate that retirement of nbp should use bdwrite().
1600 KKASSERT(chain->bp != NULL);
1601 if (chain->data != bdata) {
1602 bcopy(chain->data, bdata, chain->bytes);
1604 } else if (wasinitial) {
1605 bzero(bdata, chain->bytes);
1608 * We have a problem. We were asked to COW but
1609 * we don't have any data to COW with!
1611 panic("hammer2_chain_modify: having a COW %p\n",
1614 if (chain->bp != nbp) {
1616 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1617 chain->bp->b_flags |= B_CLUSTEROK;
1620 chain->bp->b_flags |= B_RELBUF;
1625 BUF_KERNPROC(chain->bp);
1627 chain->data = bdata;
1628 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1631 panic("hammer2_chain_modify: illegal non-embedded type %d",
1637 hammer2_chain_setsubmod(trans, chain);
1641 * Mark the volume as having been modified. This short-cut version
1642 * does not have to lock the volume's chain, which allows the ioctl
1643 * code to make adjustments to connections without deadlocking. XXX
1645 * No ref is made on vchain when flagging it MODIFIED.
1648 hammer2_modify_volume(hammer2_mount_t *hmp)
1650 hammer2_voldata_lock(hmp);
1651 hammer2_voldata_unlock(hmp, 1);
1655 * This function returns the chain at the nearest key within the specified
1656 * range with the highest delete_tid. The core spinlock must be held on
1657 * call and the returned chain will be referenced but not locked.
1659 * The returned chain may or may not be in a deleted state. Note that
1660 * live chains have a delete_tid = MAX_TID.
1662 * This function will recurse through chain->rbtree as necessary and will
1663 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1664 * the iteration value is less than the current value of *key_nextp.
1666 * The caller should use (*key_nextp) to calculate the actual range of
1667 * the returned element, which will be (key_beg to *key_nextp - 1).
1669 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1670 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1671 * it will wind up being (key_end + 1).
1673 struct hammer2_chain_find_info {
1674 hammer2_chain_t *best;
1675 hammer2_key_t key_beg;
1676 hammer2_key_t key_end;
1677 hammer2_key_t key_next;
1680 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1681 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1685 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1686 hammer2_key_t key_beg, hammer2_key_t key_end)
1688 struct hammer2_chain_find_info info;
1689 hammer2_chain_layer_t *layer;
1692 info.key_beg = key_beg;
1693 info.key_end = key_end;
1694 info.key_next = *key_nextp;
1696 KKASSERT(parent->core->good == 0x1234);
1697 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1698 KKASSERT(layer->good == 0xABCD);
1699 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1700 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1703 *key_nextp = info.key_next;
1705 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1706 parent, key_beg, key_end, *key_nextp);
1714 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1716 struct hammer2_chain_find_info *info = data;
1717 hammer2_key_t child_beg;
1718 hammer2_key_t child_end;
1720 child_beg = child->bref.key;
1721 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1723 if (child_end < info->key_beg)
1725 if (child_beg > info->key_end)
1732 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1734 struct hammer2_chain_find_info *info = data;
1735 hammer2_chain_t *best;
1736 hammer2_key_t child_end;
1740 * Skip deleted chains which have been flushed (MOVED no longer set),
1741 * causes caller to check blockref array.
1743 if ((child->flags & (HAMMER2_CHAIN_DELETED | HAMMER2_CHAIN_MOVED)) ==
1744 HAMMER2_CHAIN_DELETED) {
1753 if ((best = info->best) == NULL) {
1755 * No previous best. Assign best
1758 } else if (best->bref.key <= info->key_beg &&
1759 child->bref.key <= info->key_beg) {
1761 * If our current best is flush with key_beg and child is
1762 * also flush with key_beg choose based on delete_tid.
1764 if (child->delete_tid > best->delete_tid) {
1767 } else if (child->bref.key < best->bref.key) {
1769 * Child has a nearer key and best is not flush with key_beg.
1770 * Truncate key_next to the old best key.
1773 if (info->key_next > best->bref.key || info->key_next == 0)
1774 info->key_next = best->bref.key;
1777 * Keep the current best but truncate key_next based on
1778 * child (occurs automatically).
1783 * Always truncate key_next based on child's end-of-range.
1785 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1786 if (child_end && (info->key_next > child_end || info->key_next == 0))
1787 info->key_next = child_end;
1793 * Retrieve the specified chain from a media blockref, creating the
1794 * in-memory chain structure and setting HAMMER2_CHAIN_REPLACE to
1795 * indicate that modifications must replace an existing bref in the
1798 * NULL is returned if the insertion races.
1800 * Caller must hold the parent locked shared or exclusive since we may
1801 * need the parent's bref array to find our block.
1804 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref)
1806 hammer2_mount_t *hmp = parent->hmp;
1807 hammer2_chain_core_t *above = parent->core;
1808 hammer2_chain_t *chain;
1811 * Allocate a chain structure representing the existing media
1812 * entry. Resulting chain has one ref and is not locked.
1814 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1815 hammer2_chain_core_alloc(NULL, chain, NULL);
1816 atomic_set_int(&chain->flags, HAMMER2_CHAIN_REPLACE);
1817 /* ref'd chain returned */
1820 * Link the chain into its parent. A spinlock is required to safely
1821 * access the RBTREE, and it is possible to collide with another
1822 * hammer2_chain_get() operation because the caller might only hold
1823 * a shared lock on the parent.
1825 KKASSERT(parent->refs > 0);
1826 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
1827 HAMMER2_CHAIN_INSERT_RACE);
1828 if ((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0) {
1829 kprintf("chain %p not on RBTREE\n", chain);
1830 hammer2_chain_drop(chain);
1835 * Return our new chain referenced but not locked.
1841 * Lookup initialization/completion API
1844 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1846 if (flags & HAMMER2_LOOKUP_SHARED) {
1847 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1848 HAMMER2_RESOLVE_SHARED);
1850 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1856 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1859 hammer2_chain_unlock(parent);
1864 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1866 hammer2_chain_t *oparent;
1867 hammer2_chain_t *bparent;
1868 hammer2_chain_t *nparent;
1869 hammer2_chain_core_t *above;
1872 above = oparent->above;
1874 spin_lock(&above->cst.spin);
1875 bparent = TAILQ_FIRST(&above->ownerq);
1876 hammer2_chain_ref(bparent);
1880 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1881 nparent = TAILQ_NEXT(nparent, core_entry);
1882 hammer2_chain_ref(nparent);
1883 spin_unlock(&above->cst.spin);
1886 * Be careful of order
1888 hammer2_chain_unlock(oparent);
1889 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1890 hammer2_chain_drop(bparent);
1893 * We might have raced a delete-duplicate.
1895 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1896 spin_lock(&above->cst.spin);
1897 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1898 spin_unlock(&above->cst.spin);
1899 hammer2_chain_ref(nparent);
1900 hammer2_chain_unlock(nparent);
1902 spin_lock(&above->cst.spin);
1903 continue; /* retry */
1905 spin_unlock(&above->cst.spin);
1915 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1916 * (*parentp) typically points to an inode but can also point to a related
1917 * indirect block and this function will recurse upwards and find the inode
1920 * (*parentp) must be exclusively locked and referenced and can be an inode
1921 * or an existing indirect block within the inode.
1923 * On return (*parentp) will be modified to point at the deepest parent chain
1924 * element encountered during the search, as a helper for an insertion or
1925 * deletion. The new (*parentp) will be locked and referenced and the old
1926 * will be unlocked and dereferenced (no change if they are both the same).
1928 * The matching chain will be returned exclusively locked. If NOLOCK is
1929 * requested the chain will be returned only referenced.
1931 * NULL is returned if no match was found, but (*parentp) will still
1932 * potentially be adjusted.
1934 * On return (*key_nextp) will point to an iterative value for key_beg.
1935 * (If NULL is returned (*key_nextp) is set to key_end).
1937 * This function will also recurse up the chain if the key is not within the
1938 * current parent's range. (*parentp) can never be set to NULL. An iteration
1939 * can simply allow (*parentp) to float inside the loop.
1941 * NOTE! chain->data is not always resolved. By default it will not be
1942 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1943 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1944 * BREF_TYPE_DATA as the device buffer can alias the logical file
1948 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1949 hammer2_key_t key_beg, hammer2_key_t key_end,
1950 int *cache_indexp, int flags)
1952 hammer2_mount_t *hmp;
1953 hammer2_chain_t *parent;
1954 hammer2_chain_t *chain;
1955 hammer2_blockref_t *base;
1956 hammer2_blockref_t *bref;
1957 hammer2_blockref_t bcopy;
1958 hammer2_key_t scan_beg;
1959 hammer2_key_t scan_end;
1960 hammer2_chain_core_t *above;
1962 int how_always = HAMMER2_RESOLVE_ALWAYS;
1963 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1966 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1967 how_maybe = how_always;
1968 how = HAMMER2_RESOLVE_ALWAYS;
1969 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1970 how = HAMMER2_RESOLVE_NEVER;
1972 how = HAMMER2_RESOLVE_MAYBE;
1974 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1975 how_maybe |= HAMMER2_RESOLVE_SHARED;
1976 how_always |= HAMMER2_RESOLVE_SHARED;
1977 how |= HAMMER2_RESOLVE_SHARED;
1981 * Recurse (*parentp) upward if necessary until the parent completely
1982 * encloses the key range or we hit the inode.
1984 * This function handles races against the flusher doing a delete-
1985 * duplicate above us and re-homes the parent to the duplicate in
1986 * that case, otherwise we'd wind up recursing down a stale chain.
1991 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1992 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1993 scan_beg = parent->bref.key;
1994 scan_end = scan_beg +
1995 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1996 if (key_beg >= scan_beg && key_end <= scan_end)
1998 parent = hammer2_chain_getparent(parentp, how_maybe);
2003 * Locate the blockref array. Currently we do a fully associative
2004 * search through the array.
2006 switch(parent->bref.type) {
2007 case HAMMER2_BREF_TYPE_INODE:
2009 * Special shortcut for embedded data returns the inode
2010 * itself. Callers must detect this condition and access
2011 * the embedded data (the strategy code does this for us).
2013 * This is only applicable to regular files and softlinks.
2015 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2016 if (flags & HAMMER2_LOOKUP_NOLOCK)
2017 hammer2_chain_ref(parent);
2019 hammer2_chain_lock(parent, how_always);
2020 *key_nextp = key_end + 1;
2023 base = &parent->data->ipdata.u.blockset.blockref[0];
2024 count = HAMMER2_SET_COUNT;
2026 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2027 case HAMMER2_BREF_TYPE_INDIRECT:
2029 * Handle MATCHIND on the parent
2031 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2032 scan_beg = parent->bref.key;
2033 scan_end = scan_beg +
2034 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2035 if (key_beg == scan_beg && key_end == scan_end) {
2037 hammer2_chain_lock(chain, how_maybe);
2038 *key_nextp = scan_end + 1;
2043 * Optimize indirect blocks in the INITIAL state to avoid
2046 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2049 if (parent->data == NULL)
2050 panic("parent->data is NULL");
2051 base = &parent->data->npdata[0];
2053 count = parent->bytes / sizeof(hammer2_blockref_t);
2055 case HAMMER2_BREF_TYPE_VOLUME:
2056 base = &hmp->voldata.sroot_blockset.blockref[0];
2057 count = HAMMER2_SET_COUNT;
2059 case HAMMER2_BREF_TYPE_FREEMAP:
2060 base = &hmp->voldata.freemap_blockset.blockref[0];
2061 count = HAMMER2_SET_COUNT;
2064 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2066 base = NULL; /* safety */
2067 count = 0; /* safety */
2071 * Merged scan to find next candidate.
2073 * hammer2_base_*() functions require the above->live_* fields
2074 * to be synchronized.
2076 * We need to hold the spinlock to access the block array and RB tree
2077 * and to interlock chain creation.
2079 above = parent->core;
2080 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2081 hammer2_chain_countbrefs(parent, base, count);
2086 spin_lock(&above->cst.spin);
2087 chain = hammer2_combined_find(parent, base, count,
2088 cache_indexp, key_nextp,
2089 key_beg, key_end, &bref);
2092 * Exhausted parent chain, iterate.
2095 spin_unlock(&above->cst.spin);
2096 if (key_beg == key_end) /* short cut single-key case */
2098 return (hammer2_chain_next(parentp, NULL, key_nextp,
2100 cache_indexp, flags));
2104 * Selected from blockref or in-memory chain.
2106 if (chain == NULL) {
2108 spin_unlock(&above->cst.spin);
2109 chain = hammer2_chain_get(parent, &bcopy);
2110 if (chain == NULL) {
2111 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2112 parent, key_beg, key_end);
2115 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2116 hammer2_chain_drop(chain);
2120 hammer2_chain_ref(chain);
2121 spin_unlock(&above->cst.spin);
2123 /* chain is referenced but not locked */
2126 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2128 * NOTE: chain's key range is not relevant as there might be
2129 * one-offs within the range that are not deleted.
2131 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2132 hammer2_chain_drop(chain);
2133 key_beg = *key_nextp;
2134 if (key_beg == 0 || key_beg > key_end)
2140 * If the chain element is an indirect block it becomes the new
2141 * parent and we loop on it. We must maintain our top-down locks
2142 * to prevent the flusher from interfering (i.e. doing a
2143 * delete-duplicate and leaving us recursing down a deleted chain).
2145 * The parent always has to be locked with at least RESOLVE_MAYBE
2146 * so we can access its data. It might need a fixup if the caller
2147 * passed incompatible flags. Be careful not to cause a deadlock
2148 * as a data-load requires an exclusive lock.
2150 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2151 * range is within the requested key range we return the indirect
2152 * block and do NOT loop. This is usually only used to acquire
2155 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2156 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2157 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2158 hammer2_chain_unlock(parent);
2159 *parentp = parent = chain;
2163 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2166 * All done, return the chain
2172 * After having issued a lookup we can iterate all matching keys.
2174 * If chain is non-NULL we continue the iteration from just after it's index.
2176 * If chain is NULL we assume the parent was exhausted and continue the
2177 * iteration at the next parent.
2179 * parent must be locked on entry and remains locked throughout. chain's
2180 * lock status must match flags. Chain is always at least referenced.
2182 * WARNING! The MATCHIND flag does not apply to this function.
2185 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2186 hammer2_key_t *key_nextp,
2187 hammer2_key_t key_beg, hammer2_key_t key_end,
2188 int *cache_indexp, int flags)
2190 hammer2_chain_t *parent;
2194 * Calculate locking flags for upward recursion.
2196 how_maybe = HAMMER2_RESOLVE_MAYBE;
2197 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2198 how_maybe |= HAMMER2_RESOLVE_SHARED;
2203 * Calculate the next index and recalculate the parent if necessary.
2206 key_beg = chain->bref.key +
2207 ((hammer2_key_t)1 << chain->bref.keybits);
2208 if (flags & HAMMER2_LOOKUP_NOLOCK)
2209 hammer2_chain_drop(chain);
2211 hammer2_chain_unlock(chain);
2214 * Any scan where the lookup returned degenerate data embedded
2215 * in the inode has an invalid index and must terminate.
2217 if (chain == parent)
2219 if (key_beg == 0 || key_beg > key_end)
2222 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2223 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2225 * We reached the end of the iteration.
2230 * Continue iteration with next parent unless the current
2231 * parent covers the range.
2233 key_beg = parent->bref.key +
2234 ((hammer2_key_t)1 << parent->bref.keybits);
2235 if (key_beg == 0 || key_beg > key_end)
2237 parent = hammer2_chain_getparent(parentp, how_maybe);
2243 return (hammer2_chain_lookup(parentp, key_nextp,
2245 cache_indexp, flags));
2249 * Create and return a new hammer2 system memory structure of the specified
2250 * key, type and size and insert it under (*parentp). This is a full
2251 * insertion, based on the supplied key/keybits, and may involve creating
2252 * indirect blocks and moving other chains around via delete/duplicate.
2254 * (*parentp) must be exclusive locked and may be replaced on return
2255 * depending on how much work the function had to do.
2257 * (*chainp) usually starts out NULL and returns the newly created chain,
2258 * but if the caller desires the caller may allocate a disconnected chain
2259 * and pass it in instead. (It is also possible for the caller to use
2260 * chain_duplicate() to create a disconnected chain, manipulate it, then
2261 * pass it into this function to insert it).
2263 * This function should NOT be used to insert INDIRECT blocks. It is
2264 * typically used to create/insert inodes and data blocks.
2266 * Caller must pass-in an exclusively locked parent the new chain is to
2267 * be inserted under, and optionally pass-in a disconnected, exclusively
2268 * locked chain to insert (else we create a new chain). The function will
2269 * adjust (*parentp) as necessary, create or connect the chain, and
2270 * return an exclusively locked chain in *chainp.
2273 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2274 hammer2_chain_t **chainp,
2275 hammer2_key_t key, int keybits, int type, size_t bytes)
2277 hammer2_mount_t *hmp;
2278 hammer2_chain_t *chain;
2279 hammer2_chain_t *parent = *parentp;
2280 hammer2_chain_core_t *above;
2281 hammer2_blockref_t *base;
2282 hammer2_blockref_t dummy;
2287 above = parent->core;
2288 KKASSERT(ccms_thread_lock_owned(&above->cst));
2292 if (chain == NULL) {
2294 * First allocate media space and construct the dummy bref,
2295 * then allocate the in-memory chain structure. Set the
2296 * INITIAL flag for fresh chains.
2298 bzero(&dummy, sizeof(dummy));
2301 dummy.keybits = keybits;
2302 dummy.data_off = hammer2_getradix(bytes);
2303 dummy.methods = parent->bref.methods;
2304 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2305 hammer2_chain_core_alloc(trans, chain, NULL);
2307 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2310 * Lock the chain manually, chain_lock will load the chain
2311 * which we do NOT want to do. (note: chain->refs is set
2312 * to 1 by chain_alloc() for us, but lockcnt is not).
2315 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2319 * We do NOT set INITIAL here (yet). INITIAL is only
2320 * used for indirect blocks.
2322 * Recalculate bytes to reflect the actual media block
2325 bytes = (hammer2_off_t)1 <<
2326 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2327 chain->bytes = bytes;
2330 case HAMMER2_BREF_TYPE_VOLUME:
2331 case HAMMER2_BREF_TYPE_FREEMAP:
2332 panic("hammer2_chain_create: called with volume type");
2334 case HAMMER2_BREF_TYPE_INODE:
2335 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2336 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2337 chain->data = kmalloc(sizeof(chain->data->ipdata),
2338 hmp->mchain, M_WAITOK | M_ZERO);
2340 case HAMMER2_BREF_TYPE_INDIRECT:
2341 panic("hammer2_chain_create: cannot be used to"
2342 "create indirect block");
2344 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2345 panic("hammer2_chain_create: cannot be used to"
2346 "create freemap root or node");
2348 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2349 KKASSERT(bytes == sizeof(chain->data->bmdata));
2350 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2351 chain->data = kmalloc(sizeof(chain->data->bmdata),
2352 hmp->mchain, M_WAITOK | M_ZERO);
2354 case HAMMER2_BREF_TYPE_DATA:
2356 /* leave chain->data NULL */
2357 KKASSERT(chain->data == NULL);
2362 * Potentially update the existing chain's key/keybits.
2364 * Do NOT mess with the current state of the INITIAL flag.
2366 chain->bref.key = key;
2367 chain->bref.keybits = keybits;
2368 KKASSERT(chain->above == NULL);
2372 * Calculate how many entries we have in the blockref array and
2373 * determine if an indirect block is required.
2376 above = parent->core;
2378 switch(parent->bref.type) {
2379 case HAMMER2_BREF_TYPE_INODE:
2380 KKASSERT((parent->data->ipdata.op_flags &
2381 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2382 KKASSERT(parent->data != NULL);
2383 base = &parent->data->ipdata.u.blockset.blockref[0];
2384 count = HAMMER2_SET_COUNT;
2386 case HAMMER2_BREF_TYPE_INDIRECT:
2387 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2388 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2391 base = &parent->data->npdata[0];
2392 count = parent->bytes / sizeof(hammer2_blockref_t);
2394 case HAMMER2_BREF_TYPE_VOLUME:
2395 KKASSERT(parent->data != NULL);
2396 base = &hmp->voldata.sroot_blockset.blockref[0];
2397 count = HAMMER2_SET_COUNT;
2399 case HAMMER2_BREF_TYPE_FREEMAP:
2400 KKASSERT(parent->data != NULL);
2401 base = &hmp->voldata.freemap_blockset.blockref[0];
2402 count = HAMMER2_SET_COUNT;
2405 panic("hammer2_chain_create: unrecognized blockref type: %d",
2413 * Make sure we've counted the brefs
2415 if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2416 hammer2_chain_countbrefs(parent, base, count);
2418 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2421 * If no free blockref could be found we must create an indirect
2422 * block and move a number of blockrefs into it. With the parent
2423 * locked we can safely lock each child in order to delete+duplicate
2424 * it without causing a deadlock.
2426 * This may return the new indirect block or the old parent depending
2427 * on where the key falls. NULL is returned on error.
2429 if (above->live_count == count) {
2430 hammer2_chain_t *nparent;
2432 nparent = hammer2_chain_create_indirect(trans, parent,
2435 if (nparent == NULL) {
2437 hammer2_chain_drop(chain);
2441 if (parent != nparent) {
2442 hammer2_chain_unlock(parent);
2443 parent = *parentp = nparent;
2449 * Link the chain into its parent. Later on we will have to set
2450 * the MOVED bit in situations where we don't mark the new chain
2451 * as being modified.
2453 if (chain->above != NULL)
2454 panic("hammer2: hammer2_chain_create: chain already connected");
2455 KKASSERT(chain->above == NULL);
2456 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2457 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
2458 HAMMER2_CHAIN_INSERT_LIVE);
2462 * Mark the newly created chain modified.
2464 * Device buffers are not instantiated for DATA elements
2465 * as these are handled by logical buffers.
2467 * Indirect and freemap node indirect blocks are handled
2468 * by hammer2_chain_create_indirect() and not by this
2471 * Data for all other bref types is expected to be
2472 * instantiated (INODE, LEAF).
2474 switch(chain->bref.type) {
2475 case HAMMER2_BREF_TYPE_DATA:
2476 hammer2_chain_modify(trans, &chain,
2477 HAMMER2_MODIFY_OPTDATA |
2478 HAMMER2_MODIFY_ASSERTNOCOPY);
2480 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2481 case HAMMER2_BREF_TYPE_INODE:
2482 hammer2_chain_modify(trans, &chain,
2483 HAMMER2_MODIFY_ASSERTNOCOPY);
2487 * Remaining types are not supported by this function.
2488 * In particular, INDIRECT and LEAF_NODE types are
2489 * handled by create_indirect().
2491 panic("hammer2_chain_create: bad type: %d",
2498 * When reconnecting a chain we must set MOVED and setsubmod
2499 * so the flush recognizes that it must update the bref in
2502 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2503 hammer2_chain_ref(chain);
2504 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2506 hammer2_chain_setsubmod(trans, chain);
2516 * Replace (*chainp) with a duplicate. The original *chainp is unlocked
2517 * and the replacement will be returned locked. Both the original and the
2518 * new chain will share the same RBTREE (have the same chain->core), with
2519 * the new chain becoming the 'current' chain (meaning it is the first in
2520 * the linked list at core->chain_first).
2522 * If (parent) is non-NULL then the new duplicated chain is inserted under
2525 * If (parent) is NULL then the new duplicated chain is not inserted anywhere,
2526 * similar to if it had just been chain_alloc()'d (suitable for passing into
2527 * hammer2_chain_create() after this function returns).
2529 * NOTE! Duplication is used in order to retain the original topology to
2530 * support flush synchronization points. Both the original and the
2531 * new chain will have the same transaction id and thus the operation
2532 * appears atomic w/regards to media flushes.
2534 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2535 hammer2_chain_t *nchain);
2538 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t *parent,
2539 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2542 hammer2_mount_t *hmp;
2543 hammer2_blockref_t *base;
2544 hammer2_chain_t *ochain;
2545 hammer2_chain_t *nchain;
2546 hammer2_chain_core_t *above;
2553 * First create a duplicate of the chain structure, associating
2554 * it with the same core, making it the same size, pointing it
2555 * to the same bref (the same media block).
2560 bref = &ochain->bref;
2561 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2563 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2564 hammer2_chain_core_alloc(trans, nchain, ochain);
2565 bytes = (hammer2_off_t)1 <<
2566 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2567 nchain->bytes = bytes;
2568 nchain->modify_tid = ochain->modify_tid;
2570 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2571 HAMMER2_RESOLVE_NOREF);
2572 hammer2_chain_dup_fixup(ochain, nchain);
2573 /* nchain has 1 ref */
2576 * If parent is not NULL, insert the duplicated chain into the
2577 * parent. The newly duplicated chain must be marked MOVED and
2578 * SUBMODIFIED set in its parent(s).
2580 * Having both chains locked is extremely important for atomicy.
2584 * Locate a free blockref in the parent's array
2586 above = parent->core;
2587 KKASSERT(ccms_thread_lock_owned(&above->cst));
2589 switch(parent->bref.type) {
2590 case HAMMER2_BREF_TYPE_INODE:
2591 KKASSERT((parent->data->ipdata.op_flags &
2592 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2593 KKASSERT(parent->data != NULL);
2594 base = &parent->data->ipdata.u.blockset.blockref[0];
2595 count = HAMMER2_SET_COUNT;
2597 case HAMMER2_BREF_TYPE_INDIRECT:
2598 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2599 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2602 KKASSERT(parent->data != NULL);
2603 base = &parent->data->npdata[0];
2605 count = parent->bytes / sizeof(hammer2_blockref_t);
2607 case HAMMER2_BREF_TYPE_VOLUME:
2608 KKASSERT(parent->data != NULL);
2609 base = &hmp->voldata.sroot_blockset.blockref[0];
2610 count = HAMMER2_SET_COUNT;
2612 case HAMMER2_BREF_TYPE_FREEMAP:
2613 KKASSERT(parent->data != NULL);
2614 base = &hmp->voldata.freemap_blockset.blockref[0];
2615 count = HAMMER2_SET_COUNT;
2618 panic("hammer2_chain_create: unrecognized "
2619 "blockref type: %d",
2625 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2626 KKASSERT(parent->refs > 0);
2627 hammer2_chain_insert(above, nchain, HAMMER2_CHAIN_INSERT_SPIN |
2628 HAMMER2_CHAIN_INSERT_LIVE);
2630 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2631 hammer2_chain_ref(nchain);
2632 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2634 hammer2_chain_setsubmod(trans, nchain);
2638 * We have to unlock ochain to flush any dirty data, asserting the
2639 * case (data == NULL) to catch any extra locks that might have been
2640 * present, then transfer state to nchain.
2642 oflags = ochain->flags;
2643 odata = ochain->data;
2644 hammer2_chain_unlock(ochain);
2645 KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2646 ochain->data == NULL);
2648 if (oflags & HAMMER2_CHAIN_INITIAL)
2649 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2652 * WARNING! We should never resolve DATA to device buffers
2653 * (XXX allow it if the caller did?), and since
2654 * we currently do not have the logical buffer cache
2655 * buffer in-hand to fix its cached physical offset
2656 * we also force the modify code to not COW it. XXX
2658 * WARNING! nchain should have only one manual ref plus additional
2659 * refs related to flags or the hammer2_chain_modify()
2660 * replacement could leave a ref hanging.
2662 if (oflags & HAMMER2_CHAIN_MODIFIED) {
2663 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2664 hammer2_chain_modify(trans, &nchain,
2665 HAMMER2_MODIFY_OPTDATA |
2666 HAMMER2_MODIFY_NOREALLOC |
2667 HAMMER2_MODIFY_ASSERTNOCOPY);
2668 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2669 hammer2_chain_modify(trans, &nchain,
2670 HAMMER2_MODIFY_OPTDATA |
2671 HAMMER2_MODIFY_ASSERTNOCOPY);
2673 hammer2_chain_modify(trans, &nchain,
2674 HAMMER2_MODIFY_ASSERTNOCOPY);
2677 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2679 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2682 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_ALWAYS);
2683 hammer2_chain_unlock(nchain);
2686 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2691 * Special in-place delete-duplicate sequence which does not require a
2692 * locked parent. (*chainp) is marked DELETED and atomically replaced
2693 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2694 * order to ensure that lookups do not race us.
2696 * If the input chain is already marked deleted the duplicated chain will
2697 * also be marked deleted. This case can occur when an inode is removed
2698 * from the filesystem but programs still have an open descriptor to it.
2701 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2704 hammer2_mount_t *hmp;
2705 hammer2_chain_t *ochain;
2706 hammer2_chain_t *nchain;
2707 hammer2_chain_core_t *above;
2713 oflags = ochain->flags;
2717 * Shortcut DELETED case if possible (only if delete_tid already
2718 * matches the transaction id).
2720 if ((oflags & HAMMER2_CHAIN_DELETED) &&
2721 ochain->delete_tid == trans->sync_tid) {
2726 * First create a duplicate of the chain structure.
2727 * (nchain is allocated with one ref).
2729 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2730 if (flags & HAMMER2_DELDUP_RECORE)
2731 hammer2_chain_core_alloc(trans, nchain, NULL);
2733 hammer2_chain_core_alloc(trans, nchain, ochain);
2734 above = ochain->above;
2736 bytes = (hammer2_off_t)1 <<
2737 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2738 nchain->bytes = bytes;
2739 nchain->modify_tid = ochain->modify_tid;
2740 nchain->data_count += ochain->data_count;
2741 nchain->inode_count += ochain->inode_count;
2744 * Lock nchain so both chains are now locked (extremely important
2745 * for atomicy). Mark ochain deleted and reinsert into the topology
2746 * and insert nchain all in one go.
2748 * If the ochain is already deleted it is left alone and nchain
2749 * is inserted into the topology as a deleted chain. This is
2750 * important because it allows ongoing operations to be executed
2751 * on a deleted inode which still has open descriptors.
2753 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2754 hammer2_chain_dup_fixup(ochain, nchain);
2755 /* extra ref still present from original allocation */
2757 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2758 spin_lock(&above->cst.spin);
2759 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2761 if (oflags & HAMMER2_CHAIN_DELETED) {
2762 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
2763 nchain->delete_tid = trans->sync_tid;
2764 /*nchain->delete_gen = ++trans->delete_gen;*/
2766 ochain->delete_tid = trans->sync_tid;
2767 /*ochain->delete_gen = ++trans->delete_gen;*/
2768 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2769 atomic_add_int(&above->live_count, -1);
2772 hammer2_chain_insert(above, nchain,
2773 ((oflags & HAMMER2_CHAIN_DELETED) ?
2774 0: HAMMER2_CHAIN_INSERT_LIVE));
2776 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2777 hammer2_chain_ref(ochain);
2778 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2780 spin_unlock(&above->cst.spin);
2783 * We have to unlock ochain to flush any dirty data, asserting the
2784 * case (data == NULL) to catch any extra locks that might have been
2785 * present, then transfer state to nchain.
2787 odata = ochain->data;
2788 hammer2_chain_unlock(ochain); /* replacing ochain */
2789 KKASSERT(ochain->bref.type == HAMMER2_BREF_TYPE_INODE ||
2790 ochain->data == NULL);
2792 if (oflags & HAMMER2_CHAIN_INITIAL)
2793 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2796 * WARNING! We should never resolve DATA to device buffers
2797 * (XXX allow it if the caller did?), and since
2798 * we currently do not have the logical buffer cache
2799 * buffer in-hand to fix its cached physical offset
2800 * we also force the modify code to not COW it. XXX
2802 if (oflags & HAMMER2_CHAIN_MODIFIED) {
2803 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2804 hammer2_chain_modify(trans, &nchain,
2805 HAMMER2_MODIFY_OPTDATA |
2806 HAMMER2_MODIFY_NOREALLOC |
2807 HAMMER2_MODIFY_ASSERTNOCOPY);
2808 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2809 hammer2_chain_modify(trans, &nchain,
2810 HAMMER2_MODIFY_OPTDATA |
2811 HAMMER2_MODIFY_ASSERTNOCOPY);
2813 hammer2_chain_modify(trans, &nchain,
2814 HAMMER2_MODIFY_ASSERTNOCOPY);
2816 hammer2_chain_drop(nchain);
2818 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2819 hammer2_chain_drop(nchain);
2820 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2821 hammer2_chain_drop(nchain);
2823 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_ALWAYS |
2824 HAMMER2_RESOLVE_NOREF);
2825 hammer2_chain_unlock(nchain);
2830 * Unconditionally set the MOVED and SUBMODIFIED bit to force
2831 * update of parent bref and indirect blockrefs during flush.
2833 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2834 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2835 hammer2_chain_ref(nchain);
2837 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2838 hammer2_chain_setsubmod(trans, nchain);
2843 * Helper function to fixup inodes. The caller procedure stack may hold
2844 * multiple locks on ochain if it represents an inode, preventing our
2845 * unlock from retiring its state to the buffer cache.
2847 * In this situation any attempt to access the buffer cache could result
2848 * either in stale data or a deadlock. Work around the problem by copying
2849 * the embedded data directly.
2853 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
2855 if (ochain->data == NULL)
2857 switch(ochain->bref.type) {
2858 case HAMMER2_BREF_TYPE_INODE:
2859 KKASSERT(nchain->data == NULL);
2860 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2861 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2862 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2863 nchain->data->ipdata = ochain->data->ipdata;
2865 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2866 KKASSERT(nchain->data == NULL);
2867 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2868 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
2869 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2870 bcopy(ochain->data->bmdata,
2871 nchain->data->bmdata,
2872 sizeof(nchain->data->bmdata));
2880 * Create a snapshot of the specified {parent, chain} with the specified
2881 * label. The originating hammer2_inode must be exclusively locked for
2885 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t *ochain,
2886 hammer2_ioc_pfs_t *pfs)
2888 hammer2_mount_t *hmp;
2889 hammer2_chain_t *nchain;
2890 hammer2_chain_t *chain;
2891 hammer2_chain_t *parent;
2892 hammer2_inode_data_t *ipdata;
2894 hammer2_key_t key_dummy;
2898 int cache_index = -1;
2900 name_len = strlen(pfs->name);
2901 lhc = hammer2_dirhash(pfs->name, name_len);
2904 opfs_clid = ochain->data->ipdata.pfs_clid;
2905 KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2908 * Get second lock for duplication to replace, original lock
2909 * will be left intact (caller must unlock the original chain).
2912 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2915 * Create disconnected duplicate flagged as a snapshot
2917 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_RECYCLE);
2918 hammer2_chain_duplicate(trans, NULL, &nchain, NULL, 1);
2921 * Create named entry in the super-root.
2923 parent = hammer2_inode_lock_ex(hmp->sroot);
2925 while (error == 0) {
2926 chain = hammer2_chain_lookup(&parent, &key_dummy,
2927 lhc, lhc, &cache_index, 0);
2930 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
2932 hammer2_chain_unlock(chain);
2936 hammer2_chain_create(trans, &parent, &nchain, lhc, 0,
2937 HAMMER2_BREF_TYPE_INODE,
2938 HAMMER2_INODE_BYTES);
2939 hammer2_chain_modify(trans, &nchain, HAMMER2_MODIFY_ASSERTNOCOPY);
2940 hammer2_inode_unlock_ex(hmp->sroot, parent);
2941 parent = NULL; /* safety */
2946 ipdata = &nchain->data->ipdata;
2947 ipdata->name_key = lhc;
2948 ipdata->name_len = name_len;
2949 ksnprintf(ipdata->filename, sizeof(ipdata->filename), "%s", pfs->name);
2952 * Set PFS type, generate a unique filesystem id, and generate
2953 * a cluster id. Use the same clid when snapshotting a PFS root,
2954 * which theoretically allows the snapshot to be used as part of
2955 * the same cluster (perhaps as a cache).
2957 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2958 kern_uuidgen(&ipdata->pfs_fsid, 1);
2959 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
2960 ipdata->pfs_clid = opfs_clid;
2962 kern_uuidgen(&ipdata->pfs_clid, 1);
2963 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
2966 * Issue a restricted flush of the snapshot. This is a synchronous
2969 trans->flags |= HAMMER2_TRANS_RESTRICTED;
2970 kprintf("SNAPSHOTA\n");
2971 tsleep(trans, 0, "snapslp", hz*4);
2972 kprintf("SNAPSHOTB\n");
2973 hammer2_chain_flush(trans, nchain);
2974 trans->flags &= ~HAMMER2_TRANS_RESTRICTED;
2978 * Remove the link b/c nchain is a snapshot and snapshots don't
2979 * follow CHAIN_DELETED semantics ?
2984 KKASSERT(chain->duplink == nchain);
2985 KKASSERT(chain->core == nchain->core);
2986 KKASSERT(nchain->refs >= 2);
2987 chain->duplink = nchain->duplink;
2988 atomic_clear_int(&nchain->flags, HAMMER2_CHAIN_DUPTARGET);
2989 hammer2_chain_drop(nchain);
2992 kprintf("snapshot %s nchain->refs %d nchain->flags %08x\n",
2993 pfs->name, nchain->refs, nchain->flags);
2994 hammer2_chain_unlock(nchain);
3000 * Create an indirect block that covers one or more of the elements in the
3001 * current parent. Either returns the existing parent with no locking or
3002 * ref changes or returns the new indirect block locked and referenced
3003 * and leaving the original parent lock/ref intact as well.
3005 * If an error occurs, NULL is returned and *errorp is set to the error.
3007 * The returned chain depends on where the specified key falls.
3009 * The key/keybits for the indirect mode only needs to follow three rules:
3011 * (1) That all elements underneath it fit within its key space and
3013 * (2) That all elements outside it are outside its key space.
3015 * (3) When creating the new indirect block any elements in the current
3016 * parent that fit within the new indirect block's keyspace must be
3017 * moved into the new indirect block.
3019 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3020 * keyspace the the current parent, but lookup/iteration rules will
3021 * ensure (and must ensure) that rule (2) for all parents leading up
3022 * to the nearest inode or the root volume header is adhered to. This
3023 * is accomplished by always recursing through matching keyspaces in
3024 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3026 * The current implementation calculates the current worst-case keyspace by
3027 * iterating the current parent and then divides it into two halves, choosing
3028 * whichever half has the most elements (not necessarily the half containing
3029 * the requested key).
3031 * We can also opt to use the half with the least number of elements. This
3032 * causes lower-numbered keys (aka logical file offsets) to recurse through
3033 * fewer indirect blocks and higher-numbered keys to recurse through more.
3034 * This also has the risk of not moving enough elements to the new indirect
3035 * block and being forced to create several indirect blocks before the element
3038 * Must be called with an exclusively locked parent.
3040 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3041 hammer2_key_t *keyp, int keybits,
3042 hammer2_blockref_t *base, int count);
3043 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3044 hammer2_key_t *keyp, int keybits,
3045 hammer2_blockref_t *base, int count);
3048 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3049 hammer2_key_t create_key, int create_bits,
3050 int for_type, int *errorp)
3052 hammer2_mount_t *hmp;
3053 hammer2_chain_core_t *above;
3054 hammer2_chain_core_t *icore;
3055 hammer2_blockref_t *base;
3056 hammer2_blockref_t *bref;
3057 hammer2_blockref_t bcopy;
3058 hammer2_chain_t *chain;
3059 hammer2_chain_t *ichain;
3060 hammer2_chain_t dummy;
3061 hammer2_key_t key = create_key;
3062 hammer2_key_t key_beg;
3063 hammer2_key_t key_end;
3064 hammer2_key_t key_next;
3065 int keybits = create_bits;
3072 * Calculate the base blockref pointer or NULL if the chain
3073 * is known to be empty. We need to calculate the array count
3074 * for RB lookups either way.
3078 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3079 above = parent->core;
3081 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3082 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3085 switch(parent->bref.type) {
3086 case HAMMER2_BREF_TYPE_INODE:
3087 count = HAMMER2_SET_COUNT;
3089 case HAMMER2_BREF_TYPE_INDIRECT:
3090 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3091 count = parent->bytes / sizeof(hammer2_blockref_t);
3093 case HAMMER2_BREF_TYPE_VOLUME:
3094 count = HAMMER2_SET_COUNT;
3096 case HAMMER2_BREF_TYPE_FREEMAP:
3097 count = HAMMER2_SET_COUNT;
3100 panic("hammer2_chain_create_indirect: "
3101 "unrecognized blockref type: %d",
3107 switch(parent->bref.type) {
3108 case HAMMER2_BREF_TYPE_INODE:
3109 base = &parent->data->ipdata.u.blockset.blockref[0];
3110 count = HAMMER2_SET_COUNT;
3112 case HAMMER2_BREF_TYPE_INDIRECT:
3113 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3114 base = &parent->data->npdata[0];
3115 count = parent->bytes / sizeof(hammer2_blockref_t);
3117 case HAMMER2_BREF_TYPE_VOLUME:
3118 base = &hmp->voldata.sroot_blockset.blockref[0];
3119 count = HAMMER2_SET_COUNT;
3121 case HAMMER2_BREF_TYPE_FREEMAP:
3122 base = &hmp->voldata.freemap_blockset.blockref[0];
3123 count = HAMMER2_SET_COUNT;
3126 panic("hammer2_chain_create_indirect: "
3127 "unrecognized blockref type: %d",
3135 * dummy used in later chain allocation (no longer used for lookups).
3137 bzero(&dummy, sizeof(dummy));
3138 dummy.delete_tid = HAMMER2_MAX_TID;
3141 * When creating an indirect block for a freemap node or leaf
3142 * the key/keybits must be fitted to static radix levels because
3143 * particular radix levels use particular reserved blocks in the
3146 * This routine calculates the key/radix of the indirect block
3147 * we need to create, and whether it is on the high-side or the
3150 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3151 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3152 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3155 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3160 * Normalize the key for the radix being represented, keeping the
3161 * high bits and throwing away the low bits.
3163 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3166 * How big should our new indirect block be? It has to be at least
3167 * as large as its parent.
3169 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3170 nbytes = HAMMER2_IND_BYTES_MIN;
3172 nbytes = HAMMER2_IND_BYTES_MAX;
3173 if (nbytes < count * sizeof(hammer2_blockref_t))
3174 nbytes = count * sizeof(hammer2_blockref_t);
3177 * Ok, create our new indirect block
3179 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3180 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3181 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3183 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3185 dummy.bref.key = key;
3186 dummy.bref.keybits = keybits;
3187 dummy.bref.data_off = hammer2_getradix(nbytes);
3188 dummy.bref.methods = parent->bref.methods;
3190 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3191 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3192 hammer2_chain_core_alloc(trans, ichain, NULL);
3193 icore = ichain->core;
3194 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3195 hammer2_chain_drop(ichain); /* excess ref from alloc */
3198 * We have to mark it modified to allocate its block, but use
3199 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3200 * it won't be acted upon by the flush code.
3202 * XXX leave the node unmodified, depend on the SUBMODIFIED
3203 * flush to assign and modify parent blocks.
3205 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3208 * Iterate the original parent and move the matching brefs into
3209 * the new indirect block.
3211 * XXX handle flushes.
3214 key_end = HAMMER2_MAX_TID;
3216 spin_lock(&above->cst.spin);
3220 kprintf("I %p,%d/%d key %016jx %016jx/%d nbytes=%d\n",
3221 parent, parent->core->live_count,
3222 (int)(parent->bytes / sizeof(hammer2_blockref_t)),
3223 create_key, key, keybits, (int)nbytes);
3226 if (++loops > 8192) {
3227 spin_unlock(&above->cst.spin);
3228 panic("shit parent=%p base/count %p:%d\n",
3229 parent, base, count);
3233 * NOTE: spinlock stays intact, returned chain (if not NULL)
3234 * is not referenced or locked.
3236 chain = hammer2_combined_find(parent, base, count,
3237 &cache_index, &key_next,
3242 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3243 if (key_next == 0 || key_next > key_end)
3248 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3250 kprintf("%c%p %016jx,%016jx,%016jx bref=%p,%016jx\n",
3251 (chain ? 'm' : 'd'),
3253 key_beg, key_end, key_next,
3254 bref, (bref ? bref->key : 0));
3258 * Skip keys that are not within the key/radix of the new
3259 * indirect block. They stay in the parent.
3261 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3262 (key ^ bref->key)) != 0) {
3263 if (key_next == 0 || key_next > key_end)
3270 * Load the new indirect block by acquiring or allocating
3271 * the related chain, then move it to the new parent (ichain)
3272 * via DELETE-DUPLICATE.
3274 * WARNING! above->cst.spin must be held when parent is
3275 * modified, even though we own the full blown lock,
3276 * to deal with setsubmod and rename races.
3277 * (XXX remove this req).
3281 * Use chain already present in the RBTREE
3283 hammer2_chain_ref(chain);
3284 spin_unlock(&above->cst.spin);
3285 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3286 HAMMER2_RESOLVE_NOREF);
3289 * Get chain for blockref element. _get returns NULL
3290 * on insertion race.
3293 spin_unlock(&above->cst.spin);
3294 chain = hammer2_chain_get(parent, bref);
3297 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3298 hammer2_chain_drop(chain);
3301 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3302 HAMMER2_RESOLVE_NOREF);
3304 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
3305 hammer2_chain_duplicate(trans, ichain, &chain, NULL, 0);
3306 hammer2_chain_unlock(chain);
3307 KKASSERT(parent->refs > 0);
3309 spin_lock(&above->cst.spin);
3310 if (key_next == 0 || key_next > key_end)
3314 spin_unlock(&above->cst.spin);
3317 * Insert the new indirect block into the parent now that we've
3318 * cleared out some entries in the parent. We calculated a good
3319 * insertion index in the loop above (ichain->index).
3321 * We don't have to set MOVED here because we mark ichain modified
3322 * down below (so the normal modified -> flush -> set-moved sequence
3325 * The insertion shouldn't race as this is a completely new block
3326 * and the parent is locked.
3328 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3329 hammer2_chain_insert(above, ichain, HAMMER2_CHAIN_INSERT_SPIN |
3330 HAMMER2_CHAIN_INSERT_LIVE);
3333 * Mark the new indirect block modified after insertion, which
3334 * will propagate up through parent all the way to the root and
3335 * also allocate the physical block in ichain for our caller,
3336 * and assign ichain->data to a pre-zero'd space (because there
3337 * is not prior data to copy into it).
3339 * We have to set SUBMODIFIED in ichain's flags manually so the
3340 * flusher knows it has to recurse through it to get to all of
3341 * our moved blocks, then call setsubmod() to set the bit
3344 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3345 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_SUBMODIFIED);
3346 hammer2_chain_setsubmod(trans, ichain);
3349 * Figure out what to return.
3351 if (~(((hammer2_key_t)1 << keybits) - 1) &
3352 (create_key ^ key)) {
3354 * Key being created is outside the key range,
3355 * return the original parent.
3357 hammer2_chain_unlock(ichain);
3359 kprintf("return original parent\n");
3363 * Otherwise its in the range, return the new parent.
3364 * (leave both the new and old parent locked).
3368 kprintf("return new ichain\n");
3376 * Calculate the keybits and highside/lowside of the freemap node the
3377 * caller is creating.
3379 * This routine will specify the next higher-level freemap key/radix
3380 * representing the lowest-ordered set. By doing so, eventually all
3381 * low-ordered sets will be moved one level down.
3383 * We have to be careful here because the freemap reserves a limited
3384 * number of blocks for a limited number of levels. So we can't just
3385 * push indiscriminately.
3388 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3389 int keybits, hammer2_blockref_t *base, int count)
3391 hammer2_chain_core_t *above;
3392 hammer2_chain_t *chain;
3393 hammer2_blockref_t *bref;
3395 hammer2_key_t key_beg;
3396 hammer2_key_t key_end;
3397 hammer2_key_t key_next;
3404 above = parent->core;
3410 * Calculate the range of keys in the array being careful to skip
3411 * slots which are overridden with a deletion.
3414 key_end = HAMMER2_MAX_TID;
3416 spin_lock(&above->cst.spin);
3419 if (++loops == 100000) {
3420 panic("indkey_freemap shit %p %p:%d\n",
3421 parent, base, count);
3423 chain = hammer2_combined_find(parent, base, count,
3424 &cache_index, &key_next,
3425 key_beg, key_end, &bref);
3432 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3433 if (key_next == 0 || key_next > key_end)
3438 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3440 if (keybits > bref->keybits) {
3442 keybits = bref->keybits;
3443 } else if (keybits == bref->keybits && bref->key < key) {
3450 spin_unlock(&above->cst.spin);
3453 * Return the keybits for a higher-level FREEMAP_NODE covering
3457 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3458 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3460 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3461 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3463 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3464 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3466 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3467 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3469 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3470 panic("hammer2_chain_indkey_freemap: level too high");
3473 panic("hammer2_chain_indkey_freemap: bad radix");
3482 * Calculate the keybits and highside/lowside of the indirect block the
3483 * caller is creating.
3486 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3487 int keybits, hammer2_blockref_t *base, int count)
3489 hammer2_chain_core_t *above;
3490 hammer2_blockref_t *bref;
3491 hammer2_chain_t *chain;
3492 hammer2_key_t key_beg;
3493 hammer2_key_t key_end;
3494 hammer2_key_t key_next;
3503 above = parent->core;
3508 * Calculate the range of keys in the array being careful to skip
3509 * slots which are overridden with a deletion. Once the scan
3510 * completes we will cut the key range in half and shift half the
3511 * range into the new indirect block.
3514 key_end = HAMMER2_MAX_TID;
3516 spin_lock(&above->cst.spin);
3519 if (++loops == 100000) {
3520 panic("indkey_freemap shit %p %p:%d\n",
3521 parent, base, count);
3523 chain = hammer2_combined_find(parent, base, count,
3524 &cache_index, &key_next,
3525 key_beg, key_end, &bref);
3532 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3533 if (key_next == 0 || key_next > key_end)
3538 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3541 * Expand our calculated key range (key, keybits) to fit
3542 * the scanned key. nkeybits represents the full range
3543 * that we will later cut in half (two halves @ nkeybits - 1).
3546 if (nkeybits < bref->keybits) {
3547 if (bref->keybits > 64) {
3548 kprintf("bad bref chain %p bref %p\n",
3552 nkeybits = bref->keybits;
3554 while (nkeybits < 64 &&
3555 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3556 (key ^ bref->key)) != 0) {
3561 * If the new key range is larger we have to determine
3562 * which side of the new key range the existing keys fall
3563 * under by checking the high bit, then collapsing the
3564 * locount into the hicount or vise-versa.
3566 if (keybits != nkeybits) {
3567 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3578 * The newly scanned key will be in the lower half or the
3579 * upper half of the (new) key range.
3581 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3590 spin_unlock(&above->cst.spin);
3591 bref = NULL; /* now invalid (safety) */
3594 * Adjust keybits to represent half of the full range calculated
3595 * above (radix 63 max)
3600 * Select whichever half contains the most elements. Theoretically
3601 * we can select either side as long as it contains at least one
3602 * element (in order to ensure that a free slot is present to hold
3603 * the indirect block).
3605 if (hammer2_indirect_optimize) {
3607 * Insert node for least number of keys, this will arrange
3608 * the first few blocks of a large file or the first few
3609 * inodes in a directory with fewer indirect blocks when
3612 if (hicount < locount && hicount != 0)
3613 key |= (hammer2_key_t)1 << keybits;
3615 key &= ~(hammer2_key_t)1 << keybits;
3618 * Insert node for most number of keys, best for heavily
3621 if (hicount > locount)
3622 key |= (hammer2_key_t)1 << keybits;
3624 key &= ~(hammer2_key_t)1 << keybits;
3632 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3633 * set chain->delete_tid.
3635 * This function does NOT generate a modification to the parent. It
3636 * would be nearly impossible to figure out which parent to modify anyway.
3637 * Such modifications are handled by the flush code and are properly merged
3638 * using the flush synchronization point.
3640 * The find/get code will properly overload the RBTREE check on top of
3641 * the bref check to detect deleted entries.
3643 * This function is NOT recursive. Any entity already pushed into the
3644 * chain (such as an inode) may still need visibility into its contents,
3645 * as well as the ability to read and modify the contents. For example,
3646 * for an unlinked file which is still open.
3648 * NOTE: This function does NOT set chain->modify_tid, allowing future
3649 * code to distinguish between live and deleted chains by testing
3652 * NOTE: Deletions normally do not occur in the middle of a duplication
3653 * chain but we use a trick for hardlink migration that refactors
3654 * the originating inode without deleting it, so we make no assumptions
3658 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3660 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3663 * Nothing to do if already marked.
3665 if (chain->flags & HAMMER2_CHAIN_DELETED)
3669 * We must set MOVED along with DELETED for the flush code to
3670 * recognize the operation and properly disconnect the chain
3673 * The setting of DELETED causes finds, lookups, and _next iterations
3674 * to no longer recognize the chain. RB_SCAN()s will still have
3675 * visibility (needed for flush serialization points).
3677 * We need the spinlock on the core whos RBTREE contains chain
3678 * to protect against races.
3680 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3681 spin_lock(&chain->above->cst.spin);
3683 chain->delete_tid = trans->sync_tid;
3684 /*chain->delete_gen = ++trans->delete_gen;*/
3685 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3686 atomic_add_int(&chain->above->live_count, -1);
3688 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3689 hammer2_chain_ref(chain);
3690 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3692 spin_unlock(&chain->above->cst.spin);
3695 * Mark the underlying block as possibly being free unless WILLDUP
3696 * is set. Duplication can occur in many situations, particularly
3697 * when chains are moved to indirect blocks.
3699 if ((flags & HAMMER2_DELETE_WILLDUP) == 0)
3700 hammer2_freemap_free(trans, chain->hmp, &chain->bref, 0);
3701 hammer2_chain_setsubmod(trans, chain);
3705 * Called with the core spinlock held to check for freeable layers.
3706 * Used by the flush code. Layers can wind up not being freed due
3707 * to the temporary layer->refs count. This function frees up any
3708 * layers that were missed.
3711 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3712 hammer2_chain_core_t *core)
3714 hammer2_chain_layer_t *layer;
3715 hammer2_chain_layer_t *tmp;
3717 tmp = TAILQ_FIRST(&core->layerq);
3718 while ((layer = tmp) != NULL) {
3719 tmp = TAILQ_NEXT(tmp, entry);
3720 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
3721 TAILQ_REMOVE(&core->layerq, layer, entry);
3724 spin_unlock(&core->cst.spin);
3725 kfree(layer, hmp->mchain);
3726 spin_lock(&core->cst.spin);
3734 * Returns the index of the nearest element in the blockref array >= elm.
3735 * Returns (count) if no element could be found.
3737 * Sets *key_nextp to the next key for loop purposes but does not modify
3738 * it if the next key would be higher than the current value of *key_nextp.
3739 * Note that *key_nexp can overflow to 0, which should be tested by the
3742 * (*cache_indexp) is a heuristic and can be any value without effecting
3745 * The spin lock on the related chain must be held.
3748 hammer2_base_find(hammer2_chain_t *chain,
3749 hammer2_blockref_t *base, int count,
3750 int *cache_indexp, hammer2_key_t *key_nextp,
3751 hammer2_key_t key_beg, hammer2_key_t key_end)
3753 hammer2_blockref_t *scan;
3754 hammer2_key_t scan_end;
3760 KKASSERT(chain->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3761 if (count == 0 || base == NULL)
3765 * Sequential optimization
3769 if (i >= chain->live_zero)
3770 i = chain->live_zero - 1;
3773 KKASSERT(i < count);
3779 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3786 * Search forwards, stop when we find a scan element which
3787 * encloses the key or until we know that there are no further
3791 if (scan->type != 0) {
3792 if (scan->key > key_beg)
3794 scan_end = scan->key +
3795 ((hammer2_key_t)1 << scan->keybits) - 1;
3796 if (scan_end >= key_beg)
3799 if (i >= chain->live_zero)
3806 if (i >= chain->live_zero) {
3809 scan_end = scan->key +
3810 ((hammer2_key_t)1 << scan->keybits);
3811 if (scan_end && (*key_nextp > scan_end ||
3813 *key_nextp = scan_end;
3821 * Do a combined search and return the next match either from the blockref
3822 * array or from the in-memory chain. Sets *bresp to the returned bref in
3823 * both cases, or sets it to NULL if the search exhausted. Only returns
3824 * a non-NULL chain if the search matched from the in-memory chain.
3826 * Must be called with above's spinlock held. Spinlock remains held
3827 * through the operation.
3829 * The returned chain is not locked or referenced. Use the returned bref
3830 * to determine if the search exhausted or not.
3832 static hammer2_chain_t *
3833 hammer2_combined_find(hammer2_chain_t *parent,
3834 hammer2_blockref_t *base, int count,
3835 int *cache_indexp, hammer2_key_t *key_nextp,
3836 hammer2_key_t key_beg, hammer2_key_t key_end,
3837 hammer2_blockref_t **bresp)
3839 hammer2_blockref_t *bref;
3840 hammer2_chain_t *chain;
3843 *key_nextp = key_end + 1;
3844 i = hammer2_base_find(parent, base, count, cache_indexp,
3845 key_nextp, key_beg, key_end);
3846 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3851 if (i == count && chain == NULL) {
3853 return(chain); /* NULL */
3857 * Only chain matched
3860 bref = &chain->bref;
3865 * Only blockref matched.
3867 if (chain == NULL) {
3873 * Both in-memory and blockref match.
3875 * If they are both flush with the left hand side select the chain.
3876 * If their starts match select the chain.
3877 * Otherwise the nearer element wins.
3879 if (chain->bref.key <= key_beg && base[i].key <= key_beg) {
3880 bref = &chain->bref;
3883 if (chain->bref.key <= base[i].key) {
3884 bref = &chain->bref;
3892 * If the bref is out of bounds we've exhausted our search.
3895 if (bref->key > key_end) {
3905 * Locate the specified block array element and delete it. The element
3908 * The spin lock on the related chain must be held.
3910 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3911 * need to be adjusted when we commit the media change.
3914 hammer2_base_delete(hammer2_chain_t *chain,
3915 hammer2_blockref_t *base, int count,
3916 int *cache_indexp, hammer2_blockref_t *elm)
3918 hammer2_key_t key_next;
3922 * Delete element. Expect the element to exist.
3924 * XXX see caller, flush code not yet sophisticated enough to prevent
3925 * re-flushed in some cases.
3927 key_next = 0; /* max range */
3928 i = hammer2_base_find(chain, base, count, cache_indexp,
3929 &key_next, elm->key, elm->key);
3930 if (i == count || base[i].type == 0 ||
3931 base[i].key != elm->key || base[i].keybits != elm->keybits) {
3932 kprintf("hammer2_base_delete: duplicate key %016jx/%d\n",
3933 elm->key, elm->keybits);
3937 KKASSERT(i != count);
3938 KKASSERT(base[i].type &&
3939 base[i].key == elm->key && base[i].keybits == elm->keybits);
3941 bzero(&base[i], sizeof(*base));
3942 if (chain->live_zero == i + 1) {
3943 while (--i >= 0 && base[i].type == 0)
3945 chain->live_zero = i + 1;
3950 * Insert the specified element. The block array must have space and
3951 * will be rearranged as necessary.
3953 * The spin lock on the related chain must be held.
3955 * Test (*flagsp) for HAMMER2_CHAIN_REPLACE. If set an existing bref
3956 * is replaced, otherwise a new bref is created. The flag is then set
3957 * prior to return indicating that a bref is now present in the block table.
3959 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3960 * need to be adjusted when we commit the media change.
3963 hammer2_base_insert(hammer2_chain_t *chain,
3964 hammer2_blockref_t *base, int count,
3965 int *cache_indexp, hammer2_blockref_t *elm,
3968 hammer2_key_t key_next;
3977 * Insert new element. Expect the element to not already exist
3978 * unless we are replacing it.
3980 * XXX see caller, flush code not yet sophisticated enough to prevent
3981 * re-flushed in some cases.
3983 key_next = 0; /* max range */
3984 i = hammer2_base_find(chain, base, count, cache_indexp,
3985 &key_next, elm->key, elm->key);
3987 if (i != count && (flags & HAMMER2_CHAIN_REPLACE) == 0 &&
3989 base[i].key == elm->key && base[i].keybits == elm->keybits) {
3990 kprintf("hammer2_base_insert: duplicate key %016jx/%d\n",
3991 elm->key, elm->keybits);
3995 KKASSERT(i == count || (flags & HAMMER2_CHAIN_REPLACE) ||
3996 base[i].type == 0 || base[i].key != elm->key ||
3997 base[i].keybits != elm->keybits);
4001 * Shortcut fill optimization, typical ordered insertion(s) may not
4004 KKASSERT(i >= 0 && i <= count);
4006 if (i == count && chain->live_zero < count) {
4007 i = chain->live_zero++;
4013 base[i].key == elm->key &&
4014 base[i].keybits == elm->keybits) {
4019 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4020 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4021 panic("insert base %p overlapping elements at %d elm %p\n",
4026 * Try to find an empty slot before or after.
4030 while (j > 0 || k < count) {
4032 if (j >= 0 && base[j].type == 0) {
4036 bcopy(&base[j+1], &base[j],
4037 (i - j - 1) * sizeof(*base));
4043 if (k < count && base[k].type == 0) {
4044 bcopy(&base[i], &base[i+1],
4045 (k - i) * sizeof(hammer2_blockref_t));
4047 if (chain->live_zero <= k)
4048 chain->live_zero = k + 1;
4053 panic("hammer2_base_insert: no room!");
4060 for (l = 0; l < count; ++l) {
4062 key_next = base[l].key +
4063 ((hammer2_key_t)1 << base[l].keybits) - 1;
4067 while (++l < count) {
4069 if (base[l].key <= key_next)
4070 panic("base_insert%d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4071 key_next = base[l].key +
4072 ((hammer2_key_t)1 << base[l].keybits) - 1;
4082 * Sort the blockref array for the chain. Used by the flush code to
4083 * sort the blockref[] array.
4085 * The chain must be exclusively locked AND spin-locked.
4087 typedef hammer2_blockref_t *hammer2_blockref_p;
4091 hammer2_base_sort_callback(const void *v1, const void *v2)
4093 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4094 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4097 * Make sure empty elements are placed at the end of the array
4099 if (bref1->type == 0) {
4100 if (bref2->type == 0)
4103 } else if (bref2->type == 0) {
4110 if (bref1->key < bref2->key)
4112 if (bref1->key > bref2->key)
4118 hammer2_base_sort(hammer2_chain_t *chain)
4120 hammer2_blockref_t *base;
4123 switch(chain->bref.type) {
4124 case HAMMER2_BREF_TYPE_INODE:
4126 * Special shortcut for embedded data returns the inode
4127 * itself. Callers must detect this condition and access
4128 * the embedded data (the strategy code does this for us).
4130 * This is only applicable to regular files and softlinks.
4132 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4134 base = &chain->data->ipdata.u.blockset.blockref[0];
4135 count = HAMMER2_SET_COUNT;
4137 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4138 case HAMMER2_BREF_TYPE_INDIRECT:
4140 * Optimize indirect blocks in the INITIAL state to avoid
4143 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4144 base = &chain->data->npdata[0];
4145 count = chain->bytes / sizeof(hammer2_blockref_t);
4147 case HAMMER2_BREF_TYPE_VOLUME:
4148 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4149 count = HAMMER2_SET_COUNT;
4151 case HAMMER2_BREF_TYPE_FREEMAP:
4152 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4153 count = HAMMER2_SET_COUNT;
4156 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4158 base = NULL; /* safety */
4159 count = 0; /* safety */
4161 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4167 * Chain memory management
4170 hammer2_chain_wait(hammer2_chain_t *chain)
4172 tsleep(chain, 0, "chnflw", 1);
4176 * Manage excessive memory resource use for chain and related
4180 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4183 while (pmp->inmem_chains > desiredvnodes / 10 &&
4184 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 2) {
4187 pmp->inmem_waiting = 1;
4188 tsleep(&pmp->inmem_waiting, 0, "chnmem", hz);
4192 if (pmp->inmem_chains > desiredvnodes / 10 &&
4193 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 7 / 4) {
4200 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4202 if (pmp->inmem_waiting &&
4203 (pmp->inmem_chains <= desiredvnodes / 10 ||
4204 pmp->inmem_chains <= pmp->mp->mnt_nvnodelistsize * 2)) {
4206 pmp->inmem_waiting = 0;
4207 wakeup(&pmp->inmem_waiting);
4213 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4217 switch(bref->type) {
4218 case HAMMER2_BREF_TYPE_DATA:
4219 counterp = &hammer2_iod_file_read;
4221 case HAMMER2_BREF_TYPE_INODE:
4222 counterp = &hammer2_iod_meta_read;
4224 case HAMMER2_BREF_TYPE_INDIRECT:
4225 counterp = &hammer2_iod_indr_read;
4227 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4228 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4229 counterp = &hammer2_iod_fmap_read;
4232 counterp = &hammer2_iod_volu_read;