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
64 * All lookup and iterate operations and most modifications are done on the
65 * live view. During flushes lookups are not normally done and modifications
66 * may be run on the flush view. However, flushes often needs to allocate
67 * blocks and the freemap_alloc/free code issues lookups. This code is
68 * special cased to use the live view when called from a flush.
70 * General chain lookup/iteration functions are NOT aware of the flush view,
71 * they only know about live views.
73 #include <sys/cdefs.h>
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/types.h>
78 #include <sys/kern_syscall.h>
83 static int hammer2_indirect_optimize; /* XXX SYSCTL */
85 static hammer2_chain_t *hammer2_chain_create_indirect(
86 hammer2_trans_t *trans, hammer2_chain_t *parent,
87 hammer2_key_t key, int keybits, int for_type, int *errorp);
88 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
89 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
90 static hammer2_chain_t *hammer2_combined_find(
91 hammer2_chain_t *parent,
92 hammer2_blockref_t *base, int count,
93 int *cache_indexp, hammer2_key_t *key_nextp,
94 hammer2_key_t key_beg, hammer2_key_t key_end,
95 hammer2_blockref_t **bresp);
98 * Basic RBTree for chains. Chains cannot overlap within any given
99 * core->rbtree without recursing through chain->rbtree. We effectively
100 * guarantee this by checking the full range rather than just the first
101 * key element. By matching on the full range callers can detect when
102 * recursrion through chain->rbtree is needed.
104 * NOTE: This also means the a delete-duplicate on the same key will
105 * overload by placing the deleted element in the new element's
106 * chain->rbtree (when doing a direct replacement).
108 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
111 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
113 hammer2_key_t c1_beg;
114 hammer2_key_t c1_end;
115 hammer2_key_t c2_beg;
116 hammer2_key_t c2_end;
118 c1_beg = chain1->bref.key;
119 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
120 c2_beg = chain2->bref.key;
121 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
123 if (c1_end < c2_beg) /* fully to the left */
125 if (c1_beg > c2_end) /* fully to the right */
127 return(0); /* overlap (must not cross edge boundary) */
132 hammer2_isclusterable(hammer2_chain_t *chain)
134 if (hammer2_cluster_enable) {
135 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
136 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
137 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
145 * Recursively set the update_hi flag up to the root starting at chain's
146 * parent->core. update_hi is not set in chain's core.
148 * This controls top-down visibility for flushes. The child has just one
149 * 'above' core, but the core itself can be multi-homed with parents iterated
152 * This function is not used during a flush (except when the flush is
153 * allocating which requires the live tree). The flush keeps track of its
156 * XXX needs to be optimized to use roll-up TIDs. update_hi is only really
157 * compared against bref.mirror_tid which itself is only updated by a flush.
160 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
162 hammer2_chain_core_t *above;
166 (HAMMER2_TRANS_ISFLUSH | HAMMER2_TRANS_ISALLOCATING)) ==
167 HAMMER2_TRANS_ISFLUSH) {
172 while ((above = chain->above) != NULL) {
173 spin_lock(&above->cst.spin);
175 if (above->update_hi < trans->sync_tid)
176 above->update_hi = trans->sync_tid;
177 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
179 TAILQ_FOREACH_REVERSE(chain, &above->ownerq,
180 h2_core_list, core_entry) {
181 if (trans->sync_tid >= chain->modify_tid &&
182 trans->sync_tid <= chain->delete_tid) {
187 spin_unlock(&above->cst.spin);
192 * Allocate a new disconnected chain element representing the specified
193 * bref. chain->refs is set to 1 and the passed bref is copied to
194 * chain->bref. chain->bytes is derived from the bref.
196 * chain->core is NOT allocated and the media data and bp pointers are left
197 * NULL. The caller must call chain_core_alloc() to allocate or associate
198 * a core with the chain.
200 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
203 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
204 hammer2_trans_t *trans, hammer2_blockref_t *bref)
206 hammer2_chain_t *chain;
207 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
210 * Construct the appropriate system structure.
213 case HAMMER2_BREF_TYPE_INODE:
214 case HAMMER2_BREF_TYPE_INDIRECT:
215 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
216 case HAMMER2_BREF_TYPE_DATA:
217 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
219 * Chain's are really only associated with the hmp but we
220 * maintain a pmp association for per-mount memory tracking
221 * purposes. The pmp can be NULL.
223 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
226 atomic_add_long(&pmp->inmem_chains, 1);
229 case HAMMER2_BREF_TYPE_VOLUME:
230 case HAMMER2_BREF_TYPE_FREEMAP:
232 panic("hammer2_chain_alloc volume type illegal for op");
235 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
241 chain->bytes = bytes;
243 chain->flags = HAMMER2_CHAIN_ALLOCATED;
244 chain->delete_tid = HAMMER2_MAX_TID;
247 * Set modify_tid if a transaction is creating the chain. When
248 * loading a chain from backing store trans is passed as NULL and
249 * modify_tid is left set to 0.
252 chain->modify_tid = trans->sync_tid;
258 * Associate an existing core with the chain or allocate a new core.
260 * The core is not locked. No additional refs on the chain are made.
261 * (trans) must not be NULL if (core) is not NULL.
263 * When chains are delete-duplicated during flushes we insert nchain on
264 * the ownerq after ochain instead of at the end in order to give the
265 * drop code visibility in the correct order, otherwise drops can be missed.
268 hammer2_chain_core_alloc(hammer2_trans_t *trans,
269 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
271 hammer2_chain_core_t *core;
273 KKASSERT(nchain->core == NULL);
275 if (ochain == NULL) {
277 * Fresh core under nchain (no multi-homing of ochain's
280 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
282 TAILQ_INIT(&core->layerq);
283 TAILQ_INIT(&core->ownerq);
287 core->update_hi = trans->sync_tid;
289 core->update_hi = nchain->bref.mirror_tid;
291 ccms_cst_init(&core->cst, nchain);
292 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
295 * Propagate the PFSROOT flag which we set on all subdirs
296 * under the super-root.
298 atomic_set_int(&nchain->flags,
299 ochain->flags & HAMMER2_CHAIN_PFSROOT);
302 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
303 * ochain if nchain is not a snapshot.
305 * It is possible for the DUPLICATED flag to already be
306 * set when called via a flush operation because flush
307 * operations may have to work on elements with delete_tid's
308 * beyond the flush sync_tid. In this situation we must
309 * ensure that nchain is placed just after ochain in the
310 * ownerq and that the DUPLICATED flag is set on nchain so
311 * 'live' operations skip past it to the correct chain.
313 * The flusher understands the blockref synchronization state
314 * for any stale chains by observing bref.mirror_tid, which
315 * delete-duplicate replicates.
317 * WARNING! However, the case is disallowed when the flusher
318 * is allocating freemap space because this entails
319 * more than just adjusting a block table.
321 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
322 KKASSERT((trans->flags &
323 (HAMMER2_TRANS_ISFLUSH |
324 HAMMER2_TRANS_ISALLOCATING)) ==
325 HAMMER2_TRANS_ISFLUSH);
326 atomic_set_int(&nchain->flags,
327 HAMMER2_CHAIN_DUPLICATED);
329 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
330 atomic_set_int(&ochain->flags,
331 HAMMER2_CHAIN_DUPLICATED);
334 atomic_add_int(&core->sharecnt, 1);
336 spin_lock(&core->cst.spin);
340 if (core->update_hi < trans->sync_tid)
341 core->update_hi = trans->sync_tid;
345 * Maintain ordering for refactor test so we don't skip over
346 * a snapshot. Also, during flushes, delete-duplications
347 * for block-table updates can occur on blocks already
348 * deleted (delete-duplicated by a later transaction). We
349 * must insert nchain after ochain but before the later
350 * transaction's copy.
352 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
354 spin_unlock(&core->cst.spin);
359 * Add a reference to a chain element, preventing its destruction.
362 hammer2_chain_ref(hammer2_chain_t *chain)
364 atomic_add_int(&chain->refs, 1);
368 * Insert the chain in the core rbtree at the first layer
369 * which accepts it (for now we don't sort layers by the transaction tid)
371 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
372 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
373 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
377 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_layer_t *layer,
378 hammer2_chain_t *chain, int flags)
380 hammer2_chain_t *xchain;
381 hammer2_chain_layer_t *nlayer;
383 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
384 spin_lock(&above->cst.spin);
385 chain->above = above;
388 * Special case, place chain in a more recent layer than the specified
392 nlayer = TAILQ_PREV(layer, h2_layer_list, entry);
393 if (nlayer && RB_INSERT(hammer2_chain_tree,
394 &nlayer->rbtree, chain) == NULL) {
395 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
399 spin_unlock(&above->cst.spin);
400 KKASSERT((flags & HAMMER2_CHAIN_INSERT_LIVE) == 0);
401 nlayer = kmalloc(sizeof(*nlayer), chain->hmp->mchain,
403 RB_INIT(&nlayer->rbtree);
404 nlayer->good = 0xABCD;
405 spin_lock(&above->cst.spin);
407 TAILQ_INSERT_BEFORE(layer, nlayer, entry);
408 RB_INSERT(hammer2_chain_tree, &nlayer->rbtree, chain);
409 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
413 layer = TAILQ_FIRST(&above->layerq);
420 (xchain = RB_INSERT(hammer2_chain_tree,
421 &layer->rbtree, chain)) != NULL) {
423 * Either no layers have been allocated or the insertion
424 * failed. This is fatal if the conflicted xchain is not
425 * flagged as deleted. Caller may or may allow the failure.
427 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
428 xchain && (xchain->flags & HAMMER2_CHAIN_DELETED) == 0) {
430 chain->inlayer = NULL;
431 kprintf("insertion race against %p\n", xchain);
436 * Allocate a new layer to resolve the issue.
438 spin_unlock(&above->cst.spin);
439 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
441 RB_INIT(&layer->rbtree);
442 layer->good = 0xABCD;
443 spin_lock(&above->cst.spin);
444 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
445 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
447 chain->inlayer = layer;
448 ++above->chain_count;
451 if ((flags & HAMMER2_CHAIN_INSERT_LIVE) &&
452 (chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
453 atomic_add_int(&above->live_count, 1);
455 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
457 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
458 spin_unlock(&above->cst.spin);
462 * Drop the caller's reference to the chain. When the ref count drops to
463 * zero this function will disassociate the chain from its parent and
464 * deallocate it, then recursely drop the parent using the implied ref
465 * from the chain's chain->parent.
467 * WARNING! Just because we are able to deallocate a chain doesn't mean
468 * that chain->core->rbtree is empty. There can still be a sharecnt
469 * on chain->core and RBTREE entries that refer to different parents.
471 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
472 struct h2_core_list *delayq);
475 hammer2_chain_drop(hammer2_chain_t *chain)
477 struct h2_core_list delayq;
478 hammer2_chain_t *scan;
482 if (hammer2_debug & 0x200000)
485 if (chain->flags & HAMMER2_CHAIN_MOVED)
487 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
489 KKASSERT(chain->refs > need);
499 chain = hammer2_chain_lastdrop(chain, &delayq);
501 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
503 /* retry the same chain */
507 * When we've exhausted lastdrop chaining pull off of delayq.
508 * chains on delayq are dead but are used to placehold other
509 * chains which we added a ref to for the purpose of dropping.
512 hammer2_mount_t *hmp;
514 if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
515 chain = (void *)scan->data;
516 TAILQ_REMOVE(&delayq, scan, core_entry);
517 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
520 kfree(scan, hmp->mchain);
527 * Safe handling of the 1->0 transition on chain. Returns a chain for
528 * recursive drop or NULL, possibly returning the same chain if the atomic
531 * Whem two chains need to be recursively dropped we use the chain
532 * we would otherwise free to placehold the additional chain. It's a bit
533 * convoluted but we can't just recurse without potentially blowing out
536 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
540 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
542 hammer2_pfsmount_t *pmp;
543 hammer2_mount_t *hmp;
544 hammer2_chain_core_t *above;
545 hammer2_chain_core_t *core;
546 hammer2_chain_layer_t *layer;
547 hammer2_chain_t *rdrop1;
548 hammer2_chain_t *rdrop2;
551 * Spinlock the core and check to see if it is empty. If it is
552 * not empty we leave chain intact with refs == 0. The elements
553 * in core->rbtree are associated with other chains contemporary
554 * with ours but not with our chain directly.
556 if ((core = chain->core) != NULL) {
557 spin_lock(&core->cst.spin);
560 * We can't free chains with children because there might
561 * be a flush dependency.
563 * NOTE: We return (chain) on failure to retry.
565 if (core->chain_count) {
566 if (atomic_cmpset_int(&chain->refs, 1, 0))
567 chain = NULL; /* success */
568 spin_unlock(&core->cst.spin);
571 /* no chains left under us */
574 * Because various parts of the code, including the inode
575 * structure, might be holding a stale chain and need to
576 * iterate to a non-stale sibling, we cannot remove siblings
577 * unless they are at the head of chain.
579 * We can't free a live chain unless it is a the head
580 * of its ownerq. If we were to then the go-to chain
581 * would revert to the prior deleted chain.
583 if (TAILQ_FIRST(&core->ownerq) != chain) {
584 if (atomic_cmpset_int(&chain->refs, 1, 0))
585 chain = NULL; /* success */
586 spin_unlock(&core->cst.spin);
592 * chain->core has no children left so no accessors can get to our
593 * chain from there. Now we have to lock the above core to interlock
594 * remaining possible accessors that might bump chain's refs before
595 * we can safely drop chain's refs with intent to free the chain.
598 pmp = chain->pmp; /* can be NULL */
604 * Spinlock the parent and try to drop the last ref on chain.
605 * On success remove chain from its parent, otherwise return NULL.
607 * (normal core locks are top-down recursive but we define core
608 * spinlocks as bottom-up recursive, so this is safe).
610 if ((above = chain->above) != NULL) {
611 spin_lock(&above->cst.spin);
612 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
613 /* 1->0 transition failed */
614 spin_unlock(&above->cst.spin);
616 spin_unlock(&core->cst.spin);
617 return(chain); /* retry */
621 * 1->0 transition successful, remove chain from its
622 * above core. Track layer for removal/freeing.
624 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
625 layer = chain->inlayer;
626 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
627 --above->chain_count;
628 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
630 chain->inlayer = NULL;
632 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
633 TAILQ_REMOVE(&above->layerq, layer, entry);
639 * If our chain was the last chain in the parent's core the
640 * core is now empty and its parents might now be droppable.
641 * Try to drop the first multi-homed parent by gaining a
642 * ref on it here and then dropping it below.
644 if (above->chain_count == 0) {
645 rdrop1 = TAILQ_FIRST(&above->ownerq);
647 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
651 spin_unlock(&above->cst.spin);
652 above = NULL; /* safety */
656 * Successful 1->0 transition and the chain can be destroyed now.
658 * We still have the core spinlock (if core is non-NULL), and core's
659 * chain_count is 0. The above spinlock is gone.
661 * Remove chain from ownerq. Once core has no more owners (and no
662 * children which is already the case) we can destroy core.
664 * If core has more owners we may be able to continue a bottom-up
665 * drop with our next sibling.
670 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
671 rdrop2 = TAILQ_FIRST(&core->ownerq);
672 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
674 spin_unlock(&core->cst.spin);
677 * We can do the final 1->0 transition with an atomic op
678 * after releasing core's spinlock.
680 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
682 * On the 1->0 transition of core we can destroy
683 * it. Any remaining layers should no longer be
684 * referenced or visibile to other threads.
686 KKASSERT(TAILQ_EMPTY(&core->ownerq));
688 layer->good = 0xEF00;
689 kfree(layer, hmp->mchain);
691 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
692 KKASSERT(layer->refs == 0 &&
693 RB_EMPTY(&layer->rbtree));
694 TAILQ_REMOVE(&core->layerq, layer, entry);
695 layer->good = 0xEF01;
696 kfree(layer, hmp->mchain);
699 KKASSERT(core->cst.count == 0);
700 KKASSERT(core->cst.upgrade == 0);
702 kfree(core, hmp->mchain);
704 core = NULL; /* safety */
708 * All spin locks are gone, finish freeing stuff.
710 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
711 HAMMER2_CHAIN_MODIFIED)) == 0);
712 hammer2_chain_drop_data(chain, 1);
714 KKASSERT(chain->bp == NULL);
717 * Free saved empty layer and return chained drop.
720 layer->good = 0xEF02;
721 kfree(layer, hmp->mchain);
725 * Once chain resources are gone we can use the now dead chain
726 * structure to placehold what might otherwise require a recursive
727 * drop, because we have potentially two things to drop and can only
728 * return one directly.
730 if (rdrop1 && rdrop2) {
731 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
732 chain->data = (void *)rdrop1;
733 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
735 } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
736 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
738 kfree(chain, hmp->mchain);
741 atomic_add_long(&pmp->inmem_chains, -1);
742 hammer2_chain_memory_wakeup(pmp);
746 * Either or both can be NULL. We already handled the case where
747 * both might not have been NULL.
756 * On either last lock release or last drop
759 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
761 hammer2_mount_t *hmp = chain->hmp;
763 switch(chain->bref.type) {
764 case HAMMER2_BREF_TYPE_VOLUME:
765 case HAMMER2_BREF_TYPE_FREEMAP:
769 case HAMMER2_BREF_TYPE_INODE:
771 kfree(chain->data, hmp->mchain);
775 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
777 kfree(chain->data, hmp->mchain);
782 KKASSERT(chain->data == NULL);
788 * Ref and lock a chain element, acquiring its data with I/O if necessary,
789 * and specify how you would like the data to be resolved.
791 * Returns 0 on success or an error code if the data could not be acquired.
792 * The chain element is locked on return regardless of whether an error
795 * The lock is allowed to recurse, multiple locking ops will aggregate
796 * the requested resolve types. Once data is assigned it will not be
797 * removed until the last unlock.
799 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
800 * (typically used to avoid device/logical buffer
803 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
804 * the INITIAL-create state (indirect blocks only).
806 * Do not resolve data elements for DATA chains.
807 * (typically used to avoid device/logical buffer
810 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
812 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
813 * it will be locked exclusive.
815 * NOTE: Embedded elements (volume header, inodes) are always resolved
818 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
819 * element will instantiate and zero its buffer, and flush it on
822 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
823 * so as not to instantiate a device buffer, which could alias against
824 * a logical file buffer. However, if ALWAYS is specified the
825 * device buffer will be instantiated anyway.
827 * WARNING! If data must be fetched a shared lock will temporarily be
828 * upgraded to exclusive. However, a deadlock can occur if
829 * the caller owns more than one shared lock.
832 hammer2_chain_lock(hammer2_chain_t *chain, int how)
834 hammer2_mount_t *hmp;
835 hammer2_chain_core_t *core;
836 hammer2_blockref_t *bref;
847 * Ref and lock the element. Recursive locks are allowed.
849 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
850 hammer2_chain_ref(chain);
851 atomic_add_int(&chain->lockcnt, 1);
854 KKASSERT(hmp != NULL);
857 * Get the appropriate lock.
860 if (how & HAMMER2_RESOLVE_SHARED)
861 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
863 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
866 * If we already have a valid data pointer no further action is
873 * Do we have to resolve the data?
875 switch(how & HAMMER2_RESOLVE_MASK) {
876 case HAMMER2_RESOLVE_NEVER:
878 case HAMMER2_RESOLVE_MAYBE:
879 if (chain->flags & HAMMER2_CHAIN_INITIAL)
881 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
884 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
887 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
890 case HAMMER2_RESOLVE_ALWAYS:
895 * Upgrade to an exclusive lock so we can safely manipulate the
896 * buffer cache. If another thread got to it before us we
899 ostate = ccms_thread_lock_upgrade(&core->cst);
901 ccms_thread_lock_downgrade(&core->cst, ostate);
906 * We must resolve to a device buffer, either by issuing I/O or
907 * by creating a zero-fill element. We do not mark the buffer
908 * dirty when creating a zero-fill element (the hammer2_chain_modify()
909 * API must still be used to do that).
911 * The device buffer is variable-sized in powers of 2 down
912 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
913 * chunk always contains buffers of the same size. (XXX)
915 * The minimum physical IO size may be larger than the variable
920 psize = hammer2_devblksize(chain->bytes);
921 pmask = (hammer2_off_t)psize - 1;
922 pbase = bref->data_off & ~pmask;
923 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
924 KKASSERT(pbase != 0);
925 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
928 * The getblk() optimization can only be used on newly created
929 * elements if the physical block size matches the request.
931 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
932 chain->bytes == psize) {
933 chain->bp = getblk(hmp->devvp, pbase, psize, 0, 0);
935 } else if (hammer2_isclusterable(chain)) {
936 error = cluster_read(hmp->devvp, peof, pbase, psize,
937 psize, HAMMER2_PBUFSIZE*4,
939 adjreadcounter(&chain->bref, chain->bytes);
941 error = bread(hmp->devvp, pbase, psize, &chain->bp);
942 adjreadcounter(&chain->bref, chain->bytes);
946 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
947 (intmax_t)pbase, error);
950 ccms_thread_lock_downgrade(&core->cst, ostate);
955 * Zero the data area if the chain is in the INITIAL-create state.
956 * Mark the buffer for bdwrite(). This clears the INITIAL state
957 * but does not mark the chain modified.
959 bdata = (char *)chain->bp->b_data + boff;
960 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
961 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
962 bzero(bdata, chain->bytes);
963 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
967 * Setup the data pointer, either pointing it to an embedded data
968 * structure and copying the data from the buffer, or pointing it
971 * The buffer is not retained when copying to an embedded data
972 * structure in order to avoid potential deadlocks or recursions
973 * on the same physical buffer.
975 switch (bref->type) {
976 case HAMMER2_BREF_TYPE_VOLUME:
977 case HAMMER2_BREF_TYPE_FREEMAP:
979 * Copy data from bp to embedded buffer
981 panic("hammer2_chain_lock: called on unresolved volume header");
984 KKASSERT(pbase == 0);
985 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
986 bcopy(bdata, &hmp->voldata, chain->bytes);
987 chain->data = (void *)&hmp->voldata;
992 case HAMMER2_BREF_TYPE_INODE:
994 * Copy data from bp to embedded buffer, do not retain the
997 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
998 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
999 chain->data = kmalloc(sizeof(chain->data->ipdata),
1000 hmp->mchain, M_WAITOK | M_ZERO);
1001 bcopy(bdata, &chain->data->ipdata, chain->bytes);
1005 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1006 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
1007 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
1008 chain->data = kmalloc(sizeof(chain->data->bmdata),
1009 hmp->mchain, M_WAITOK | M_ZERO);
1010 bcopy(bdata, &chain->data->bmdata, chain->bytes);
1014 case HAMMER2_BREF_TYPE_INDIRECT:
1015 case HAMMER2_BREF_TYPE_DATA:
1016 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1019 * Point data at the device buffer and leave bp intact.
1021 chain->data = (void *)bdata;
1026 * Make sure the bp is not specifically owned by this thread before
1027 * restoring to a possibly shared lock, so another hammer2 thread
1031 BUF_KERNPROC(chain->bp);
1032 ccms_thread_lock_downgrade(&core->cst, ostate);
1037 * Asynchronously read the device buffer (dbp) and execute the specified
1038 * callback. The caller should pass-in a locked chain (shared lock is ok).
1039 * The function is responsible for unlocking the chain and for disposing
1042 * NOTE! A NULL dbp (but non-NULL data) will be passed to the function
1043 * if the dbp is integrated into the chain, because we do not want
1044 * the caller to dispose of dbp in that situation.
1046 static void hammer2_chain_load_async_callback(struct bio *bio);
1049 hammer2_chain_load_async(hammer2_chain_t *chain,
1050 void (*func)(hammer2_chain_t *, struct buf *, char *, void *),
1053 hammer2_cbinfo_t *cbinfo;
1054 hammer2_mount_t *hmp;
1055 hammer2_blockref_t *bref;
1056 hammer2_off_t pbase;
1057 hammer2_off_t pmask;
1065 func(chain, NULL, (char *)chain->data, arg);
1070 * We must resolve to a device buffer, either by issuing I/O or
1071 * by creating a zero-fill element. We do not mark the buffer
1072 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1073 * API must still be used to do that).
1075 * The device buffer is variable-sized in powers of 2 down
1076 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1077 * chunk always contains buffers of the same size. (XXX)
1079 * The minimum physical IO size may be larger than the variable
1082 bref = &chain->bref;
1084 psize = hammer2_devblksize(chain->bytes);
1085 pmask = (hammer2_off_t)psize - 1;
1086 pbase = bref->data_off & ~pmask;
1087 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
1088 KKASSERT(pbase != 0);
1089 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1094 * The getblk() optimization can only be used on newly created
1095 * elements if the physical block size matches the request.
1097 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1098 chain->bytes == psize) {
1099 dbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1100 /*atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);*/
1101 bdata = (char *)dbp->b_data + boff;
1102 bzero(bdata, chain->bytes);
1103 /*atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);*/
1104 func(chain, dbp, bdata, arg);
1109 adjreadcounter(&chain->bref, chain->bytes);
1110 cbinfo = kmalloc(sizeof(*cbinfo), hmp->mchain, M_INTWAIT | M_ZERO);
1111 cbinfo->chain = chain;
1112 cbinfo->func = func;
1114 cbinfo->boff = boff;
1116 cluster_readcb(hmp->devvp, peof, pbase, psize,
1117 HAMMER2_PBUFSIZE*4, HAMMER2_PBUFSIZE*4,
1118 hammer2_chain_load_async_callback, cbinfo);
1122 hammer2_chain_load_async_callback(struct bio *bio)
1124 hammer2_cbinfo_t *cbinfo;
1125 hammer2_mount_t *hmp;
1130 * Nobody is waiting for bio/dbp to complete, we are
1131 * responsible for handling the biowait() equivalent
1132 * on dbp which means clearing BIO_DONE and BIO_SYNC
1133 * and calling bpdone() if it hasn't already been called
1134 * to restore any covered holes in the buffer's backing
1138 if ((bio->bio_flags & BIO_DONE) == 0)
1140 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
1143 * Extract the auxillary info and issue the callback.
1144 * Finish up with the dbp after it returns.
1146 cbinfo = bio->bio_caller_info1.ptr;
1147 /*ccms_thread_lock_setown(cbinfo->chain->core);*/
1148 data = dbp->b_data + cbinfo->boff;
1149 hmp = cbinfo->chain->hmp;
1151 cbinfo = bio->bio_caller_info1.ptr;
1152 if (cbinfo->chain->flags & HAMMER2_CHAIN_INITIAL)
1153 bzero(data, cbinfo->chain->bytes);
1154 cbinfo->func(cbinfo->chain, dbp, data, cbinfo->arg);
1155 /* cbinfo->chain is stale now */
1157 kfree(cbinfo, hmp->mchain);
1161 * Unlock and deref a chain element.
1163 * On the last lock release any non-embedded data (chain->bp) will be
1167 hammer2_chain_unlock(hammer2_chain_t *chain)
1169 hammer2_chain_core_t *core = chain->core;
1170 ccms_state_t ostate;
1175 * The core->cst lock can be shared across several chains so we
1176 * need to track the per-chain lockcnt separately.
1178 * If multiple locks are present (or being attempted) on this
1179 * particular chain we can just unlock, drop refs, and return.
1181 * Otherwise fall-through on the 1->0 transition.
1184 lockcnt = chain->lockcnt;
1185 KKASSERT(lockcnt > 0);
1188 if (atomic_cmpset_int(&chain->lockcnt,
1189 lockcnt, lockcnt - 1)) {
1190 ccms_thread_unlock(&core->cst);
1191 hammer2_chain_drop(chain);
1195 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1202 * On the 1->0 transition we upgrade the core lock (if necessary)
1203 * to exclusive for terminal processing. If after upgrading we find
1204 * that lockcnt is non-zero, another thread is racing us and will
1205 * handle the unload for us later on, so just cleanup and return
1206 * leaving the data/bp intact
1208 * Otherwise if lockcnt is still 0 it is possible for it to become
1209 * non-zero and race, but since we hold the core->cst lock
1210 * exclusively all that will happen is that the chain will be
1211 * reloaded after we unload it.
1213 ostate = ccms_thread_lock_upgrade(&core->cst);
1214 if (chain->lockcnt) {
1215 ccms_thread_unlock_upgraded(&core->cst, ostate);
1216 hammer2_chain_drop(chain);
1221 * Shortcut the case if the data is embedded or not resolved.
1223 * Do NOT NULL out chain->data (e.g. inode data), it might be
1226 * The DIRTYBP flag is non-applicable in this situation and can
1227 * be cleared to keep the flags state clean.
1229 if (chain->bp == NULL) {
1230 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1231 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1232 hammer2_chain_drop_data(chain, 0);
1233 ccms_thread_unlock_upgraded(&core->cst, ostate);
1234 hammer2_chain_drop(chain);
1241 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
1243 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1244 switch(chain->bref.type) {
1245 case HAMMER2_BREF_TYPE_DATA:
1246 counterp = &hammer2_ioa_file_write;
1248 case HAMMER2_BREF_TYPE_INODE:
1249 counterp = &hammer2_ioa_meta_write;
1251 case HAMMER2_BREF_TYPE_INDIRECT:
1252 counterp = &hammer2_ioa_indr_write;
1254 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1255 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1256 counterp = &hammer2_ioa_fmap_write;
1259 counterp = &hammer2_ioa_volu_write;
1262 *counterp += chain->bytes;
1264 switch(chain->bref.type) {
1265 case HAMMER2_BREF_TYPE_DATA:
1266 counterp = &hammer2_iod_file_write;
1268 case HAMMER2_BREF_TYPE_INODE:
1269 counterp = &hammer2_iod_meta_write;
1271 case HAMMER2_BREF_TYPE_INDIRECT:
1272 counterp = &hammer2_iod_indr_write;
1274 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1275 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1276 counterp = &hammer2_iod_fmap_write;
1279 counterp = &hammer2_iod_volu_write;
1282 *counterp += chain->bytes;
1288 * If a device buffer was used for data be sure to destroy the
1289 * buffer when we are done to avoid aliases (XXX what about the
1290 * underlying VM pages?).
1292 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1297 * XXX our primary cache is now the block device, not
1298 * the logical file. don't release the buffer.
1300 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1301 chain->bp->b_flags |= B_RELBUF;
1305 * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
1306 * or not. The flag will get re-set when chain_modify() is called,
1307 * even if MODIFIED is already set, allowing the OS to retire the
1308 * buffer independent of a hammer2 flus.
1311 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1312 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1313 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1314 atomic_clear_int(&chain->flags,
1315 HAMMER2_CHAIN_IOFLUSH);
1316 chain->bp->b_flags |= B_RELBUF;
1317 cluster_awrite(chain->bp);
1319 chain->bp->b_flags |= B_CLUSTEROK;
1323 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1324 atomic_clear_int(&chain->flags,
1325 HAMMER2_CHAIN_IOFLUSH);
1326 chain->bp->b_flags |= B_RELBUF;
1329 /* bp might still be dirty */
1334 ccms_thread_unlock_upgraded(&core->cst, ostate);
1335 hammer2_chain_drop(chain);
1339 * This counts the number of live blockrefs in a block array and
1340 * also calculates the point at which all remaining blockrefs are empty.
1342 * NOTE: Flag is not set until after the count is complete, allowing
1343 * callers to test the flag without holding the spinlock.
1345 * NOTE: If base is NULL the related chain is still in the INITIAL
1346 * state and there are no blockrefs to count.
1348 * NOTE: live_count may already have some counts accumulated due to
1349 * creation and deletion and could even be initially negative.
1352 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1353 hammer2_blockref_t *base, int count)
1355 hammer2_chain_core_t *core = chain->core;
1357 spin_lock(&core->cst.spin);
1358 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1360 while (--count >= 0) {
1361 if (base[count].type)
1364 core->live_zero = count + 1;
1365 while (count >= 0) {
1366 if (base[count].type)
1367 atomic_add_int(&core->live_count, 1);
1371 core->live_zero = 0;
1373 /* else do not modify live_count */
1374 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1376 spin_unlock(&core->cst.spin);
1380 * Resize the chain's physical storage allocation in-place. This may
1381 * replace the passed-in chain with a new chain.
1383 * Chains can be resized smaller without reallocating the storage.
1384 * Resizing larger will reallocate the storage.
1386 * Must be passed an exclusively locked parent and chain, returns a new
1387 * exclusively locked chain at the same index and unlocks the old chain.
1388 * Flushes the buffer if necessary.
1390 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1391 * to avoid instantiating a device buffer that conflicts with the vnode
1392 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1393 * any chain-oriented bp would be a device buffer.
1395 * XXX flags currently ignored, uses chain->bp to detect data/no-data.
1396 * XXX return error if cannot resize.
1399 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1400 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1401 int nradix, int flags)
1403 hammer2_mount_t *hmp;
1404 hammer2_chain_t *chain;
1405 hammer2_off_t pbase;
1415 * Only data and indirect blocks can be resized for now.
1416 * (The volu root, inodes, and freemap elements use a fixed size).
1418 KKASSERT(chain != &hmp->vchain);
1419 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1420 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1423 * Nothing to do if the element is already the proper size
1425 obytes = chain->bytes;
1426 nbytes = 1U << nradix;
1427 if (obytes == nbytes)
1431 * Delete the old chain and duplicate it at the same (parent, index),
1432 * returning a new chain. This allows the old chain to still be
1433 * used by the flush code. The new chain will be returned in a
1436 * The parent does not have to be locked for the delete/duplicate call,
1437 * but is in this particular code path.
1439 * NOTE: If we are not crossing a synchronization point the
1440 * duplication code will simply reuse the existing chain
1443 hammer2_chain_delete_duplicate(trans, &chain, 0);
1446 * Relocate the block, even if making it smaller (because different
1447 * block sizes may be in different regions).
1449 hammer2_freemap_alloc(trans, chain->hmp, &chain->bref, nbytes);
1450 chain->bytes = nbytes;
1451 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1452 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1455 * The device buffer may be larger than the allocation size.
1457 bbytes = hammer2_devblksize(chain->bytes);
1458 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1459 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1462 * For now just support it on DATA chains (and not on indirect
1465 KKASSERT(chain->bp == NULL);
1469 * Make sure the chain is marked MOVED and propagate the update
1470 * to the root for flush.
1472 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1473 hammer2_chain_ref(chain);
1474 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1476 hammer2_chain_setsubmod(trans, chain);
1482 * Set a chain modified, making it read-write and duplicating it if necessary.
1483 * This function will assign a new physical block to the chain if necessary
1485 * Duplication of already-modified chains is possible when the modification
1486 * crosses a flush synchronization boundary.
1488 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1489 * level or the COW operation will not work.
1491 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1492 * run the data through the device buffers.
1494 * This function may return a different chain than was passed, in which case
1495 * the old chain will be unlocked and the new chain will be locked.
1497 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1499 hammer2_inode_data_t *
1500 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1501 hammer2_chain_t **chainp, int flags)
1503 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1504 hammer2_chain_modify(trans, chainp, flags);
1505 if (ip->chain != *chainp)
1506 hammer2_inode_repoint(ip, NULL, *chainp);
1508 vsetisdirty(ip->vp);
1509 return(&ip->chain->data->ipdata);
1513 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1516 hammer2_mount_t *hmp;
1517 hammer2_chain_t *chain;
1518 hammer2_off_t pbase;
1519 hammer2_off_t pmask;
1532 kprintf("MODIFY %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1535 * Data must be resolved if already assigned unless explicitly
1536 * flagged otherwise.
1538 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1539 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1540 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1541 hammer2_chain_unlock(chain);
1545 * data is not optional for freemap chains (we must always be sure
1546 * to copy the data on COW storage allocations).
1548 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1549 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1550 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1551 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1555 * Determine if a delete-duplicate is needed.
1557 * (a) Modify_tid is part of a prior flush
1558 * (b) Transaction is concurrent with a flush (has higher tid)
1559 * (c) and chain is not in the initial state (freshly created)
1560 * (d) and caller didn't request an in-place modification.
1562 * The freemap and volume header special chains are never D-Dd.
1564 if (chain->modify_tid != trans->sync_tid && /* cross boundary */
1565 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1566 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1567 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1568 hammer2_chain_delete_duplicate(trans, chainp, 0);
1570 kprintf("RET1A %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1574 kprintf("RET1B %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1578 /* fall through if fchain or vchain */
1582 * Otherwise do initial-chain handling
1584 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1585 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1586 hammer2_chain_ref(chain);
1590 * The modification or re-modification requires an allocation and
1593 * We normally always allocate new storage here. If storage exists
1594 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1596 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1597 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1598 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1599 chain->modify_tid != trans->sync_tid)
1601 hammer2_freemap_alloc(trans, chain->hmp,
1602 &chain->bref, chain->bytes);
1603 /* XXX failed allocation */
1604 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1605 hammer2_freemap_alloc(trans, chain->hmp,
1606 &chain->bref, chain->bytes);
1607 /* XXX failed allocation */
1609 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1612 chain->modify_tid = trans->sync_tid;
1613 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1614 chain->bref.modify_tid = trans->sync_tid;
1617 * Do not COW if OPTDATA is set. INITIAL flag remains unchanged.
1618 * (OPTDATA does not prevent [re]allocation of storage, only the
1619 * related copy-on-write op).
1621 if (flags & HAMMER2_MODIFY_OPTDATA)
1625 * Clearing the INITIAL flag (for indirect blocks) indicates that
1626 * we've processed the uninitialized storage allocation.
1628 * If this flag is already clear we are likely in a copy-on-write
1629 * situation but we have to be sure NOT to bzero the storage if
1630 * no data is present.
1632 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1633 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1640 * Instantiate data buffer and possibly execute COW operation
1642 switch(chain->bref.type) {
1643 case HAMMER2_BREF_TYPE_VOLUME:
1644 case HAMMER2_BREF_TYPE_FREEMAP:
1645 case HAMMER2_BREF_TYPE_INODE:
1646 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1648 * The data is embedded, no copy-on-write operation is
1651 KKASSERT(chain->bp == NULL);
1653 case HAMMER2_BREF_TYPE_DATA:
1654 case HAMMER2_BREF_TYPE_INDIRECT:
1655 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1657 * Perform the copy-on-write operation
1659 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1661 psize = hammer2_devblksize(chain->bytes);
1662 pmask = (hammer2_off_t)psize - 1;
1663 pbase = chain->bref.data_off & ~pmask;
1664 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1665 KKASSERT(pbase != 0);
1666 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1669 * The getblk() optimization can only be used if the
1670 * chain element size matches the physical block size.
1672 if (chain->bp && chain->bp->b_loffset == pbase) {
1675 } else if (chain->bytes == psize) {
1676 nbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1678 } else if (hammer2_isclusterable(chain)) {
1679 error = cluster_read(hmp->devvp, peof, pbase, psize,
1680 psize, HAMMER2_PBUFSIZE*4,
1682 adjreadcounter(&chain->bref, chain->bytes);
1684 error = bread(hmp->devvp, pbase, psize, &nbp);
1685 adjreadcounter(&chain->bref, chain->bytes);
1687 KKASSERT(error == 0);
1688 bdata = (char *)nbp->b_data + boff;
1691 * Copy or zero-fill on write depending on whether
1692 * chain->data exists or not. Retire the existing bp
1693 * based on the DIRTYBP flag. Set the DIRTYBP flag to
1694 * indicate that retirement of nbp should use bdwrite().
1697 KKASSERT(chain->bp != NULL);
1698 if (chain->data != bdata) {
1699 bcopy(chain->data, bdata, chain->bytes);
1701 } else if (wasinitial) {
1702 bzero(bdata, chain->bytes);
1705 * We have a problem. We were asked to COW but
1706 * we don't have any data to COW with!
1708 panic("hammer2_chain_modify: having a COW %p\n",
1711 if (chain->bp != nbp) {
1713 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1714 chain->bp->b_flags |= B_CLUSTEROK;
1717 chain->bp->b_flags |= B_RELBUF;
1722 BUF_KERNPROC(chain->bp);
1724 chain->data = bdata;
1725 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1728 panic("hammer2_chain_modify: illegal non-embedded type %d",
1735 kprintf("RET2 %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1737 hammer2_chain_setsubmod(trans, chain);
1741 * Mark the volume as having been modified. This short-cut version
1742 * does not have to lock the volume's chain, which allows the ioctl
1743 * code to make adjustments to connections without deadlocking. XXX
1745 * No ref is made on vchain when flagging it MODIFIED.
1748 hammer2_modify_volume(hammer2_mount_t *hmp)
1750 hammer2_voldata_lock(hmp);
1751 hammer2_voldata_unlock(hmp, 1);
1755 * This function returns the chain at the nearest key within the specified
1756 * range with the highest delete_tid. The core spinlock must be held on
1757 * call and the returned chain will be referenced but not locked.
1759 * The returned chain may or may not be in a deleted state. Note that
1760 * live chains have a delete_tid = MAX_TID.
1762 * This function will recurse through chain->rbtree as necessary and will
1763 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1764 * the iteration value is less than the current value of *key_nextp.
1766 * The caller should use (*key_nextp) to calculate the actual range of
1767 * the returned element, which will be (key_beg to *key_nextp - 1), because
1768 * there might be another element which is superior to the returned element
1771 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1772 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1773 * it will wind up being (key_end + 1).
1775 struct hammer2_chain_find_info {
1776 hammer2_chain_t *best;
1777 hammer2_key_t key_beg;
1778 hammer2_key_t key_end;
1779 hammer2_key_t key_next;
1782 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1783 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1787 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1788 hammer2_key_t key_beg, hammer2_key_t key_end)
1790 struct hammer2_chain_find_info info;
1791 hammer2_chain_layer_t *layer;
1794 info.key_beg = key_beg;
1795 info.key_end = key_end;
1796 info.key_next = *key_nextp;
1798 KKASSERT(parent->core->good == 0x1234);
1799 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1800 KKASSERT(layer->good == 0xABCD);
1801 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1802 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1805 *key_nextp = info.key_next;
1807 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1808 parent, key_beg, key_end, *key_nextp);
1816 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1818 struct hammer2_chain_find_info *info = data;
1819 hammer2_key_t child_beg;
1820 hammer2_key_t child_end;
1822 child_beg = child->bref.key;
1823 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1825 if (child_end < info->key_beg)
1827 if (child_beg > info->key_end)
1834 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1836 struct hammer2_chain_find_info *info = data;
1837 hammer2_chain_t *best;
1838 hammer2_key_t child_end;
1842 * Skip deleted chains which have been flushed (MOVED no longer set),
1843 * causes caller to check blockref array.
1845 if ((child->flags & (HAMMER2_CHAIN_DELETED | HAMMER2_CHAIN_MOVED)) ==
1846 HAMMER2_CHAIN_DELETED) {
1855 if ((best = info->best) == NULL) {
1857 * No previous best. Assign best
1860 } else if (best->bref.key <= info->key_beg &&
1861 child->bref.key <= info->key_beg) {
1863 * If our current best is flush with key_beg and child is
1864 * also flush with key_beg choose based on delete_tid.
1866 * key_next will automatically be limited to the smaller of
1867 * the two end-points.
1869 if (child->delete_tid > best->delete_tid)
1871 } else if (child->bref.key < best->bref.key) {
1873 * Child has a nearer key and best is not flush with key_beg.
1874 * Truncate key_next to the old best key iff it had a better
1878 if (best->delete_tid >= child->delete_tid &&
1879 (info->key_next > best->bref.key || info->key_next == 0))
1880 info->key_next = best->bref.key;
1881 } else if (child->bref.key == best->bref.key) {
1883 * If our current best is flush with the child then choose
1884 * based on delete_tid.
1886 * key_next will automatically be limited to the smaller of
1887 * the two end-points.
1889 if (child->delete_tid > best->delete_tid)
1893 * Keep the current best but truncate key_next to the child's
1894 * base iff the child has a higher delete_tid.
1896 * key_next will also automatically be limited to the smaller
1897 * of the two end-points (probably not necessary for this case
1898 * but we do it anyway).
1900 if (child->delete_tid >= best->delete_tid &&
1901 (info->key_next > child->bref.key || info->key_next == 0))
1902 info->key_next = child->bref.key;
1906 * Always truncate key_next based on child's end-of-range.
1908 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1909 if (child_end && (info->key_next > child_end || info->key_next == 0))
1910 info->key_next = child_end;
1916 * Retrieve the specified chain from a media blockref, creating the
1917 * in-memory chain structure which reflects it. modify_tid will be
1918 * left 0 which forces any modifications to issue a delete-duplicate.
1920 * NULL is returned if the insertion races.
1922 * Caller must hold the parent locked shared or exclusive since we may
1923 * need the parent's bref array to find our block.
1926 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref)
1928 hammer2_mount_t *hmp = parent->hmp;
1929 hammer2_chain_core_t *above = parent->core;
1930 hammer2_chain_t *chain;
1933 * Allocate a chain structure representing the existing media
1934 * entry. Resulting chain has one ref and is not locked.
1936 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1937 hammer2_chain_core_alloc(NULL, chain, NULL);
1938 /* ref'd chain returned */
1939 chain->modify_tid = chain->bref.mirror_tid;
1942 * Link the chain into its parent. A spinlock is required to safely
1943 * access the RBTREE, and it is possible to collide with another
1944 * hammer2_chain_get() operation because the caller might only hold
1945 * a shared lock on the parent.
1947 KKASSERT(parent->refs > 0);
1948 hammer2_chain_insert(above, NULL, chain,
1949 HAMMER2_CHAIN_INSERT_SPIN |
1950 HAMMER2_CHAIN_INSERT_RACE);
1951 if ((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0) {
1952 kprintf("chain %p not on RBTREE\n", chain);
1953 hammer2_chain_drop(chain);
1958 * Return our new chain referenced but not locked.
1964 * Lookup initialization/completion API
1967 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1969 if (flags & HAMMER2_LOOKUP_SHARED) {
1970 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1971 HAMMER2_RESOLVE_SHARED);
1973 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1979 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1982 hammer2_chain_unlock(parent);
1987 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1989 hammer2_chain_t *oparent;
1990 hammer2_chain_t *bparent;
1991 hammer2_chain_t *nparent;
1992 hammer2_chain_core_t *above;
1995 above = oparent->above;
1997 spin_lock(&above->cst.spin);
1998 bparent = TAILQ_FIRST(&above->ownerq);
1999 hammer2_chain_ref(bparent);
2003 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
2004 nparent = TAILQ_NEXT(nparent, core_entry);
2005 hammer2_chain_ref(nparent);
2006 spin_unlock(&above->cst.spin);
2009 * Be careful of order
2011 hammer2_chain_unlock(oparent);
2012 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
2013 hammer2_chain_drop(bparent);
2016 * We might have raced a delete-duplicate.
2018 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
2019 spin_lock(&above->cst.spin);
2020 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
2021 spin_unlock(&above->cst.spin);
2022 hammer2_chain_ref(nparent);
2023 hammer2_chain_unlock(nparent);
2025 spin_lock(&above->cst.spin);
2026 continue; /* retry */
2028 spin_unlock(&above->cst.spin);
2038 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2039 * (*parentp) typically points to an inode but can also point to a related
2040 * indirect block and this function will recurse upwards and find the inode
2043 * (*parentp) must be exclusively locked and referenced and can be an inode
2044 * or an existing indirect block within the inode.
2046 * On return (*parentp) will be modified to point at the deepest parent chain
2047 * element encountered during the search, as a helper for an insertion or
2048 * deletion. The new (*parentp) will be locked and referenced and the old
2049 * will be unlocked and dereferenced (no change if they are both the same).
2051 * The matching chain will be returned exclusively locked. If NOLOCK is
2052 * requested the chain will be returned only referenced.
2054 * NULL is returned if no match was found, but (*parentp) will still
2055 * potentially be adjusted.
2057 * On return (*key_nextp) will point to an iterative value for key_beg.
2058 * (If NULL is returned (*key_nextp) is set to key_end).
2060 * This function will also recurse up the chain if the key is not within the
2061 * current parent's range. (*parentp) can never be set to NULL. An iteration
2062 * can simply allow (*parentp) to float inside the loop.
2064 * NOTE! chain->data is not always resolved. By default it will not be
2065 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
2066 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2067 * BREF_TYPE_DATA as the device buffer can alias the logical file
2071 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2072 hammer2_key_t key_beg, hammer2_key_t key_end,
2073 int *cache_indexp, int flags)
2075 hammer2_mount_t *hmp;
2076 hammer2_chain_t *parent;
2077 hammer2_chain_t *chain;
2078 hammer2_blockref_t *base;
2079 hammer2_blockref_t *bref;
2080 hammer2_blockref_t bcopy;
2081 hammer2_key_t scan_beg;
2082 hammer2_key_t scan_end;
2083 hammer2_chain_core_t *above;
2085 int how_always = HAMMER2_RESOLVE_ALWAYS;
2086 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2089 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2090 how_maybe = how_always;
2091 how = HAMMER2_RESOLVE_ALWAYS;
2092 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2093 how = HAMMER2_RESOLVE_NEVER;
2095 how = HAMMER2_RESOLVE_MAYBE;
2097 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2098 how_maybe |= HAMMER2_RESOLVE_SHARED;
2099 how_always |= HAMMER2_RESOLVE_SHARED;
2100 how |= HAMMER2_RESOLVE_SHARED;
2104 * Recurse (*parentp) upward if necessary until the parent completely
2105 * encloses the key range or we hit the inode.
2107 * This function handles races against the flusher doing a delete-
2108 * duplicate above us and re-homes the parent to the duplicate in
2109 * that case, otherwise we'd wind up recursing down a stale chain.
2114 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2115 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2116 scan_beg = parent->bref.key;
2117 scan_end = scan_beg +
2118 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2119 if (key_beg >= scan_beg && key_end <= scan_end)
2121 parent = hammer2_chain_getparent(parentp, how_maybe);
2126 * Locate the blockref array. Currently we do a fully associative
2127 * search through the array.
2129 switch(parent->bref.type) {
2130 case HAMMER2_BREF_TYPE_INODE:
2132 * Special shortcut for embedded data returns the inode
2133 * itself. Callers must detect this condition and access
2134 * the embedded data (the strategy code does this for us).
2136 * This is only applicable to regular files and softlinks.
2138 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2139 if (flags & HAMMER2_LOOKUP_NOLOCK)
2140 hammer2_chain_ref(parent);
2142 hammer2_chain_lock(parent, how_always);
2143 *key_nextp = key_end + 1;
2146 base = &parent->data->ipdata.u.blockset.blockref[0];
2147 count = HAMMER2_SET_COUNT;
2149 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2150 case HAMMER2_BREF_TYPE_INDIRECT:
2152 * Handle MATCHIND on the parent
2154 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2155 scan_beg = parent->bref.key;
2156 scan_end = scan_beg +
2157 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2158 if (key_beg == scan_beg && key_end == scan_end) {
2160 hammer2_chain_lock(chain, how_maybe);
2161 *key_nextp = scan_end + 1;
2166 * Optimize indirect blocks in the INITIAL state to avoid
2169 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2172 if (parent->data == NULL)
2173 panic("parent->data is NULL");
2174 base = &parent->data->npdata[0];
2176 count = parent->bytes / sizeof(hammer2_blockref_t);
2178 case HAMMER2_BREF_TYPE_VOLUME:
2179 base = &hmp->voldata.sroot_blockset.blockref[0];
2180 count = HAMMER2_SET_COUNT;
2182 case HAMMER2_BREF_TYPE_FREEMAP:
2183 base = &hmp->voldata.freemap_blockset.blockref[0];
2184 count = HAMMER2_SET_COUNT;
2187 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2189 base = NULL; /* safety */
2190 count = 0; /* safety */
2194 * Merged scan to find next candidate.
2196 * hammer2_base_*() functions require the above->live_* fields
2197 * to be synchronized.
2199 * We need to hold the spinlock to access the block array and RB tree
2200 * and to interlock chain creation.
2202 above = parent->core;
2203 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2204 hammer2_chain_countbrefs(parent, base, count);
2209 spin_lock(&above->cst.spin);
2210 chain = hammer2_combined_find(parent, base, count,
2211 cache_indexp, key_nextp,
2212 key_beg, key_end, &bref);
2215 * Exhausted parent chain, iterate.
2218 spin_unlock(&above->cst.spin);
2219 if (key_beg == key_end) /* short cut single-key case */
2221 return (hammer2_chain_next(parentp, NULL, key_nextp,
2223 cache_indexp, flags));
2227 * Selected from blockref or in-memory chain.
2229 if (chain == NULL) {
2231 spin_unlock(&above->cst.spin);
2232 chain = hammer2_chain_get(parent, &bcopy);
2233 if (chain == NULL) {
2234 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2235 parent, key_beg, key_end);
2238 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2239 hammer2_chain_drop(chain);
2243 hammer2_chain_ref(chain);
2244 spin_unlock(&above->cst.spin);
2246 /* chain is referenced but not locked */
2249 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2251 * NOTE: chain's key range is not relevant as there might be
2252 * one-offs within the range that are not deleted.
2254 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2255 hammer2_chain_drop(chain);
2256 key_beg = *key_nextp;
2257 if (key_beg == 0 || key_beg > key_end)
2263 * If the chain element is an indirect block it becomes the new
2264 * parent and we loop on it. We must maintain our top-down locks
2265 * to prevent the flusher from interfering (i.e. doing a
2266 * delete-duplicate and leaving us recursing down a deleted chain).
2268 * The parent always has to be locked with at least RESOLVE_MAYBE
2269 * so we can access its data. It might need a fixup if the caller
2270 * passed incompatible flags. Be careful not to cause a deadlock
2271 * as a data-load requires an exclusive lock.
2273 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2274 * range is within the requested key range we return the indirect
2275 * block and do NOT loop. This is usually only used to acquire
2278 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2279 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2280 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2281 hammer2_chain_unlock(parent);
2282 *parentp = parent = chain;
2286 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2289 * All done, return the chain
2295 * After having issued a lookup we can iterate all matching keys.
2297 * If chain is non-NULL we continue the iteration from just after it's index.
2299 * If chain is NULL we assume the parent was exhausted and continue the
2300 * iteration at the next parent.
2302 * parent must be locked on entry and remains locked throughout. chain's
2303 * lock status must match flags. Chain is always at least referenced.
2305 * WARNING! The MATCHIND flag does not apply to this function.
2308 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2309 hammer2_key_t *key_nextp,
2310 hammer2_key_t key_beg, hammer2_key_t key_end,
2311 int *cache_indexp, int flags)
2313 hammer2_chain_t *parent;
2317 * Calculate locking flags for upward recursion.
2319 how_maybe = HAMMER2_RESOLVE_MAYBE;
2320 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2321 how_maybe |= HAMMER2_RESOLVE_SHARED;
2326 * Calculate the next index and recalculate the parent if necessary.
2329 key_beg = chain->bref.key +
2330 ((hammer2_key_t)1 << chain->bref.keybits);
2331 if (flags & HAMMER2_LOOKUP_NOLOCK)
2332 hammer2_chain_drop(chain);
2334 hammer2_chain_unlock(chain);
2337 * Any scan where the lookup returned degenerate data embedded
2338 * in the inode has an invalid index and must terminate.
2340 if (chain == parent)
2342 if (key_beg == 0 || key_beg > key_end)
2345 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2346 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2348 * We reached the end of the iteration.
2353 * Continue iteration with next parent unless the current
2354 * parent covers the range.
2356 key_beg = parent->bref.key +
2357 ((hammer2_key_t)1 << parent->bref.keybits);
2358 if (key_beg == 0 || key_beg > key_end)
2360 parent = hammer2_chain_getparent(parentp, how_maybe);
2366 return (hammer2_chain_lookup(parentp, key_nextp,
2368 cache_indexp, flags));
2372 * Create and return a new hammer2 system memory structure of the specified
2373 * key, type and size and insert it under (*parentp). This is a full
2374 * insertion, based on the supplied key/keybits, and may involve creating
2375 * indirect blocks and moving other chains around via delete/duplicate.
2377 * (*parentp) must be exclusive locked and may be replaced on return
2378 * depending on how much work the function had to do.
2380 * (*chainp) usually starts out NULL and returns the newly created chain,
2381 * but if the caller desires the caller may allocate a disconnected chain
2382 * and pass it in instead. (It is also possible for the caller to use
2383 * chain_duplicate() to create a disconnected chain, manipulate it, then
2384 * pass it into this function to insert it).
2386 * This function should NOT be used to insert INDIRECT blocks. It is
2387 * typically used to create/insert inodes and data blocks.
2389 * Caller must pass-in an exclusively locked parent the new chain is to
2390 * be inserted under, and optionally pass-in a disconnected, exclusively
2391 * locked chain to insert (else we create a new chain). The function will
2392 * adjust (*parentp) as necessary, create or connect the chain, and
2393 * return an exclusively locked chain in *chainp.
2396 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2397 hammer2_chain_t **chainp,
2398 hammer2_key_t key, int keybits, int type, size_t bytes)
2400 hammer2_mount_t *hmp;
2401 hammer2_chain_t *chain;
2402 hammer2_chain_t *parent = *parentp;
2403 hammer2_chain_core_t *above;
2404 hammer2_blockref_t *base;
2405 hammer2_blockref_t dummy;
2410 above = parent->core;
2411 KKASSERT(ccms_thread_lock_owned(&above->cst));
2415 if (chain == NULL) {
2417 * First allocate media space and construct the dummy bref,
2418 * then allocate the in-memory chain structure. Set the
2419 * INITIAL flag for fresh chains which do not have embedded
2422 bzero(&dummy, sizeof(dummy));
2425 dummy.keybits = keybits;
2426 dummy.data_off = hammer2_getradix(bytes);
2427 dummy.methods = parent->bref.methods;
2428 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2429 hammer2_chain_core_alloc(trans, chain, NULL);
2432 * Lock the chain manually, chain_lock will load the chain
2433 * which we do NOT want to do. (note: chain->refs is set
2434 * to 1 by chain_alloc() for us, but lockcnt is not).
2437 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2441 * We do NOT set INITIAL here (yet). INITIAL is only
2442 * used for indirect blocks.
2444 * Recalculate bytes to reflect the actual media block
2447 bytes = (hammer2_off_t)1 <<
2448 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2449 chain->bytes = bytes;
2452 case HAMMER2_BREF_TYPE_VOLUME:
2453 case HAMMER2_BREF_TYPE_FREEMAP:
2454 panic("hammer2_chain_create: called with volume type");
2456 case HAMMER2_BREF_TYPE_INODE:
2457 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2458 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2459 chain->data = kmalloc(sizeof(chain->data->ipdata),
2460 hmp->mchain, M_WAITOK | M_ZERO);
2462 case HAMMER2_BREF_TYPE_INDIRECT:
2463 panic("hammer2_chain_create: cannot be used to"
2464 "create indirect block");
2466 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2467 panic("hammer2_chain_create: cannot be used to"
2468 "create freemap root or node");
2470 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2471 KKASSERT(bytes == sizeof(chain->data->bmdata));
2472 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2473 chain->data = kmalloc(sizeof(chain->data->bmdata),
2474 hmp->mchain, M_WAITOK | M_ZERO);
2476 case HAMMER2_BREF_TYPE_DATA:
2479 * leave chain->data NULL, set INITIAL
2481 KKASSERT(chain->data == NULL);
2482 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2487 * Potentially update the existing chain's key/keybits.
2489 * Do NOT mess with the current state of the INITIAL flag.
2491 chain->bref.key = key;
2492 chain->bref.keybits = keybits;
2493 KKASSERT(chain->above == NULL);
2497 * Calculate how many entries we have in the blockref array and
2498 * determine if an indirect block is required.
2501 above = parent->core;
2503 switch(parent->bref.type) {
2504 case HAMMER2_BREF_TYPE_INODE:
2505 KKASSERT((parent->data->ipdata.op_flags &
2506 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2507 KKASSERT(parent->data != NULL);
2508 base = &parent->data->ipdata.u.blockset.blockref[0];
2509 count = HAMMER2_SET_COUNT;
2511 case HAMMER2_BREF_TYPE_INDIRECT:
2512 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2513 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2516 base = &parent->data->npdata[0];
2517 count = parent->bytes / sizeof(hammer2_blockref_t);
2519 case HAMMER2_BREF_TYPE_VOLUME:
2520 KKASSERT(parent->data != NULL);
2521 base = &hmp->voldata.sroot_blockset.blockref[0];
2522 count = HAMMER2_SET_COUNT;
2524 case HAMMER2_BREF_TYPE_FREEMAP:
2525 KKASSERT(parent->data != NULL);
2526 base = &hmp->voldata.freemap_blockset.blockref[0];
2527 count = HAMMER2_SET_COUNT;
2530 panic("hammer2_chain_create: unrecognized blockref type: %d",
2538 * Make sure we've counted the brefs
2540 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2541 hammer2_chain_countbrefs(parent, base, count);
2543 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2546 * If no free blockref could be found we must create an indirect
2547 * block and move a number of blockrefs into it. With the parent
2548 * locked we can safely lock each child in order to delete+duplicate
2549 * it without causing a deadlock.
2551 * This may return the new indirect block or the old parent depending
2552 * on where the key falls. NULL is returned on error.
2554 if (above->live_count == count) {
2555 hammer2_chain_t *nparent;
2557 nparent = hammer2_chain_create_indirect(trans, parent,
2560 if (nparent == NULL) {
2562 hammer2_chain_drop(chain);
2566 if (parent != nparent) {
2567 hammer2_chain_unlock(parent);
2568 parent = *parentp = nparent;
2574 * Link the chain into its parent. Later on we will have to set
2575 * the MOVED bit in situations where we don't mark the new chain
2576 * as being modified.
2578 if (chain->above != NULL)
2579 panic("hammer2: hammer2_chain_create: chain already connected");
2580 KKASSERT(chain->above == NULL);
2581 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2582 hammer2_chain_insert(above, NULL, chain,
2583 HAMMER2_CHAIN_INSERT_SPIN |
2584 HAMMER2_CHAIN_INSERT_LIVE);
2588 * Mark the newly created chain modified.
2590 * Device buffers are not instantiated for DATA elements
2591 * as these are handled by logical buffers.
2593 * Indirect and freemap node indirect blocks are handled
2594 * by hammer2_chain_create_indirect() and not by this
2597 * Data for all other bref types is expected to be
2598 * instantiated (INODE, LEAF).
2600 switch(chain->bref.type) {
2601 case HAMMER2_BREF_TYPE_DATA:
2602 hammer2_chain_modify(trans, &chain,
2603 HAMMER2_MODIFY_OPTDATA |
2604 HAMMER2_MODIFY_ASSERTNOCOPY);
2606 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2607 case HAMMER2_BREF_TYPE_INODE:
2608 hammer2_chain_modify(trans, &chain,
2609 HAMMER2_MODIFY_ASSERTNOCOPY);
2613 * Remaining types are not supported by this function.
2614 * In particular, INDIRECT and LEAF_NODE types are
2615 * handled by create_indirect().
2617 panic("hammer2_chain_create: bad type: %d",
2624 * When reconnecting a chain we must set MOVED and setsubmod
2625 * so the flush recognizes that it must update the bref in
2628 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2629 hammer2_chain_ref(chain);
2630 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2633 hammer2_chain_setsubmod(trans, chain);
2642 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2643 * the same core and media state as the orignal. The original *chainp is
2644 * unlocked and the replacement will be returned locked.
2646 * The old chain may or may not be in a DELETED state. This new chain will
2647 * be live (not deleted).
2649 * The new chain will be marked modified for the current transaction.
2651 * If (parent) is non-NULL then the new duplicated chain is inserted under
2654 * If (parent) is NULL then the new duplicated chain is not inserted anywhere,
2655 * similar to if it had just been chain_alloc()'d (suitable for passing into
2656 * hammer2_chain_create() after this function returns).
2658 * WARNING! This is not a snapshot. Changes made underneath either the old
2659 * or new chain will affect both.
2661 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2662 hammer2_chain_t *nchain);
2665 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2666 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2669 hammer2_mount_t *hmp;
2670 hammer2_chain_t *parent;
2671 hammer2_chain_t *ochain;
2672 hammer2_chain_t *nchain;
2673 hammer2_chain_core_t *above;
2677 * We want nchain to be our go-to live chain, but ochain may be in
2678 * a MODIFIED state within the current flush synchronization segment.
2679 * Force any further modifications of ochain to do another COW
2680 * operation even if modify_tid indicates that one is not needed.
2682 * WARNING! We should never resolve DATA to device buffers
2683 * (XXX allow it if the caller did?), and since
2684 * we currently do not have the logical buffer cache
2685 * buffer in-hand to fix its cached physical offset
2686 * we also force the modify code to not COW it. XXX
2691 ochain->debug_reason += 0x10000;
2693 ochain->debug_reason += 0x100000;
2696 if (ochain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2697 hammer2_chain_modify(trans, &ochain,
2698 HAMMER2_MODIFY_OPTDATA |
2699 HAMMER2_MODIFY_NOREALLOC);
2700 } else if (ochain->flags & HAMMER2_CHAIN_INITIAL) {
2701 hammer2_chain_modify(trans, &ochain,
2702 HAMMER2_MODIFY_OPTDATA);
2704 hammer2_chain_modify(trans, &ochain, 0);
2707 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2710 * Now create a duplicate of the chain structure, associating
2711 * it with the same core, making it the same size, pointing it
2712 * to the same bref (the same media block).
2714 * Give the duplicate the same modify_tid that we previously
2715 * ensured was sufficiently advanced to trigger a block table
2716 * insertion on flush.
2718 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2719 * hammer2_chain_alloc()
2722 bref = &ochain->bref;
2724 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2725 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2727 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2729 hammer2_chain_core_alloc(trans, nchain, ochain);
2730 bytes = (hammer2_off_t)1 <<
2731 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2732 nchain->bytes = bytes;
2733 nchain->modify_tid = ochain->modify_tid;
2734 if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2735 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2738 * Fixup (copy) any embedded data. Non-embedded data relies on the
2739 * media block. We must unlock ochain before we can access nchain's
2740 * media block because they might share the same bp and deadlock if
2743 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2744 HAMMER2_RESOLVE_NOREF);
2745 hammer2_chain_dup_fixup(ochain, nchain);
2746 /* nchain has 1 ref */
2747 hammer2_chain_unlock(ochain);
2748 KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2749 ochain->data == NULL);
2752 * Place nchain in the modified state, instantiate media data
2753 * if necessary. Because modify_tid is already completely
2754 * synchronized this should not result in a delete-duplicate.
2756 * We want nchain at the target to look like a new insertion.
2757 * Forcing the modification to be INPLACE accomplishes this
2758 * because we get the same nchain with an updated modify_tid.
2760 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2761 hammer2_chain_modify(trans, &nchain,
2762 HAMMER2_MODIFY_OPTDATA |
2763 HAMMER2_MODIFY_NOREALLOC |
2764 HAMMER2_MODIFY_INPLACE);
2765 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2766 hammer2_chain_modify(trans, &nchain,
2767 HAMMER2_MODIFY_OPTDATA |
2768 HAMMER2_MODIFY_INPLACE);
2770 hammer2_chain_modify(trans, &nchain,
2771 HAMMER2_MODIFY_INPLACE);
2775 * If parent is not NULL the duplicated chain will be entered under
2776 * the parent and the MOVED bit set.
2778 * Having both chains locked is extremely important for atomicy.
2780 if (parentp && (parent = *parentp) != NULL) {
2781 above = parent->core;
2782 KKASSERT(ccms_thread_lock_owned(&above->cst));
2783 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2784 KKASSERT(parent->refs > 0);
2786 hammer2_chain_create(trans, parentp, &nchain,
2787 nchain->bref.key, nchain->bref.keybits,
2788 nchain->bref.type, nchain->bytes);
2791 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2792 hammer2_chain_ref(nchain);
2793 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2795 hammer2_chain_setsubmod(trans, nchain);
2800 * Unconditionally set MOVED to force the parent blockrefs to
2801 * update, and adjust update_hi below nchain so nchain's
2802 * blockrefs are updated with the new attachment.
2804 if (nchain->core->update_hi < trans->sync_tid) {
2805 spin_lock(&nchain->core->cst.spin);
2806 if (nchain->core->update_hi < trans->sync_tid)
2807 nchain->core->update_hi = trans->sync_tid;
2808 spin_unlock(&nchain->core->cst.spin);
2816 * Special in-place delete-duplicate sequence which does not require a
2817 * locked parent. (*chainp) is marked DELETED and atomically replaced
2818 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2819 * order to ensure that lookups do not race us.
2821 * If the old chain is already marked deleted the new chain will also be
2822 * marked deleted. This case can occur when an inode is removed from the
2823 * filesystem but programs still have an open descriptor to it, and during
2824 * flushes when the flush needs to operate on a chain that is deleted in
2825 * the live view but still alive in the flush view.
2827 * The new chain will be marked modified for the current transaction.
2830 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2833 hammer2_mount_t *hmp;
2834 hammer2_chain_t *ochain;
2835 hammer2_chain_t *nchain;
2836 hammer2_chain_core_t *above;
2839 if (hammer2_debug & 0x20000)
2843 * Note that we do not have to call setsubmod on ochain, calling it
2844 * on nchain is sufficient.
2849 ochain->debug_reason += 0x1000;
2850 if ((ochain->debug_reason & 0xF000) > 0x4000) {
2851 kprintf("ochain %p\n", ochain);
2854 if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2855 KKASSERT(ochain->data);
2859 * First create a duplicate of the chain structure.
2860 * (nchain is allocated with one ref).
2862 * In the case where nchain inherits ochains core, nchain is
2863 * effectively locked due to ochain being locked (and sharing the
2864 * core), until we can give nchain its own official ock.
2866 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2867 if (flags & HAMMER2_DELDUP_RECORE)
2868 hammer2_chain_core_alloc(trans, nchain, NULL);
2870 hammer2_chain_core_alloc(trans, nchain, ochain);
2871 above = ochain->above;
2873 bytes = (hammer2_off_t)1 <<
2874 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2875 nchain->bytes = bytes;
2878 * Duplicate inherits ochain's live state including its modification
2879 * state. This function disposes of the original. Because we are
2880 * doing this in-place under the same parent the block array
2881 * inserted/deleted state does not change.
2883 * The caller isn't expected to make further modifications of ochain
2884 * but set the FORCECOW bit anyway, just in case it does. If ochain
2885 * was previously marked FORCECOW we also flag nchain FORCECOW
2886 * (used during hardlink splits).
2888 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2889 * hammer2_chain_alloc()
2891 nchain->data_count += ochain->data_count;
2892 nchain->inode_count += ochain->inode_count;
2893 atomic_set_int(&nchain->flags,
2894 ochain->flags & (HAMMER2_CHAIN_INITIAL |
2895 HAMMER2_CHAIN_FORCECOW));
2896 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2899 * Lock nchain so both chains are now locked (extremely important
2900 * for atomicy). Mark ochain deleted and reinsert into the topology
2901 * and insert nchain all in one go.
2903 * If the ochain is already deleted it is left alone and nchain
2904 * is inserted into the topology as a deleted chain. This is
2905 * important because it allows ongoing operations to be executed
2906 * on a deleted inode which still has open descriptors.
2908 * The deleted case can also occur when a flush delete-duplicates
2909 * a node which is being concurrently modified by ongoing operations
2910 * in a later transaction. This creates a problem because the flush
2911 * is intended to update blockrefs which then propagate, allowing
2912 * the original covering in-memory chains to be freed up. In this
2913 * situation the flush code does NOT free the original covering
2914 * chains and will re-apply them to successive copies.
2916 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2917 hammer2_chain_dup_fixup(ochain, nchain);
2918 /* extra ref still present from original allocation */
2920 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2921 spin_lock(&above->cst.spin);
2922 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2925 * Ultimately nchain->modify_tid will be set to trans->sync_tid,
2926 * but we can't do that here because we want to call
2927 * hammer2_chain_modify() to reallocate the block (if necessary).
2929 nchain->modify_tid = ochain->modify_tid;
2931 if (ochain->flags & HAMMER2_CHAIN_DELETED) {
2932 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
2933 if (ochain->delete_tid > trans->sync_tid) {
2935 * delete-duplicate a chain deleted in a later
2936 * transaction. Only allowed on chains created
2937 * before or during the current transaction (flush
2938 * code should filter out chains created after the
2939 * current transaction).
2941 * To make this work is a bit of a hack. We convert
2942 * ochain's delete_tid to the current sync_tid and
2943 * create a nchain which sets up ochains original
2946 * This effectively forces ochain to flush as a
2947 * deletion and nchain as a creation. Thus MOVED
2948 * must be set in ochain (it should already be
2949 * set since it's original delete_tid could not
2950 * have been flushed yet). Since ochain's delete_tid
2951 * has been moved down to sync_tid, a re-flush at
2952 * sync_tid won't try to delete-duplicate ochain
2955 KKASSERT(ochain->modify_tid <= trans->sync_tid);
2956 nchain->delete_tid = ochain->delete_tid;
2957 ochain->delete_tid = trans->sync_tid;
2958 KKASSERT(ochain->flags & HAMMER2_CHAIN_MOVED);
2959 } else if (ochain->delete_tid == trans->sync_tid) {
2961 * ochain was deleted in the current transaction
2963 nchain->delete_tid = trans->sync_tid;
2966 * ochain was deleted in a prior transaction.
2967 * create and delete nchain in the current
2970 nchain->delete_tid = trans->sync_tid;
2972 hammer2_chain_insert(above, ochain->inlayer, nchain, 0);
2974 KKASSERT(trans->sync_tid >= ochain->modify_tid);
2975 ochain->delete_tid = trans->sync_tid;
2976 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2977 atomic_add_int(&above->live_count, -1);
2978 hammer2_chain_insert(above, NULL, nchain,
2979 HAMMER2_CHAIN_INSERT_LIVE);
2982 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2983 hammer2_chain_ref(ochain);
2984 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2986 spin_unlock(&above->cst.spin);
2989 * ochain must be unlocked because ochain and nchain might share
2990 * a buffer cache buffer, so we need to release it so nchain can
2991 * potentially obtain it.
2993 hammer2_chain_unlock(ochain);
2996 * Finishing fixing up nchain. A new block will be allocated if
2997 * crossing a synchronization point (meta-data only).
2999 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3000 hammer2_chain_modify(trans, &nchain,
3001 HAMMER2_MODIFY_OPTDATA |
3002 HAMMER2_MODIFY_NOREALLOC |
3003 HAMMER2_MODIFY_INPLACE);
3004 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3005 hammer2_chain_modify(trans, &nchain,
3006 HAMMER2_MODIFY_OPTDATA |
3007 HAMMER2_MODIFY_INPLACE);
3009 hammer2_chain_modify(trans, &nchain,
3010 HAMMER2_MODIFY_INPLACE);
3012 hammer2_chain_drop(nchain);
3015 * Unconditionally set MOVED to force the parent blockrefs to
3016 * update as the chain_modify() above won't necessarily do it.
3018 * Adjust update_hi below nchain so nchain's blockrefs are updated
3019 * with the new attachment.
3021 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3022 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
3023 hammer2_chain_ref(nchain);
3026 if (nchain->core->update_hi < trans->sync_tid) {
3027 spin_lock(&nchain->core->cst.spin);
3028 if (nchain->core->update_hi < trans->sync_tid)
3029 nchain->core->update_hi = trans->sync_tid;
3030 spin_unlock(&nchain->core->cst.spin);
3033 hammer2_chain_setsubmod(trans, nchain);
3038 * Helper function to fixup inodes. The caller procedure stack may hold
3039 * multiple locks on ochain if it represents an inode, preventing our
3040 * unlock from retiring its state to the buffer cache.
3042 * In this situation any attempt to access the buffer cache could result
3043 * either in stale data or a deadlock. Work around the problem by copying
3044 * the embedded data directly.
3048 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
3050 if (ochain->data == NULL)
3052 switch(ochain->bref.type) {
3053 case HAMMER2_BREF_TYPE_INODE:
3054 KKASSERT(nchain->data == NULL);
3055 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
3056 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
3057 ochain->hmp->mchain, M_WAITOK | M_ZERO);
3058 nchain->data->ipdata = ochain->data->ipdata;
3060 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3061 KKASSERT(nchain->data == NULL);
3062 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
3063 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
3064 ochain->hmp->mchain, M_WAITOK | M_ZERO);
3065 bcopy(ochain->data->bmdata,
3066 nchain->data->bmdata,
3067 sizeof(nchain->data->bmdata));
3075 * Create a snapshot of the specified {parent, ochain} with the specified
3076 * label. The originating hammer2_inode must be exclusively locked for
3079 * The ioctl code has already synced the filesystem.
3082 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
3083 hammer2_ioc_pfs_t *pfs)
3085 hammer2_mount_t *hmp;
3086 hammer2_chain_t *ochain = *ochainp;
3087 hammer2_chain_t *nchain;
3088 hammer2_inode_data_t *ipdata;
3089 hammer2_inode_t *nip;
3096 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
3097 pfs->name, ochain->refs, ochain->flags);
3099 name_len = strlen(pfs->name);
3100 lhc = hammer2_dirhash(pfs->name, name_len);
3103 opfs_clid = ochain->data->ipdata.pfs_clid;
3108 * Create the snapshot directory under the super-root
3110 * Set PFS type, generate a unique filesystem id, and generate
3111 * a cluster id. Use the same clid when snapshotting a PFS root,
3112 * which theoretically allows the snapshot to be used as part of
3113 * the same cluster (perhaps as a cache).
3115 * Copy the (flushed) ochain's blockref array. Theoretically we
3116 * could use chain_duplicate() but it becomes difficult to disentangle
3117 * the shared core so for now just brute-force it.
3123 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
3124 pfs->name, name_len, &nchain, &error);
3127 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
3128 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
3129 kern_uuidgen(&ipdata->pfs_fsid, 1);
3130 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
3131 ipdata->pfs_clid = opfs_clid;
3133 kern_uuidgen(&ipdata->pfs_clid, 1);
3134 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
3135 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
3137 hammer2_inode_unlock_ex(nip, nchain);
3143 * Create an indirect block that covers one or more of the elements in the
3144 * current parent. Either returns the existing parent with no locking or
3145 * ref changes or returns the new indirect block locked and referenced
3146 * and leaving the original parent lock/ref intact as well.
3148 * If an error occurs, NULL is returned and *errorp is set to the error.
3150 * The returned chain depends on where the specified key falls.
3152 * The key/keybits for the indirect mode only needs to follow three rules:
3154 * (1) That all elements underneath it fit within its key space and
3156 * (2) That all elements outside it are outside its key space.
3158 * (3) When creating the new indirect block any elements in the current
3159 * parent that fit within the new indirect block's keyspace must be
3160 * moved into the new indirect block.
3162 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3163 * keyspace the the current parent, but lookup/iteration rules will
3164 * ensure (and must ensure) that rule (2) for all parents leading up
3165 * to the nearest inode or the root volume header is adhered to. This
3166 * is accomplished by always recursing through matching keyspaces in
3167 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3169 * The current implementation calculates the current worst-case keyspace by
3170 * iterating the current parent and then divides it into two halves, choosing
3171 * whichever half has the most elements (not necessarily the half containing
3172 * the requested key).
3174 * We can also opt to use the half with the least number of elements. This
3175 * causes lower-numbered keys (aka logical file offsets) to recurse through
3176 * fewer indirect blocks and higher-numbered keys to recurse through more.
3177 * This also has the risk of not moving enough elements to the new indirect
3178 * block and being forced to create several indirect blocks before the element
3181 * Must be called with an exclusively locked parent.
3183 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3184 hammer2_key_t *keyp, int keybits,
3185 hammer2_blockref_t *base, int count);
3186 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3187 hammer2_key_t *keyp, int keybits,
3188 hammer2_blockref_t *base, int count);
3191 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3192 hammer2_key_t create_key, int create_bits,
3193 int for_type, int *errorp)
3195 hammer2_mount_t *hmp;
3196 hammer2_chain_core_t *above;
3197 hammer2_chain_core_t *icore;
3198 hammer2_blockref_t *base;
3199 hammer2_blockref_t *bref;
3200 hammer2_blockref_t bcopy;
3201 hammer2_chain_t *chain;
3202 hammer2_chain_t *ichain;
3203 hammer2_chain_t dummy;
3204 hammer2_key_t key = create_key;
3205 hammer2_key_t key_beg;
3206 hammer2_key_t key_end;
3207 hammer2_key_t key_next;
3208 int keybits = create_bits;
3215 * Calculate the base blockref pointer or NULL if the chain
3216 * is known to be empty. We need to calculate the array count
3217 * for RB lookups either way.
3221 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3222 above = parent->core;
3224 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3225 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3228 switch(parent->bref.type) {
3229 case HAMMER2_BREF_TYPE_INODE:
3230 count = HAMMER2_SET_COUNT;
3232 case HAMMER2_BREF_TYPE_INDIRECT:
3233 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3234 count = parent->bytes / sizeof(hammer2_blockref_t);
3236 case HAMMER2_BREF_TYPE_VOLUME:
3237 count = HAMMER2_SET_COUNT;
3239 case HAMMER2_BREF_TYPE_FREEMAP:
3240 count = HAMMER2_SET_COUNT;
3243 panic("hammer2_chain_create_indirect: "
3244 "unrecognized blockref type: %d",
3250 switch(parent->bref.type) {
3251 case HAMMER2_BREF_TYPE_INODE:
3252 base = &parent->data->ipdata.u.blockset.blockref[0];
3253 count = HAMMER2_SET_COUNT;
3255 case HAMMER2_BREF_TYPE_INDIRECT:
3256 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3257 base = &parent->data->npdata[0];
3258 count = parent->bytes / sizeof(hammer2_blockref_t);
3260 case HAMMER2_BREF_TYPE_VOLUME:
3261 base = &hmp->voldata.sroot_blockset.blockref[0];
3262 count = HAMMER2_SET_COUNT;
3264 case HAMMER2_BREF_TYPE_FREEMAP:
3265 base = &hmp->voldata.freemap_blockset.blockref[0];
3266 count = HAMMER2_SET_COUNT;
3269 panic("hammer2_chain_create_indirect: "
3270 "unrecognized blockref type: %d",
3278 * dummy used in later chain allocation (no longer used for lookups).
3280 bzero(&dummy, sizeof(dummy));
3281 dummy.delete_tid = HAMMER2_MAX_TID;
3284 * When creating an indirect block for a freemap node or leaf
3285 * the key/keybits must be fitted to static radix levels because
3286 * particular radix levels use particular reserved blocks in the
3289 * This routine calculates the key/radix of the indirect block
3290 * we need to create, and whether it is on the high-side or the
3293 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3294 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3295 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3298 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3303 * Normalize the key for the radix being represented, keeping the
3304 * high bits and throwing away the low bits.
3306 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3309 * How big should our new indirect block be? It has to be at least
3310 * as large as its parent.
3312 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3313 nbytes = HAMMER2_IND_BYTES_MIN;
3315 nbytes = HAMMER2_IND_BYTES_MAX;
3316 if (nbytes < count * sizeof(hammer2_blockref_t))
3317 nbytes = count * sizeof(hammer2_blockref_t);
3320 * Ok, create our new indirect block
3322 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3323 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3324 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3326 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3328 dummy.bref.key = key;
3329 dummy.bref.keybits = keybits;
3330 dummy.bref.data_off = hammer2_getradix(nbytes);
3331 dummy.bref.methods = parent->bref.methods;
3333 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3334 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3335 hammer2_chain_core_alloc(trans, ichain, NULL);
3336 icore = ichain->core;
3337 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3338 hammer2_chain_drop(ichain); /* excess ref from alloc */
3341 * We have to mark it modified to allocate its block, but use
3342 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3343 * it won't be acted upon by the flush code.
3345 * XXX leave the node unmodified, depend on the update_hi
3346 * flush to assign and modify parent blocks.
3348 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3351 * Iterate the original parent and move the matching brefs into
3352 * the new indirect block.
3354 * XXX handle flushes.
3357 key_end = HAMMER2_MAX_KEY;
3359 spin_lock(&above->cst.spin);
3363 if (++loops > 8192) {
3364 spin_unlock(&above->cst.spin);
3365 panic("shit parent=%p base/count %p:%d\n",
3366 parent, base, count);
3370 * NOTE: spinlock stays intact, returned chain (if not NULL)
3371 * is not referenced or locked.
3373 chain = hammer2_combined_find(parent, base, count,
3374 &cache_index, &key_next,
3379 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3380 if (key_next == 0 || key_next > key_end)
3387 * Use the full live (not deleted) element for the scan
3388 * iteration. HAMMER2 does not allow partial replacements.
3390 * XXX should be built into hammer2_combined_find().
3392 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3395 * Skip keys that are not within the key/radix of the new
3396 * indirect block. They stay in the parent.
3398 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3399 (key ^ bref->key)) != 0) {
3400 if (key_next == 0 || key_next > key_end)
3407 * Load the new indirect block by acquiring or allocating
3408 * the related chain, then move it to the new parent (ichain)
3409 * via DELETE-DUPLICATE.
3411 * WARNING! above->cst.spin must be held when parent is
3412 * modified, even though we own the full blown lock,
3413 * to deal with setsubmod and rename races.
3414 * (XXX remove this req).
3418 * Use chain already present in the RBTREE
3420 hammer2_chain_ref(chain);
3421 spin_unlock(&above->cst.spin);
3422 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3423 HAMMER2_RESOLVE_NOREF);
3426 * Get chain for blockref element. _get returns NULL
3427 * on insertion race.
3430 spin_unlock(&above->cst.spin);
3431 chain = hammer2_chain_get(parent, bref);
3434 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3435 hammer2_chain_drop(chain);
3438 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3439 HAMMER2_RESOLVE_NOREF);
3441 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
3442 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0);
3443 hammer2_chain_unlock(chain);
3444 KKASSERT(parent->refs > 0);
3446 spin_lock(&above->cst.spin);
3447 if (key_next == 0 || key_next > key_end)
3451 spin_unlock(&above->cst.spin);
3454 * Insert the new indirect block into the parent now that we've
3455 * cleared out some entries in the parent. We calculated a good
3456 * insertion index in the loop above (ichain->index).
3458 * We don't have to set MOVED here because we mark ichain modified
3459 * down below (so the normal modified -> flush -> set-moved sequence
3462 * The insertion shouldn't race as this is a completely new block
3463 * and the parent is locked.
3465 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3466 hammer2_chain_insert(above, NULL, ichain,
3467 HAMMER2_CHAIN_INSERT_SPIN |
3468 HAMMER2_CHAIN_INSERT_LIVE);
3471 * Mark the new indirect block modified after insertion, which
3472 * will propagate up through parent all the way to the root and
3473 * also allocate the physical block in ichain for our caller,
3474 * and assign ichain->data to a pre-zero'd space (because there
3475 * is not prior data to copy into it).
3477 * We have to set update_hi in ichain's flags manually so the
3478 * flusher knows it has to recurse through it to get to all of
3479 * our moved blocks, then call setsubmod() to set the bit
3482 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3483 if (ichain->core->update_hi < trans->sync_tid) {
3484 spin_lock(&ichain->core->cst.spin);
3485 if (ichain->core->update_hi < trans->sync_tid)
3486 ichain->core->update_hi = trans->sync_tid;
3487 spin_unlock(&ichain->core->cst.spin);
3489 hammer2_chain_setsubmod(trans, ichain);
3492 * Figure out what to return.
3494 if (~(((hammer2_key_t)1 << keybits) - 1) &
3495 (create_key ^ key)) {
3497 * Key being created is outside the key range,
3498 * return the original parent.
3500 hammer2_chain_unlock(ichain);
3503 * Otherwise its in the range, return the new parent.
3504 * (leave both the new and old parent locked).
3513 * Calculate the keybits and highside/lowside of the freemap node the
3514 * caller is creating.
3516 * This routine will specify the next higher-level freemap key/radix
3517 * representing the lowest-ordered set. By doing so, eventually all
3518 * low-ordered sets will be moved one level down.
3520 * We have to be careful here because the freemap reserves a limited
3521 * number of blocks for a limited number of levels. So we can't just
3522 * push indiscriminately.
3525 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3526 int keybits, hammer2_blockref_t *base, int count)
3528 hammer2_chain_core_t *above;
3529 hammer2_chain_t *chain;
3530 hammer2_blockref_t *bref;
3532 hammer2_key_t key_beg;
3533 hammer2_key_t key_end;
3534 hammer2_key_t key_next;
3541 above = parent->core;
3547 * Calculate the range of keys in the array being careful to skip
3548 * slots which are overridden with a deletion.
3551 key_end = HAMMER2_MAX_KEY;
3553 spin_lock(&above->cst.spin);
3556 if (++loops == 100000) {
3557 panic("indkey_freemap shit %p %p:%d\n",
3558 parent, base, count);
3560 chain = hammer2_combined_find(parent, base, count,
3561 &cache_index, &key_next,
3562 key_beg, key_end, &bref);
3569 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3570 if (key_next == 0 || key_next > key_end)
3577 * Use the full live (not deleted) element for the scan
3578 * iteration. HAMMER2 does not allow partial replacements.
3580 * XXX should be built into hammer2_combined_find().
3582 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3584 if (keybits > bref->keybits) {
3586 keybits = bref->keybits;
3587 } else if (keybits == bref->keybits && bref->key < key) {
3594 spin_unlock(&above->cst.spin);
3597 * Return the keybits for a higher-level FREEMAP_NODE covering
3601 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3602 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3604 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3605 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3607 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3608 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3610 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3611 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3613 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3614 panic("hammer2_chain_indkey_freemap: level too high");
3617 panic("hammer2_chain_indkey_freemap: bad radix");
3626 * Calculate the keybits and highside/lowside of the indirect block the
3627 * caller is creating.
3630 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3631 int keybits, hammer2_blockref_t *base, int count)
3633 hammer2_chain_core_t *above;
3634 hammer2_blockref_t *bref;
3635 hammer2_chain_t *chain;
3636 hammer2_key_t key_beg;
3637 hammer2_key_t key_end;
3638 hammer2_key_t key_next;
3647 above = parent->core;
3652 * Calculate the range of keys in the array being careful to skip
3653 * slots which are overridden with a deletion. Once the scan
3654 * completes we will cut the key range in half and shift half the
3655 * range into the new indirect block.
3658 key_end = HAMMER2_MAX_KEY;
3660 spin_lock(&above->cst.spin);
3663 if (++loops == 100000) {
3664 panic("indkey_freemap shit %p %p:%d\n",
3665 parent, base, count);
3667 chain = hammer2_combined_find(parent, base, count,
3668 &cache_index, &key_next,
3669 key_beg, key_end, &bref);
3676 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3677 if (key_next == 0 || key_next > key_end)
3684 * Use the full live (not deleted) element for the scan
3685 * iteration. HAMMER2 does not allow partial replacements.
3687 * XXX should be built into hammer2_combined_find().
3689 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3692 * Expand our calculated key range (key, keybits) to fit
3693 * the scanned key. nkeybits represents the full range
3694 * that we will later cut in half (two halves @ nkeybits - 1).
3697 if (nkeybits < bref->keybits) {
3698 if (bref->keybits > 64) {
3699 kprintf("bad bref chain %p bref %p\n",
3703 nkeybits = bref->keybits;
3705 while (nkeybits < 64 &&
3706 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3707 (key ^ bref->key)) != 0) {
3712 * If the new key range is larger we have to determine
3713 * which side of the new key range the existing keys fall
3714 * under by checking the high bit, then collapsing the
3715 * locount into the hicount or vise-versa.
3717 if (keybits != nkeybits) {
3718 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3729 * The newly scanned key will be in the lower half or the
3730 * upper half of the (new) key range.
3732 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3741 spin_unlock(&above->cst.spin);
3742 bref = NULL; /* now invalid (safety) */
3745 * Adjust keybits to represent half of the full range calculated
3746 * above (radix 63 max)
3751 * Select whichever half contains the most elements. Theoretically
3752 * we can select either side as long as it contains at least one
3753 * element (in order to ensure that a free slot is present to hold
3754 * the indirect block).
3756 if (hammer2_indirect_optimize) {
3758 * Insert node for least number of keys, this will arrange
3759 * the first few blocks of a large file or the first few
3760 * inodes in a directory with fewer indirect blocks when
3763 if (hicount < locount && hicount != 0)
3764 key |= (hammer2_key_t)1 << keybits;
3766 key &= ~(hammer2_key_t)1 << keybits;
3769 * Insert node for most number of keys, best for heavily
3772 if (hicount > locount)
3773 key |= (hammer2_key_t)1 << keybits;
3775 key &= ~(hammer2_key_t)1 << keybits;
3783 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3784 * set chain->delete_tid. The chain is not actually marked possibly-free
3785 * in the freemap until the deletion is completely flushed out (because
3786 * a flush which doesn't cover the entire deletion is flushing the deleted
3787 * chain as if it were live).
3789 * This function does NOT generate a modification to the parent. It
3790 * would be nearly impossible to figure out which parent to modify anyway.
3791 * Such modifications are handled top-down by the flush code and are
3792 * properly merged using the flush synchronization point.
3794 * The find/get code will properly overload the RBTREE check on top of
3795 * the bref check to detect deleted entries.
3797 * This function is NOT recursive. Any entity already pushed into the
3798 * chain (such as an inode) may still need visibility into its contents,
3799 * as well as the ability to read and modify the contents. For example,
3800 * for an unlinked file which is still open.
3802 * NOTE: This function does NOT set chain->modify_tid, allowing future
3803 * code to distinguish between live and deleted chains by testing
3804 * trans->sync_tid vs chain->modify_tid and chain->delete_tid.
3806 * NOTE: Deletions normally do not occur in the middle of a duplication
3807 * chain but we use a trick for hardlink migration that refactors
3808 * the originating inode without deleting it, so we make no assumptions
3812 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3814 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3817 * Nothing to do if already marked.
3819 if (chain->flags & HAMMER2_CHAIN_DELETED)
3823 * The setting of DELETED causes finds, lookups, and _next iterations
3824 * to no longer recognize the chain. RB_SCAN()s will still have
3825 * visibility (needed for flush serialization points).
3827 * We need the spinlock on the core whos RBTREE contains chain
3828 * to protect against races.
3830 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3831 spin_lock(&chain->above->cst.spin);
3833 KKASSERT(trans->sync_tid >= chain->modify_tid);
3834 chain->delete_tid = trans->sync_tid;
3835 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3836 atomic_add_int(&chain->above->live_count, -1);
3837 ++chain->above->generation;
3840 * We must set MOVED along with DELETED for the flush code to
3841 * recognize the operation and properly disconnect the chain
3844 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3845 hammer2_chain_ref(chain);
3846 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3848 spin_unlock(&chain->above->cst.spin);
3850 if (flags & HAMMER2_DELETE_WILLDUP)
3851 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
3853 hammer2_chain_setsubmod(trans, chain);
3857 * Called with the core spinlock held to check for freeable layers.
3858 * Used by the flush code. Layers can wind up not being freed due
3859 * to the temporary layer->refs count. This function frees up any
3860 * layers that were missed.
3863 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3864 hammer2_chain_core_t *core)
3866 hammer2_chain_layer_t *layer;
3867 hammer2_chain_layer_t *tmp;
3869 tmp = TAILQ_FIRST(&core->layerq);
3870 while ((layer = tmp) != NULL) {
3871 tmp = TAILQ_NEXT(tmp, entry);
3872 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
3873 TAILQ_REMOVE(&core->layerq, layer, entry);
3876 spin_unlock(&core->cst.spin);
3877 kfree(layer, hmp->mchain);
3878 spin_lock(&core->cst.spin);
3886 * Returns the index of the nearest element in the blockref array >= elm.
3887 * Returns (count) if no element could be found.
3889 * Sets *key_nextp to the next key for loop purposes but does not modify
3890 * it if the next key would be higher than the current value of *key_nextp.
3891 * Note that *key_nexp can overflow to 0, which should be tested by the
3894 * (*cache_indexp) is a heuristic and can be any value without effecting
3897 * The spin lock on the related chain must be held.
3900 hammer2_base_find(hammer2_chain_t *chain,
3901 hammer2_blockref_t *base, int count,
3902 int *cache_indexp, hammer2_key_t *key_nextp,
3903 hammer2_key_t key_beg, hammer2_key_t key_end)
3905 hammer2_chain_core_t *core = chain->core;
3906 hammer2_blockref_t *scan;
3907 hammer2_key_t scan_end;
3913 KKASSERT(core->flags & HAMMER2_CORE_COUNTEDBREFS);
3914 if (count == 0 || base == NULL)
3918 * Sequential optimization
3922 if (i >= core->live_zero)
3923 i = core->live_zero - 1;
3926 KKASSERT(i < count);
3932 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3939 * Search forwards, stop when we find a scan element which
3940 * encloses the key or until we know that there are no further
3944 if (scan->type != 0) {
3945 if (scan->key > key_beg)
3947 scan_end = scan->key +
3948 ((hammer2_key_t)1 << scan->keybits) - 1;
3949 if (scan_end >= key_beg)
3952 if (i >= core->live_zero)
3959 if (i >= core->live_zero) {
3962 scan_end = scan->key +
3963 ((hammer2_key_t)1 << scan->keybits);
3964 if (scan_end && (*key_nextp > scan_end ||
3966 *key_nextp = scan_end;
3974 * Do a combined search and return the next match either from the blockref
3975 * array or from the in-memory chain. Sets *bresp to the returned bref in
3976 * both cases, or sets it to NULL if the search exhausted. Only returns
3977 * a non-NULL chain if the search matched from the in-memory chain.
3979 * Must be called with above's spinlock held. Spinlock remains held
3980 * through the operation.
3982 * The returned chain is not locked or referenced. Use the returned bref
3983 * to determine if the search exhausted or not.
3985 static hammer2_chain_t *
3986 hammer2_combined_find(hammer2_chain_t *parent,
3987 hammer2_blockref_t *base, int count,
3988 int *cache_indexp, hammer2_key_t *key_nextp,
3989 hammer2_key_t key_beg, hammer2_key_t key_end,
3990 hammer2_blockref_t **bresp)
3992 hammer2_blockref_t *bref;
3993 hammer2_chain_t *chain;
3996 *key_nextp = key_end + 1;
3997 i = hammer2_base_find(parent, base, count, cache_indexp,
3998 key_nextp, key_beg, key_end);
3999 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4004 if (i == count && chain == NULL) {
4006 return(chain); /* NULL */
4010 * Only chain matched
4013 bref = &chain->bref;
4018 * Only blockref matched.
4020 if (chain == NULL) {
4026 * Both in-memory and blockref match.
4028 * If they are both flush with the left hand side select the chain.
4029 * If their starts match select the chain.
4030 * Otherwise the nearer element wins.
4032 if (chain->bref.key <= key_beg && base[i].key <= key_beg) {
4033 bref = &chain->bref;
4036 if (chain->bref.key <= base[i].key) {
4037 bref = &chain->bref;
4045 * If the bref is out of bounds we've exhausted our search.
4048 if (bref->key > key_end) {
4058 * Locate the specified block array element and delete it. The element
4061 * The spin lock on the related chain must be held.
4063 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4064 * need to be adjusted when we commit the media change.
4067 hammer2_base_delete(hammer2_chain_t *chain,
4068 hammer2_blockref_t *base, int count,
4069 int *cache_indexp, hammer2_chain_t *child)
4071 hammer2_blockref_t *elm = &child->bref;
4072 hammer2_chain_core_t *core = chain->core;
4073 hammer2_key_t key_next;
4077 * Delete element. Expect the element to exist.
4079 * XXX see caller, flush code not yet sophisticated enough to prevent
4080 * re-flushed in some cases.
4082 key_next = 0; /* max range */
4083 i = hammer2_base_find(chain, base, count, cache_indexp,
4084 &key_next, elm->key, elm->key);
4085 if (i == count || base[i].type == 0 ||
4086 base[i].key != elm->key || base[i].keybits != elm->keybits) {
4087 panic("delete base %p element not found at %d/%d elm %p\n",
4088 base, i, count, elm);
4091 bzero(&base[i], sizeof(*base));
4092 if (core->live_zero == i + 1) {
4093 while (--i >= 0 && base[i].type == 0)
4095 core->live_zero = i + 1;
4100 * Insert the specified element. The block array must not already have the
4101 * element and must have space available for the insertion.
4103 * The spin lock on the related chain must be held.
4105 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4106 * need to be adjusted when we commit the media change.
4109 hammer2_base_insert(hammer2_chain_t *parent,
4110 hammer2_blockref_t *base, int count,
4111 int *cache_indexp, hammer2_chain_t *child)
4113 hammer2_blockref_t *elm = &child->bref;
4114 hammer2_chain_core_t *core = parent->core;
4115 hammer2_key_t key_next;
4124 * Insert new element. Expect the element to not already exist
4125 * unless we are replacing it.
4127 * XXX see caller, flush code not yet sophisticated enough to prevent
4128 * re-flushed in some cases.
4130 key_next = 0; /* max range */
4131 i = hammer2_base_find(parent, base, count, cache_indexp,
4132 &key_next, elm->key, elm->key);
4135 * Shortcut fill optimization, typical ordered insertion(s) may not
4138 KKASSERT(i >= 0 && i <= count);
4140 if (i == count && core->live_zero < count) {
4141 i = core->live_zero++;
4146 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4147 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4148 panic("insert base %p overlapping elements at %d elm %p\n",
4153 * Try to find an empty slot before or after.
4157 while (j > 0 || k < count) {
4159 if (j >= 0 && base[j].type == 0) {
4163 bcopy(&base[j+1], &base[j],
4164 (i - j - 1) * sizeof(*base));
4170 if (k < count && base[k].type == 0) {
4171 bcopy(&base[i], &base[i+1],
4172 (k - i) * sizeof(hammer2_blockref_t));
4174 if (core->live_zero <= k)
4175 core->live_zero = k + 1;
4180 panic("hammer2_base_insert: no room!");
4187 for (l = 0; l < count; ++l) {
4189 key_next = base[l].key +
4190 ((hammer2_key_t)1 << base[l].keybits) - 1;
4194 while (++l < count) {
4196 if (base[l].key <= key_next)
4197 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4198 key_next = base[l].key +
4199 ((hammer2_key_t)1 << base[l].keybits) - 1;
4209 * Sort the blockref array for the chain. Used by the flush code to
4210 * sort the blockref[] array.
4212 * The chain must be exclusively locked AND spin-locked.
4214 typedef hammer2_blockref_t *hammer2_blockref_p;
4218 hammer2_base_sort_callback(const void *v1, const void *v2)
4220 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4221 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4224 * Make sure empty elements are placed at the end of the array
4226 if (bref1->type == 0) {
4227 if (bref2->type == 0)
4230 } else if (bref2->type == 0) {
4237 if (bref1->key < bref2->key)
4239 if (bref1->key > bref2->key)
4245 hammer2_base_sort(hammer2_chain_t *chain)
4247 hammer2_blockref_t *base;
4250 switch(chain->bref.type) {
4251 case HAMMER2_BREF_TYPE_INODE:
4253 * Special shortcut for embedded data returns the inode
4254 * itself. Callers must detect this condition and access
4255 * the embedded data (the strategy code does this for us).
4257 * This is only applicable to regular files and softlinks.
4259 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4261 base = &chain->data->ipdata.u.blockset.blockref[0];
4262 count = HAMMER2_SET_COUNT;
4264 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4265 case HAMMER2_BREF_TYPE_INDIRECT:
4267 * Optimize indirect blocks in the INITIAL state to avoid
4270 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4271 base = &chain->data->npdata[0];
4272 count = chain->bytes / sizeof(hammer2_blockref_t);
4274 case HAMMER2_BREF_TYPE_VOLUME:
4275 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4276 count = HAMMER2_SET_COUNT;
4278 case HAMMER2_BREF_TYPE_FREEMAP:
4279 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4280 count = HAMMER2_SET_COUNT;
4283 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4285 base = NULL; /* safety */
4286 count = 0; /* safety */
4288 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4294 * Chain memory management
4297 hammer2_chain_wait(hammer2_chain_t *chain)
4299 tsleep(chain, 0, "chnflw", 1);
4303 * Manage excessive memory resource use for chain and related
4307 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4310 while (pmp->inmem_chains > desiredvnodes / 10 &&
4311 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 2) {
4313 speedup_syncer(pmp->mp);
4314 pmp->inmem_waiting = 1;
4315 tsleep(&pmp->inmem_waiting, 0, "chnmem", hz);
4319 if (pmp->inmem_chains > desiredvnodes / 10 &&
4320 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 7 / 4) {
4321 speedup_syncer(pmp->mp);
4327 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4329 if (pmp->inmem_waiting &&
4330 (pmp->inmem_chains <= desiredvnodes / 10 ||
4331 pmp->inmem_chains <= pmp->mp->mnt_nvnodelistsize * 2)) {
4333 pmp->inmem_waiting = 0;
4334 wakeup(&pmp->inmem_waiting);
4340 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4344 switch(bref->type) {
4345 case HAMMER2_BREF_TYPE_DATA:
4346 counterp = &hammer2_iod_file_read;
4348 case HAMMER2_BREF_TYPE_INODE:
4349 counterp = &hammer2_iod_meta_read;
4351 case HAMMER2_BREF_TYPE_INDIRECT:
4352 counterp = &hammer2_iod_indr_read;
4354 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4355 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4356 counterp = &hammer2_iod_fmap_read;
4359 counterp = &hammer2_iod_volu_read;