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);
96 static void hammer2_chain_assert_not_present(hammer2_chain_core_t *above,
97 hammer2_chain_t *chain);
99 hammer2_chain_t *XXChain;
102 * Basic RBTree for chains. Chains cannot overlap within any given
103 * core->rbtree without recursing through chain->rbtree. We effectively
104 * guarantee this by checking the full range rather than just the first
105 * key element. By matching on the full range callers can detect when
106 * recursrion through chain->rbtree is needed.
108 * NOTE: This also means the a delete-duplicate on the same key will
109 * overload by placing the deleted element in the new element's
110 * chain->rbtree (when doing a direct replacement).
112 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
115 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
117 hammer2_key_t c1_beg;
118 hammer2_key_t c1_end;
119 hammer2_key_t c2_beg;
120 hammer2_key_t c2_end;
122 c1_beg = chain1->bref.key;
123 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
124 c2_beg = chain2->bref.key;
125 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
127 if (c1_end < c2_beg) /* fully to the left */
129 if (c1_beg > c2_end) /* fully to the right */
131 return(0); /* overlap (must not cross edge boundary) */
136 hammer2_isclusterable(hammer2_chain_t *chain)
138 if (hammer2_cluster_enable) {
139 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
140 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
141 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
149 * Recursively set the update_hi flag up to the root starting at chain's
150 * parent->core. update_hi is not set in chain's core.
152 * This controls top-down visibility for flushes. The child has just one
153 * 'above' core, but the core itself can be multi-homed with parents iterated
156 * This function is not used during a flush (except when the flush is
157 * allocating which requires the live tree). The flush keeps track of its
160 * XXX needs to be optimized to use roll-up TIDs. update_hi is only really
161 * compared against bref.mirror_tid which itself is only updated by a flush.
164 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
166 hammer2_chain_core_t *above;
168 while ((above = chain->above) != NULL) {
169 spin_lock(&above->cst.spin);
171 if (above->update_hi < trans->sync_tid)
172 above->update_hi = trans->sync_tid;
173 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
175 TAILQ_FOREACH_REVERSE(chain, &above->ownerq,
176 h2_core_list, core_entry) {
177 if (trans->sync_tid >= chain->modify_tid &&
178 trans->sync_tid <= chain->delete_tid) {
183 spin_unlock(&above->cst.spin);
188 * Allocate a new disconnected chain element representing the specified
189 * bref. chain->refs is set to 1 and the passed bref is copied to
190 * chain->bref. chain->bytes is derived from the bref.
192 * chain->core is NOT allocated and the media data and bp pointers are left
193 * NULL. The caller must call chain_core_alloc() to allocate or associate
194 * a core with the chain.
196 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
199 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
200 hammer2_trans_t *trans, hammer2_blockref_t *bref)
202 hammer2_chain_t *chain;
203 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
206 * Construct the appropriate system structure.
209 case HAMMER2_BREF_TYPE_INODE:
210 case HAMMER2_BREF_TYPE_INDIRECT:
211 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
212 case HAMMER2_BREF_TYPE_DATA:
213 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
215 * Chain's are really only associated with the hmp but we
216 * maintain a pmp association for per-mount memory tracking
217 * purposes. The pmp can be NULL.
219 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
223 case HAMMER2_BREF_TYPE_VOLUME:
224 case HAMMER2_BREF_TYPE_FREEMAP:
226 panic("hammer2_chain_alloc volume type illegal for op");
229 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
235 chain->bytes = bytes;
237 chain->flags = HAMMER2_CHAIN_ALLOCATED;
238 chain->delete_tid = HAMMER2_MAX_TID;
241 * Set modify_tid if a transaction is creating the chain. When
242 * loading a chain from backing store trans is passed as NULL and
243 * modify_tid is left set to 0.
246 chain->modify_tid = trans->sync_tid;
252 * Associate an existing core with the chain or allocate a new core.
254 * The core is not locked. No additional refs on the chain are made.
255 * (trans) must not be NULL if (core) is not NULL.
257 * When chains are delete-duplicated during flushes we insert nchain on
258 * the ownerq after ochain instead of at the end in order to give the
259 * drop code visibility in the correct order, otherwise drops can be missed.
262 hammer2_chain_core_alloc(hammer2_trans_t *trans,
263 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
265 hammer2_chain_core_t *core;
267 KKASSERT(nchain->core == NULL);
269 if (ochain == NULL) {
271 * Fresh core under nchain (no multi-homing of ochain's
274 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
276 TAILQ_INIT(&core->layerq);
277 TAILQ_INIT(&core->ownerq);
281 core->update_hi = trans->sync_tid;
283 core->update_hi = nchain->bref.mirror_tid;
285 ccms_cst_init(&core->cst, nchain);
286 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
289 * Propagate the PFSROOT flag which we set on all subdirs
290 * under the super-root.
292 atomic_set_int(&nchain->flags,
293 ochain->flags & HAMMER2_CHAIN_PFSROOT);
296 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
297 * ochain if nchain is not a snapshot.
299 * It is possible for the DUPLICATED flag to already be
300 * set when called via a flush operation because flush
301 * operations may have to work on elements with delete_tid's
302 * beyond the flush sync_tid. In this situation we must
303 * ensure that nchain is placed just after ochain in the
304 * ownerq and that the DUPLICATED flag is set on nchain so
305 * 'live' operations skip past it to the correct chain.
307 * The flusher understands the blockref synchronization state
308 * for any stale chains by observing bref.mirror_tid, which
309 * delete-duplicate replicates.
311 * WARNING! However, the case is disallowed when the flusher
312 * is allocating freemap space because this entails
313 * more than just adjusting a block table.
315 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
316 KKASSERT((trans->flags &
317 (HAMMER2_TRANS_ISFLUSH |
318 HAMMER2_TRANS_ISALLOCATING)) ==
319 HAMMER2_TRANS_ISFLUSH);
320 atomic_set_int(&nchain->flags,
321 HAMMER2_CHAIN_DUPLICATED);
323 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
324 atomic_set_int(&ochain->flags,
325 HAMMER2_CHAIN_DUPLICATED);
328 atomic_add_int(&core->sharecnt, 1);
330 spin_lock(&core->cst.spin);
334 if (core->update_hi < trans->sync_tid)
335 core->update_hi = trans->sync_tid;
339 * Maintain ordering for refactor test so we don't skip over
340 * a snapshot. Also, during flushes, delete-duplications
341 * for block-table updates can occur on blocks already
342 * deleted (delete-duplicated by a later transaction). We
343 * must insert nchain after ochain but before the later
344 * transaction's copy.
346 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
348 spin_unlock(&core->cst.spin);
353 * Add a reference to a chain element, preventing its destruction.
356 hammer2_chain_ref(hammer2_chain_t *chain)
358 atomic_add_int(&chain->refs, 1);
362 * Insert the chain in the core rbtree at the first layer
363 * which accepts it (for now we don't sort layers by the transaction tid)
365 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
366 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
367 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
371 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_layer_t *layer,
372 hammer2_chain_t *chain, int flags, int generation)
374 hammer2_chain_t *xchain;
375 hammer2_chain_layer_t *nlayer;
378 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
379 spin_lock(&above->cst.spin);
382 * Special case, place the chain in the next most-recent layer as the
383 * specified layer, inserting a layer inbetween if necessary.
386 KKASSERT((flags & HAMMER2_CHAIN_INSERT_RACE) == 0);
387 nlayer = TAILQ_PREV(layer, h2_layer_list, entry);
388 if (nlayer && RB_INSERT(hammer2_chain_tree,
389 &nlayer->rbtree, chain) == NULL) {
394 spin_unlock(&above->cst.spin);
395 KKASSERT((flags & HAMMER2_CHAIN_INSERT_LIVE) == 0);
396 nlayer = kmalloc(sizeof(*nlayer), chain->hmp->mchain,
398 RB_INIT(&nlayer->rbtree);
399 nlayer->good = 0xABCD;
400 spin_lock(&above->cst.spin);
402 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0)
403 hammer2_chain_assert_not_present(above, chain);
405 TAILQ_INSERT_BEFORE(layer, nlayer, entry);
406 RB_INSERT(hammer2_chain_tree, &nlayer->rbtree, chain);
412 * Interlocked by spinlock, check for race
414 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
415 above->generation != generation) {
421 * Try to insert, allocate a new layer if a nominal collision
422 * occurs (a collision is different from a SMP race).
424 layer = TAILQ_FIRST(&above->layerq);
428 (xchain = RB_INSERT(hammer2_chain_tree,
429 &layer->rbtree, chain)) != NULL) {
432 * Allocate a new layer to resolve the issue.
434 spin_unlock(&above->cst.spin);
435 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
437 RB_INIT(&layer->rbtree);
438 layer->good = 0xABCD;
439 spin_lock(&above->cst.spin);
441 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
442 above->generation != generation) {
443 spin_unlock(&above->cst.spin);
444 kfree(layer, chain->hmp->mchain);
445 spin_lock(&above->cst.spin);
449 hammer2_chain_assert_not_present(above, chain);
451 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
452 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
455 chain->above = above;
456 chain->inlayer = layer;
457 ++above->chain_count;
459 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
462 * We have to keep track of the effective live-view blockref count
463 * so the create code knows when to push an indirect block.
465 if ((flags & HAMMER2_CHAIN_INSERT_LIVE) &&
466 (chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
467 atomic_add_int(&above->live_count, 1);
470 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
471 spin_unlock(&above->cst.spin);
476 * Drop the caller's reference to the chain. When the ref count drops to
477 * zero this function will try to disassociate the chain from its parent and
478 * deallocate it, then recursely drop the parent using the implied ref
479 * from the chain's chain->parent.
481 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
482 struct h2_core_list *delayq);
485 hammer2_chain_drop(hammer2_chain_t *chain)
487 struct h2_core_list delayq;
488 hammer2_chain_t *scan;
492 if (hammer2_debug & 0x200000)
495 if (chain->flags & HAMMER2_CHAIN_MOVED)
497 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
499 KKASSERT(chain->refs > need);
509 chain = hammer2_chain_lastdrop(chain, &delayq);
511 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
513 /* retry the same chain */
517 * When we've exhausted lastdrop chaining pull off of delayq.
518 * chains on delayq are dead but are used to placehold other
519 * chains which we added a ref to for the purpose of dropping.
522 hammer2_mount_t *hmp;
524 if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
525 chain = (void *)scan->data;
526 TAILQ_REMOVE(&delayq, scan, core_entry);
527 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
530 kfree(scan, hmp->mchain);
537 * Safe handling of the 1->0 transition on chain. Returns a chain for
538 * recursive drop or NULL, possibly returning the same chain if the atomic
541 * Whem two chains need to be recursively dropped we use the chain
542 * we would otherwise free to placehold the additional chain. It's a bit
543 * convoluted but we can't just recurse without potentially blowing out
546 * The chain cannot be freed if it has a non-empty core (children) or
547 * it is not at the head of ownerq.
549 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
553 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
555 hammer2_pfsmount_t *pmp;
556 hammer2_mount_t *hmp;
557 hammer2_chain_core_t *above;
558 hammer2_chain_core_t *core;
559 hammer2_chain_layer_t *layer;
560 hammer2_chain_t *rdrop1;
561 hammer2_chain_t *rdrop2;
564 * Spinlock the core and check to see if it is empty. If it is
565 * not empty we leave chain intact with refs == 0. The elements
566 * in core->rbtree are associated with other chains contemporary
567 * with ours but not with our chain directly.
569 if ((core = chain->core) != NULL) {
570 spin_lock(&core->cst.spin);
573 * We can't free non-stale chains with children until we are
574 * able to free the children because there might be a flush
575 * dependency. Flushes of stale children (which should also
576 * have their deleted flag set) short-cut recursive flush
577 * dependencies and can be freed here. Any flushes which run
578 * through stale children due to the flush synchronization
579 * point should have the MOVED bit set in the chain and not
580 * reach lastdrop at this time.
582 * NOTE: We return (chain) on failure to retry.
584 if (core->chain_count &&
585 (chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
586 if (atomic_cmpset_int(&chain->refs, 1, 0))
587 chain = NULL; /* success */
588 spin_unlock(&core->cst.spin);
591 /* no chains left under us */
594 * Various parts of the code might be holding a ref on a
595 * stale chain as a placemarker which must be iterated to
596 * locate a later non-stale (live) chain. We must be sure
597 * NOT to free the later non-stale chain (which might have
598 * no refs). Otherwise mass confusion may result.
600 * The DUPLICATED flag tells us whether the chain is stale
601 * or not, so the rule is that any chain whos DUPLICATED flag
602 * is NOT set must also be at the head of the ownerq.
604 * Note that the DELETED flag is not involved. That is, a
605 * live chain can represent a deletion that has not yet been
606 * flushed (or still has refs).
609 if (TAILQ_NEXT(chain, core_entry) == NULL &&
610 TAILQ_FIRST(&core->ownerq) != chain) {
612 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 &&
613 TAILQ_FIRST(&core->ownerq) != chain) {
614 if (atomic_cmpset_int(&chain->refs, 1, 0))
615 chain = NULL; /* success */
616 spin_unlock(&core->cst.spin);
622 * chain->core has no children left so no accessors can get to our
623 * chain from there. Now we have to lock the above core to interlock
624 * remaining possible accessors that might bump chain's refs before
625 * we can safely drop chain's refs with intent to free the chain.
628 pmp = chain->pmp; /* can be NULL */
634 * Spinlock the parent and try to drop the last ref on chain.
635 * On success remove chain from its parent, otherwise return NULL.
637 * (normal core locks are top-down recursive but we define core
638 * spinlocks as bottom-up recursive, so this is safe).
640 if ((above = chain->above) != NULL) {
641 spin_lock(&above->cst.spin);
642 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
643 /* 1->0 transition failed */
644 spin_unlock(&above->cst.spin);
646 spin_unlock(&core->cst.spin);
647 return(chain); /* retry */
651 * 1->0 transition successful, remove chain from its
652 * above core. Track layer for removal/freeing.
654 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
655 layer = chain->inlayer;
656 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
657 --above->chain_count;
658 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
660 chain->inlayer = NULL;
662 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
663 TAILQ_REMOVE(&above->layerq, layer, entry);
669 * If our chain was the last chain in the parent's core the
670 * core is now empty and its parents might now be droppable.
671 * Try to drop the first multi-homed parent by gaining a
672 * ref on it here and then dropping it below.
674 if (above->chain_count == 0) {
675 rdrop1 = TAILQ_FIRST(&above->ownerq);
677 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
681 spin_unlock(&above->cst.spin);
682 above = NULL; /* safety */
686 * Successful 1->0 transition and the chain can be destroyed now.
688 * We still have the core spinlock (if core is non-NULL), and core's
689 * chain_count is 0. The above spinlock is gone.
691 * Remove chain from ownerq. Once core has no more owners (and no
692 * children which is already the case) we can destroy core.
694 * If core has more owners we may be able to continue a bottom-up
695 * drop with our next sibling.
700 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
701 rdrop2 = TAILQ_FIRST(&core->ownerq);
702 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
704 spin_unlock(&core->cst.spin);
707 * We can do the final 1->0 transition with an atomic op
708 * after releasing core's spinlock.
710 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
712 * On the 1->0 transition of core we can destroy
713 * it. Any remaining layers should no longer be
714 * referenced or visibile to other threads.
716 KKASSERT(TAILQ_EMPTY(&core->ownerq));
718 layer->good = 0xEF00;
719 kfree(layer, hmp->mchain);
721 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
722 KKASSERT(layer->refs == 0 &&
723 RB_EMPTY(&layer->rbtree));
724 TAILQ_REMOVE(&core->layerq, layer, entry);
725 layer->good = 0xEF01;
726 kfree(layer, hmp->mchain);
729 KKASSERT(core->cst.count == 0);
730 KKASSERT(core->cst.upgrade == 0);
732 kfree(core, hmp->mchain);
734 core = NULL; /* safety */
738 * All spin locks are gone, finish freeing stuff.
740 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
741 HAMMER2_CHAIN_MODIFIED)) == 0);
742 hammer2_chain_drop_data(chain, 1);
744 KKASSERT(chain->dio == NULL);
747 * Free saved empty layer and return chained drop.
750 layer->good = 0xEF02;
751 kfree(layer, hmp->mchain);
755 * Once chain resources are gone we can use the now dead chain
756 * structure to placehold what might otherwise require a recursive
757 * drop, because we have potentially two things to drop and can only
758 * return one directly.
760 if (rdrop1 && rdrop2) {
761 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
762 chain->data = (void *)rdrop1;
763 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
765 } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
766 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
768 kfree(chain, hmp->mchain);
772 * Either or both can be NULL. We already handled the case where
773 * both might not have been NULL.
782 * On either last lock release or last drop
785 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
787 /*hammer2_mount_t *hmp = chain->hmp;*/
789 switch(chain->bref.type) {
790 case HAMMER2_BREF_TYPE_VOLUME:
791 case HAMMER2_BREF_TYPE_FREEMAP:
796 KKASSERT(chain->data == NULL);
802 * Ref and lock a chain element, acquiring its data with I/O if necessary,
803 * and specify how you would like the data to be resolved.
805 * Returns 0 on success or an error code if the data could not be acquired.
806 * The chain element is locked on return regardless of whether an error
809 * The lock is allowed to recurse, multiple locking ops will aggregate
810 * the requested resolve types. Once data is assigned it will not be
811 * removed until the last unlock.
813 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
814 * (typically used to avoid device/logical buffer
817 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
818 * the INITIAL-create state (indirect blocks only).
820 * Do not resolve data elements for DATA chains.
821 * (typically used to avoid device/logical buffer
824 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
826 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
827 * it will be locked exclusive.
829 * NOTE: Embedded elements (volume header, inodes) are always resolved
832 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
833 * element will instantiate and zero its buffer, and flush it on
836 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
837 * so as not to instantiate a device buffer, which could alias against
838 * a logical file buffer. However, if ALWAYS is specified the
839 * device buffer will be instantiated anyway.
841 * WARNING! If data must be fetched a shared lock will temporarily be
842 * upgraded to exclusive. However, a deadlock can occur if
843 * the caller owns more than one shared lock.
846 hammer2_chain_lock(hammer2_chain_t *chain, int how)
848 hammer2_mount_t *hmp;
849 hammer2_chain_core_t *core;
850 hammer2_blockref_t *bref;
856 * Ref and lock the element. Recursive locks are allowed.
858 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
859 hammer2_chain_ref(chain);
860 atomic_add_int(&chain->lockcnt, 1);
863 KKASSERT(hmp != NULL);
866 * Get the appropriate lock.
869 if (how & HAMMER2_RESOLVE_SHARED)
870 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
872 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
875 * If we already have a valid data pointer no further action is
882 * Do we have to resolve the data?
884 switch(how & HAMMER2_RESOLVE_MASK) {
885 case HAMMER2_RESOLVE_NEVER:
887 case HAMMER2_RESOLVE_MAYBE:
888 if (chain->flags & HAMMER2_CHAIN_INITIAL)
890 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
893 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
896 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
899 case HAMMER2_RESOLVE_ALWAYS:
904 * Upgrade to an exclusive lock so we can safely manipulate the
905 * buffer cache. If another thread got to it before us we
908 ostate = ccms_thread_lock_upgrade(&core->cst);
910 ccms_thread_lock_downgrade(&core->cst, ostate);
915 * We must resolve to a device buffer, either by issuing I/O or
916 * by creating a zero-fill element. We do not mark the buffer
917 * dirty when creating a zero-fill element (the hammer2_chain_modify()
918 * API must still be used to do that).
920 * The device buffer is variable-sized in powers of 2 down
921 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
922 * chunk always contains buffers of the same size. (XXX)
924 * The minimum physical IO size may be larger than the variable
930 * The getblk() optimization can only be used on newly created
931 * elements if the physical block size matches the request.
933 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
934 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
937 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
939 adjreadcounter(&chain->bref, chain->bytes);
943 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
944 (intmax_t)bref->data_off, error);
945 hammer2_io_bqrelse(&chain->dio);
946 ccms_thread_lock_downgrade(&core->cst, ostate);
951 * We can clear the INITIAL state now, we've resolved the buffer
952 * to zeros and marked it dirty with hammer2_io_new().
954 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
955 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
956 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
960 * Setup the data pointer, either pointing it to an embedded data
961 * structure and copying the data from the buffer, or pointing it
964 * The buffer is not retained when copying to an embedded data
965 * structure in order to avoid potential deadlocks or recursions
966 * on the same physical buffer.
968 switch (bref->type) {
969 case HAMMER2_BREF_TYPE_VOLUME:
970 case HAMMER2_BREF_TYPE_FREEMAP:
972 * Copy data from bp to embedded buffer
974 panic("hammer2_chain_lock: called on unresolved volume header");
976 case HAMMER2_BREF_TYPE_INODE:
977 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
978 case HAMMER2_BREF_TYPE_INDIRECT:
979 case HAMMER2_BREF_TYPE_DATA:
980 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
983 * Point data at the device buffer and leave dio intact.
985 chain->data = (void *)bdata;
988 ccms_thread_lock_downgrade(&core->cst, ostate);
993 * This basically calls hammer2_io_breadcb() but does some pre-processing
994 * of the chain first to handle certain cases.
997 hammer2_chain_load_async(hammer2_chain_t *chain,
998 void (*callback)(hammer2_io_t *dio,
999 hammer2_chain_t *chain,
1000 void *arg_p, off_t arg_o),
1001 void *arg_p, off_t arg_o)
1003 hammer2_mount_t *hmp;
1004 struct hammer2_io *dio;
1005 hammer2_blockref_t *bref;
1009 callback(NULL, chain, arg_p, arg_o);
1014 * We must resolve to a device buffer, either by issuing I/O or
1015 * by creating a zero-fill element. We do not mark the buffer
1016 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1017 * API must still be used to do that).
1019 * The device buffer is variable-sized in powers of 2 down
1020 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1021 * chunk always contains buffers of the same size. (XXX)
1023 * The minimum physical IO size may be larger than the variable
1026 bref = &chain->bref;
1030 * The getblk() optimization can only be used on newly created
1031 * elements if the physical block size matches the request.
1033 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1034 chain->bytes == hammer2_devblksize(chain->bytes)) {
1035 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
1036 KKASSERT(error == 0);
1037 callback(dio, chain, arg_p, arg_o);
1042 * Otherwise issue a read
1044 adjreadcounter(&chain->bref, chain->bytes);
1045 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
1046 callback, chain, arg_p, arg_o);
1050 * Unlock and deref a chain element.
1052 * On the last lock release any non-embedded data (chain->dio) will be
1056 hammer2_chain_unlock(hammer2_chain_t *chain)
1058 hammer2_chain_core_t *core = chain->core;
1059 ccms_state_t ostate;
1064 * The core->cst lock can be shared across several chains so we
1065 * need to track the per-chain lockcnt separately.
1067 * If multiple locks are present (or being attempted) on this
1068 * particular chain we can just unlock, drop refs, and return.
1070 * Otherwise fall-through on the 1->0 transition.
1073 lockcnt = chain->lockcnt;
1074 KKASSERT(lockcnt > 0);
1077 if (atomic_cmpset_int(&chain->lockcnt,
1078 lockcnt, lockcnt - 1)) {
1079 ccms_thread_unlock(&core->cst);
1080 hammer2_chain_drop(chain);
1084 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1091 * On the 1->0 transition we upgrade the core lock (if necessary)
1092 * to exclusive for terminal processing. If after upgrading we find
1093 * that lockcnt is non-zero, another thread is racing us and will
1094 * handle the unload for us later on, so just cleanup and return
1095 * leaving the data/io intact
1097 * Otherwise if lockcnt is still 0 it is possible for it to become
1098 * non-zero and race, but since we hold the core->cst lock
1099 * exclusively all that will happen is that the chain will be
1100 * reloaded after we unload it.
1102 ostate = ccms_thread_lock_upgrade(&core->cst);
1103 if (chain->lockcnt) {
1104 ccms_thread_unlock_upgraded(&core->cst, ostate);
1105 hammer2_chain_drop(chain);
1110 * Shortcut the case if the data is embedded or not resolved.
1112 * Do NOT NULL out chain->data (e.g. inode data), it might be
1115 if (chain->dio == NULL) {
1116 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1117 hammer2_chain_drop_data(chain, 0);
1118 ccms_thread_unlock_upgraded(&core->cst, ostate);
1119 hammer2_chain_drop(chain);
1126 if (hammer2_io_isdirty(chain->dio) == 0) {
1128 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1129 switch(chain->bref.type) {
1130 case HAMMER2_BREF_TYPE_DATA:
1131 counterp = &hammer2_ioa_file_write;
1133 case HAMMER2_BREF_TYPE_INODE:
1134 counterp = &hammer2_ioa_meta_write;
1136 case HAMMER2_BREF_TYPE_INDIRECT:
1137 counterp = &hammer2_ioa_indr_write;
1139 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1140 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1141 counterp = &hammer2_ioa_fmap_write;
1144 counterp = &hammer2_ioa_volu_write;
1147 *counterp += chain->bytes;
1149 switch(chain->bref.type) {
1150 case HAMMER2_BREF_TYPE_DATA:
1151 counterp = &hammer2_iod_file_write;
1153 case HAMMER2_BREF_TYPE_INODE:
1154 counterp = &hammer2_iod_meta_write;
1156 case HAMMER2_BREF_TYPE_INDIRECT:
1157 counterp = &hammer2_iod_indr_write;
1159 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1160 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1161 counterp = &hammer2_iod_fmap_write;
1164 counterp = &hammer2_iod_volu_write;
1167 *counterp += chain->bytes;
1171 * Clean out the dio.
1173 * If a device buffer was used for data be sure to destroy the
1174 * buffer when we are done to avoid aliases (XXX what about the
1175 * underlying VM pages?).
1177 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1180 * NOTE: The isdirty check tracks whether we have to bdwrite() the
1181 * buffer or not. The buffer might already be dirty. The
1182 * flag is re-set when chain_modify() is called, even if
1183 * MODIFIED is already set, allowing the OS to retire the
1184 * buffer independent of a hammer2 flush.
1187 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
1188 hammer2_io_isdirty(chain->dio)) {
1189 hammer2_io_bawrite(&chain->dio);
1191 hammer2_io_bqrelse(&chain->dio);
1193 ccms_thread_unlock_upgraded(&core->cst, ostate);
1194 hammer2_chain_drop(chain);
1198 * This counts the number of live blockrefs in a block array and
1199 * also calculates the point at which all remaining blockrefs are empty.
1200 * This routine can only be called on a live chain (DUPLICATED flag not set).
1202 * NOTE: Flag is not set until after the count is complete, allowing
1203 * callers to test the flag without holding the spinlock.
1205 * NOTE: If base is NULL the related chain is still in the INITIAL
1206 * state and there are no blockrefs to count.
1208 * NOTE: live_count may already have some counts accumulated due to
1209 * creation and deletion and could even be initially negative.
1212 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1213 hammer2_blockref_t *base, int count)
1215 hammer2_chain_core_t *core = chain->core;
1217 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
1219 spin_lock(&core->cst.spin);
1220 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1222 while (--count >= 0) {
1223 if (base[count].type)
1226 core->live_zero = count + 1;
1227 while (count >= 0) {
1228 if (base[count].type)
1229 atomic_add_int(&core->live_count, 1);
1233 core->live_zero = 0;
1235 /* else do not modify live_count */
1236 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1238 spin_unlock(&core->cst.spin);
1242 * Resize the chain's physical storage allocation in-place. This may
1243 * replace the passed-in chain with a new chain.
1245 * Chains can be resized smaller without reallocating the storage.
1246 * Resizing larger will reallocate the storage.
1248 * Must be passed an exclusively locked parent and chain, returns a new
1249 * exclusively locked chain at the same index and unlocks the old chain.
1250 * Flushes the buffer if necessary.
1252 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1253 * to avoid instantiating a device buffer that conflicts with the vnode
1254 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1255 * any chain-oriented bp would be a device buffer.
1257 * XXX return error if cannot resize.
1260 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1261 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1262 int nradix, int flags)
1264 hammer2_mount_t *hmp;
1265 hammer2_chain_t *chain;
1273 * Only data and indirect blocks can be resized for now.
1274 * (The volu root, inodes, and freemap elements use a fixed size).
1276 KKASSERT(chain != &hmp->vchain);
1277 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1278 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1281 * Nothing to do if the element is already the proper size
1283 obytes = chain->bytes;
1284 nbytes = 1U << nradix;
1285 if (obytes == nbytes)
1289 * Delete the old chain and duplicate it at the same (parent, index),
1290 * returning a new chain. This allows the old chain to still be
1291 * used by the flush code. The new chain will be returned in a
1294 * The parent does not have to be locked for the delete/duplicate call,
1295 * but is in this particular code path.
1297 * NOTE: If we are not crossing a synchronization point the
1298 * duplication code will simply reuse the existing chain
1301 hammer2_chain_delete_duplicate(trans, &chain, 0);
1304 * Relocate the block, even if making it smaller (because different
1305 * block sizes may be in different regions).
1307 hammer2_freemap_alloc(trans, chain, nbytes);
1308 chain->bytes = nbytes;
1309 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1310 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1313 * For now just support it on DATA chains (and not on indirect
1316 KKASSERT(chain->dio == NULL);
1320 * Make sure the chain is marked MOVED and propagate the update
1321 * to the root for flush.
1323 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1324 hammer2_chain_ref(chain);
1325 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1327 hammer2_chain_setsubmod(trans, chain);
1333 * Set a chain modified, making it read-write and duplicating it if necessary.
1334 * This function will assign a new physical block to the chain if necessary
1336 * Duplication of already-modified chains is possible when the modification
1337 * crosses a flush synchronization boundary.
1339 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1340 * level or the COW operation will not work.
1342 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1343 * run the data through the device buffers.
1345 * This function may return a different chain than was passed, in which case
1346 * the old chain will be unlocked and the new chain will be locked.
1348 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1350 hammer2_inode_data_t *
1351 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1352 hammer2_chain_t **chainp, int flags)
1354 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1355 hammer2_chain_modify(trans, chainp, flags);
1356 if (ip->chain != *chainp)
1357 hammer2_inode_repoint(ip, NULL, *chainp);
1359 vsetisdirty(ip->vp);
1360 return(&ip->chain->data->ipdata);
1364 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1367 hammer2_mount_t *hmp;
1368 hammer2_chain_t *chain;
1377 KKASSERT(chain->bref.mirror_tid != trans->sync_tid ||
1378 (chain->flags & HAMMER2_CHAIN_MODIFIED));
1381 * data is not optional for freemap chains (we must always be sure
1382 * to copy the data on COW storage allocations).
1384 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1385 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1386 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1387 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1391 * Determine if a delete-duplicate is needed.
1393 * (a) Modify_tid is part of a prior flush
1394 * (b) Transaction is concurrent with a flush (has higher tid)
1395 * (c) and chain is not in the initial state (freshly created)
1396 * (d) and caller didn't request an in-place modification.
1398 * The freemap and volume header special chains are never D-Dd.
1400 if (chain->modify_tid != trans->sync_tid && /* cross boundary */
1401 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1402 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1403 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1404 hammer2_chain_delete_duplicate(trans, chainp, 0);
1409 * Fall through if fchain or vchain, clearing the CHAIN_FLUSHED
1410 * flag. Basically other chains are delete-duplicated and so
1411 * the duplicated chains of course will not have the FLUSHED
1412 * flag set, but fchain and vchain are special-cased and the
1413 * flag must be cleared when changing modify_tid.
1415 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FLUSHED);
1419 * Data must be resolved if already assigned unless explicitly
1420 * flagged otherwise.
1422 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1423 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1424 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1425 hammer2_chain_unlock(chain);
1429 * Otherwise do initial-chain handling
1431 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1432 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1433 hammer2_chain_ref(chain);
1434 hammer2_chain_memory_inc(chain->pmp);
1437 /* shouldn't be needed */
1438 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1439 hammer2_chain_ref(chain);
1440 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1445 * The modification or re-modification requires an allocation and
1448 * We normally always allocate new storage here. If storage exists
1449 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1451 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1452 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1453 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1454 chain->modify_tid != trans->sync_tid)
1456 hammer2_freemap_alloc(trans, chain, chain->bytes);
1457 /* XXX failed allocation */
1458 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1459 hammer2_freemap_alloc(trans, chain, chain->bytes);
1460 /* XXX failed allocation */
1462 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1466 * Update modify_tid. XXX special-case vchain/fchain because they
1467 * are always modified in-place. Otherwise the chain being modified
1468 * must not be part of a future transaction.
1470 if (chain == &hmp->vchain || chain == &hmp->fchain) {
1471 if (chain->modify_tid <= trans->sync_tid)
1472 chain->modify_tid = trans->sync_tid;
1474 KKASSERT(chain->modify_tid <= trans->sync_tid);
1475 chain->modify_tid = trans->sync_tid;
1478 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1479 chain->bref.modify_tid = trans->sync_tid;
1482 * Do not COW BREF_TYPE_DATA when OPTDATA is set. This is because
1483 * data modifications are done via the logical buffer cache so COWing
1484 * it here would result in unnecessary extra copies (and possibly extra
1485 * block reallocations). The INITIAL flag remains unchanged in this
1488 * (This is a bit of a hack).
1490 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1491 (flags & HAMMER2_MODIFY_OPTDATA)) {
1496 * Clearing the INITIAL flag (for indirect blocks) indicates that
1497 * we've processed the uninitialized storage allocation.
1499 * If this flag is already clear we are likely in a copy-on-write
1500 * situation but we have to be sure NOT to bzero the storage if
1501 * no data is present.
1503 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1504 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1511 * Instantiate data buffer and possibly execute COW operation
1513 switch(chain->bref.type) {
1514 case HAMMER2_BREF_TYPE_VOLUME:
1515 case HAMMER2_BREF_TYPE_FREEMAP:
1517 * The data is embedded, no copy-on-write operation is
1520 KKASSERT(chain->dio == NULL);
1522 case HAMMER2_BREF_TYPE_INODE:
1523 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1524 case HAMMER2_BREF_TYPE_DATA:
1525 case HAMMER2_BREF_TYPE_INDIRECT:
1526 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1528 * Perform the copy-on-write operation
1530 * zero-fill or copy-on-write depending on whether
1531 * chain->data exists or not and set the dirty state for
1532 * the new buffer. hammer2_io_new() will handle the
1535 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1538 error = hammer2_io_new(hmp, chain->bref.data_off,
1539 chain->bytes, &dio);
1541 error = hammer2_io_bread(hmp, chain->bref.data_off,
1542 chain->bytes, &dio);
1544 adjreadcounter(&chain->bref, chain->bytes);
1545 KKASSERT(error == 0);
1547 bdata = hammer2_io_data(dio, chain->bref.data_off);
1550 KKASSERT(chain->dio != NULL);
1551 if (chain->data != (void *)bdata) {
1552 bcopy(chain->data, bdata, chain->bytes);
1554 } else if (wasinitial == 0) {
1556 * We have a problem. We were asked to COW but
1557 * we don't have any data to COW with!
1559 panic("hammer2_chain_modify: having a COW %p\n",
1564 * Retire the old buffer, replace with the new
1567 hammer2_io_brelse(&chain->dio);
1568 chain->data = (void *)bdata;
1570 hammer2_io_setdirty(dio); /* modified by bcopy above */
1573 panic("hammer2_chain_modify: illegal non-embedded type %d",
1579 hammer2_chain_setsubmod(trans, chain);
1583 * Mark the volume as having been modified. This short-cut version
1584 * does not have to lock the volume's chain, which allows the ioctl
1585 * code to make adjustments to connections without deadlocking. XXX
1587 * No ref is made on vchain when flagging it MODIFIED.
1590 hammer2_modify_volume(hammer2_mount_t *hmp)
1592 hammer2_voldata_lock(hmp);
1593 hammer2_voldata_unlock(hmp, 1);
1597 * This function returns the chain at the nearest key within the specified
1598 * range with the highest delete_tid. The core spinlock must be held on
1599 * call and the returned chain will be referenced but not locked.
1601 * The returned chain may or may not be in a deleted state. Note that
1602 * live chains have a delete_tid = MAX_TID.
1604 * This function will recurse through chain->rbtree as necessary and will
1605 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1606 * the iteration value is less than the current value of *key_nextp.
1608 * The caller should use (*key_nextp) to calculate the actual range of
1609 * the returned element, which will be (key_beg to *key_nextp - 1), because
1610 * there might be another element which is superior to the returned element
1613 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1614 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1615 * it will wind up being (key_end + 1).
1617 struct hammer2_chain_find_info {
1618 hammer2_chain_t *best;
1619 hammer2_key_t key_beg;
1620 hammer2_key_t key_end;
1621 hammer2_key_t key_next;
1624 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1625 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1628 * DEBUGGING - Assert that the chain will not collide.
1632 hammer2_chain_assert_not_present(hammer2_chain_core_t *core,
1633 hammer2_chain_t *chain)
1635 struct hammer2_chain_find_info info;
1636 hammer2_chain_layer_t *layer;
1638 if (chain->flags & HAMMER2_CHAIN_DELETED)
1642 info.key_beg = chain->bref.key;
1643 info.key_end = chain->bref.key +
1644 ((hammer2_key_t)1 << chain->bref.keybits) - 1;
1645 info.key_next = HAMMER2_MAX_KEY;
1647 TAILQ_FOREACH(layer, &core->layerq, entry) {
1648 KKASSERT(layer->good == 0xABCD);
1649 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1650 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1653 if (info.best && (info.best->flags & HAMMER2_CHAIN_DELETED) == 0)
1654 panic("hammer2_chain_assert_not_present: %p/%p\n",
1660 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1661 hammer2_key_t key_beg, hammer2_key_t key_end)
1663 struct hammer2_chain_find_info info;
1664 hammer2_chain_layer_t *layer;
1667 info.key_beg = key_beg;
1668 info.key_end = key_end;
1669 info.key_next = *key_nextp;
1671 KKASSERT(parent->core->good == 0x1234);
1672 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1673 KKASSERT(layer->good == 0xABCD);
1674 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1675 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1678 *key_nextp = info.key_next;
1680 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1681 parent, key_beg, key_end, *key_nextp);
1689 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1691 struct hammer2_chain_find_info *info = data;
1692 hammer2_key_t child_beg;
1693 hammer2_key_t child_end;
1695 child_beg = child->bref.key;
1696 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1698 if (child_end < info->key_beg)
1700 if (child_beg > info->key_end)
1707 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1709 struct hammer2_chain_find_info *info = data;
1710 hammer2_chain_t *best;
1711 hammer2_key_t child_end;
1714 * WARNING! Do not discard DUPLICATED chains, it is possible that
1715 * we are catching an insertion half-way done. If a
1716 * duplicated chain turns out to be the best choice the
1717 * caller will re-check its flags after locking it.
1719 * WARNING! Layerq is scanned forwards, exact matches should keep
1720 * the existing info->best.
1722 if ((best = info->best) == NULL) {
1724 * No previous best. Assign best
1727 } else if (best->bref.key <= info->key_beg &&
1728 child->bref.key <= info->key_beg) {
1730 * If our current best is flush with key_beg and child is
1731 * also flush with key_beg choose based on delete_tid.
1733 * key_next will automatically be limited to the smaller of
1734 * the two end-points.
1736 if (child->delete_tid > best->delete_tid)
1738 } else if (child->bref.key < best->bref.key) {
1740 * Child has a nearer key and best is not flush with key_beg.
1741 * Truncate key_next to the old best key iff it had a better
1745 if (best->delete_tid >= child->delete_tid &&
1746 (info->key_next > best->bref.key || info->key_next == 0))
1747 info->key_next = best->bref.key;
1748 } else if (child->bref.key == best->bref.key) {
1750 * If our current best is flush with the child then choose
1751 * based on delete_tid.
1753 * key_next will automatically be limited to the smaller of
1754 * the two end-points.
1756 if (child->delete_tid > best->delete_tid)
1760 * Keep the current best but truncate key_next to the child's
1761 * base iff the child has a higher delete_tid.
1763 * key_next will also automatically be limited to the smaller
1764 * of the two end-points (probably not necessary for this case
1765 * but we do it anyway).
1767 if (child->delete_tid >= best->delete_tid &&
1768 (info->key_next > child->bref.key || info->key_next == 0))
1769 info->key_next = child->bref.key;
1773 * Always truncate key_next based on child's end-of-range.
1775 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1776 if (child_end && (info->key_next > child_end || info->key_next == 0))
1777 info->key_next = child_end;
1783 * Retrieve the specified chain from a media blockref, creating the
1784 * in-memory chain structure which reflects it. modify_tid will be
1785 * left 0 which forces any modifications to issue a delete-duplicate.
1787 * To handle insertion races pass the INSERT_RACE flag along with the
1788 * generation number of the core. NULL will be returned if the generation
1789 * number changes before we have a chance to insert the chain. Insert
1790 * races can occur because the parent might be held shared.
1792 * Caller must hold the parent locked shared or exclusive since we may
1793 * need the parent's bref array to find our block.
1796 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref,
1799 hammer2_mount_t *hmp = parent->hmp;
1800 hammer2_chain_core_t *above = parent->core;
1801 hammer2_chain_t *chain;
1805 * Allocate a chain structure representing the existing media
1806 * entry. Resulting chain has one ref and is not locked.
1808 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1809 hammer2_chain_core_alloc(NULL, chain, NULL);
1810 /* ref'd chain returned */
1811 chain->modify_tid = chain->bref.mirror_tid;
1814 * Link the chain into its parent. A spinlock is required to safely
1815 * access the RBTREE, and it is possible to collide with another
1816 * hammer2_chain_get() operation because the caller might only hold
1817 * a shared lock on the parent.
1819 KKASSERT(parent->refs > 0);
1820 error = hammer2_chain_insert(above, NULL, chain,
1821 HAMMER2_CHAIN_INSERT_SPIN |
1822 HAMMER2_CHAIN_INSERT_RACE,
1825 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1826 kprintf("chain %p get race\n", chain);
1827 hammer2_chain_drop(chain);
1830 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1834 * Return our new chain referenced but not locked, or NULL if
1841 * Lookup initialization/completion API
1844 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1846 if (flags & HAMMER2_LOOKUP_SHARED) {
1847 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1848 HAMMER2_RESOLVE_SHARED);
1850 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1856 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1859 hammer2_chain_unlock(parent);
1864 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1866 hammer2_chain_t *oparent;
1867 hammer2_chain_t *bparent;
1868 hammer2_chain_t *nparent;
1869 hammer2_chain_core_t *above;
1872 above = oparent->above;
1874 spin_lock(&above->cst.spin);
1875 bparent = TAILQ_FIRST(&above->ownerq);
1876 hammer2_chain_ref(bparent);
1879 * Be careful of order, oparent must be unlocked before nparent
1880 * is locked below to avoid a deadlock. We might as well delay its
1881 * unlocking until we conveniently no longer have the spinlock (instead
1882 * of cycling the spinlock).
1884 * Theoretically our ref on bparent should prevent elements of the
1885 * following chain from going away and prevent above from going away,
1886 * but we still need the spinlock to safely scan the list.
1890 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1891 nparent = TAILQ_NEXT(nparent, core_entry);
1892 hammer2_chain_ref(nparent);
1893 spin_unlock(&above->cst.spin);
1896 hammer2_chain_unlock(oparent);
1899 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1900 hammer2_chain_drop(bparent);
1903 * We might have raced a delete-duplicate.
1905 if ((nparent->flags & HAMMER2_CHAIN_DUPLICATED) == 0)
1908 hammer2_chain_ref(bparent);
1909 hammer2_chain_unlock(nparent);
1910 spin_lock(&above->cst.spin);
1919 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1920 * (*parentp) typically points to an inode but can also point to a related
1921 * indirect block and this function will recurse upwards and find the inode
1924 * (*parentp) must be exclusively locked and referenced and can be an inode
1925 * or an existing indirect block within the inode.
1927 * On return (*parentp) will be modified to point at the deepest parent chain
1928 * element encountered during the search, as a helper for an insertion or
1929 * deletion. The new (*parentp) will be locked and referenced and the old
1930 * will be unlocked and dereferenced (no change if they are both the same).
1932 * The matching chain will be returned exclusively locked. If NOLOCK is
1933 * requested the chain will be returned only referenced.
1935 * NULL is returned if no match was found, but (*parentp) will still
1936 * potentially be adjusted.
1938 * On return (*key_nextp) will point to an iterative value for key_beg.
1939 * (If NULL is returned (*key_nextp) is set to key_end).
1941 * This function will also recurse up the chain if the key is not within the
1942 * current parent's range. (*parentp) can never be set to NULL. An iteration
1943 * can simply allow (*parentp) to float inside the loop.
1945 * NOTE! chain->data is not always resolved. By default it will not be
1946 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1947 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1948 * BREF_TYPE_DATA as the device buffer can alias the logical file
1952 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1953 hammer2_key_t key_beg, hammer2_key_t key_end,
1954 int *cache_indexp, int flags)
1956 hammer2_mount_t *hmp;
1957 hammer2_chain_t *parent;
1958 hammer2_chain_t *chain;
1959 hammer2_blockref_t *base;
1960 hammer2_blockref_t *bref;
1961 hammer2_blockref_t bcopy;
1962 hammer2_key_t scan_beg;
1963 hammer2_key_t scan_end;
1964 hammer2_chain_core_t *above;
1966 int how_always = HAMMER2_RESOLVE_ALWAYS;
1967 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1970 int maxloops = 300000;
1972 hammer2_chain_t * volatile xxchain = NULL;
1973 volatile int xxchainwhy;
1975 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1976 how_maybe = how_always;
1977 how = HAMMER2_RESOLVE_ALWAYS;
1978 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1979 how = HAMMER2_RESOLVE_NEVER;
1981 how = HAMMER2_RESOLVE_MAYBE;
1983 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1984 how_maybe |= HAMMER2_RESOLVE_SHARED;
1985 how_always |= HAMMER2_RESOLVE_SHARED;
1986 how |= HAMMER2_RESOLVE_SHARED;
1990 * Recurse (*parentp) upward if necessary until the parent completely
1991 * encloses the key range or we hit the inode.
1993 * This function handles races against the flusher doing a delete-
1994 * duplicate above us and re-homes the parent to the duplicate in
1995 * that case, otherwise we'd wind up recursing down a stale chain.
2000 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2001 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2002 scan_beg = parent->bref.key;
2003 scan_end = scan_beg +
2004 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2005 if (key_beg >= scan_beg && key_end <= scan_end)
2007 parent = hammer2_chain_getparent(parentp, how_maybe);
2011 if (--maxloops == 0)
2012 panic("hammer2_chain_lookup: maxloops");
2014 * Locate the blockref array. Currently we do a fully associative
2015 * search through the array.
2017 switch(parent->bref.type) {
2018 case HAMMER2_BREF_TYPE_INODE:
2020 * Special shortcut for embedded data returns the inode
2021 * itself. Callers must detect this condition and access
2022 * the embedded data (the strategy code does this for us).
2024 * This is only applicable to regular files and softlinks.
2026 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2027 if (flags & HAMMER2_LOOKUP_NOLOCK)
2028 hammer2_chain_ref(parent);
2030 hammer2_chain_lock(parent, how_always);
2031 *key_nextp = key_end + 1;
2034 base = &parent->data->ipdata.u.blockset.blockref[0];
2035 count = HAMMER2_SET_COUNT;
2037 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2038 case HAMMER2_BREF_TYPE_INDIRECT:
2040 * Handle MATCHIND on the parent
2042 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2043 scan_beg = parent->bref.key;
2044 scan_end = scan_beg +
2045 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2046 if (key_beg == scan_beg && key_end == scan_end) {
2048 hammer2_chain_lock(chain, how_maybe);
2049 *key_nextp = scan_end + 1;
2054 * Optimize indirect blocks in the INITIAL state to avoid
2057 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2060 if (parent->data == NULL)
2061 panic("parent->data is NULL");
2062 base = &parent->data->npdata[0];
2064 count = parent->bytes / sizeof(hammer2_blockref_t);
2066 case HAMMER2_BREF_TYPE_VOLUME:
2067 base = &hmp->voldata.sroot_blockset.blockref[0];
2068 count = HAMMER2_SET_COUNT;
2070 case HAMMER2_BREF_TYPE_FREEMAP:
2071 base = &hmp->voldata.freemap_blockset.blockref[0];
2072 count = HAMMER2_SET_COUNT;
2075 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2077 base = NULL; /* safety */
2078 count = 0; /* safety */
2082 * Merged scan to find next candidate.
2084 * hammer2_base_*() functions require the above->live_* fields
2085 * to be synchronized.
2087 * We need to hold the spinlock to access the block array and RB tree
2088 * and to interlock chain creation.
2090 above = parent->core;
2091 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2092 hammer2_chain_countbrefs(parent, base, count);
2097 spin_lock(&above->cst.spin);
2098 chain = hammer2_combined_find(parent, base, count,
2099 cache_indexp, key_nextp,
2100 key_beg, key_end, &bref);
2101 generation = above->generation;
2104 * Exhausted parent chain, iterate.
2107 spin_unlock(&above->cst.spin);
2108 if (key_beg == key_end) /* short cut single-key case */
2110 return (hammer2_chain_next(parentp, NULL, key_nextp,
2112 cache_indexp, flags));
2116 * Selected from blockref or in-memory chain.
2118 if (chain == NULL) {
2120 spin_unlock(&above->cst.spin);
2121 chain = hammer2_chain_get(parent, &bcopy, generation);
2122 if (chain == NULL) {
2123 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2124 parent, key_beg, key_end);
2127 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2130 hammer2_chain_drop(chain);
2135 hammer2_chain_ref(chain);
2136 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2137 spin_unlock(&above->cst.spin);
2141 * chain is referenced but not locked. We must lock the chain
2142 * to obtain definitive DUPLICATED/DELETED state
2144 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2145 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2146 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2148 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2152 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2154 * NOTE: Chain's key range is not relevant as there might be
2155 * one-offs within the range that are not deleted.
2157 * NOTE: Lookups can race delete-duplicate because
2158 * delete-duplicate does not lock the parent's core
2159 * (they just use the spinlock on the core). We must
2160 * check for races by comparing the DUPLICATED flag before
2161 * releasing the spinlock with the flag after locking the
2164 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2165 hammer2_chain_unlock(chain);
2166 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2167 key_beg = *key_nextp;
2168 if (key_beg == 0 || key_beg > key_end)
2177 * If the chain element is an indirect block it becomes the new
2178 * parent and we loop on it. We must maintain our top-down locks
2179 * to prevent the flusher from interfering (i.e. doing a
2180 * delete-duplicate and leaving us recursing down a deleted chain).
2182 * The parent always has to be locked with at least RESOLVE_MAYBE
2183 * so we can access its data. It might need a fixup if the caller
2184 * passed incompatible flags. Be careful not to cause a deadlock
2185 * as a data-load requires an exclusive lock.
2187 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2188 * range is within the requested key range we return the indirect
2189 * block and do NOT loop. This is usually only used to acquire
2192 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2193 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2194 hammer2_chain_unlock(parent);
2195 *parentp = parent = chain;
2202 * All done, return the chain
2205 XXChainWhy = xxchainwhy;
2210 * After having issued a lookup we can iterate all matching keys.
2212 * If chain is non-NULL we continue the iteration from just after it's index.
2214 * If chain is NULL we assume the parent was exhausted and continue the
2215 * iteration at the next parent.
2217 * parent must be locked on entry and remains locked throughout. chain's
2218 * lock status must match flags. Chain is always at least referenced.
2220 * WARNING! The MATCHIND flag does not apply to this function.
2223 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2224 hammer2_key_t *key_nextp,
2225 hammer2_key_t key_beg, hammer2_key_t key_end,
2226 int *cache_indexp, int flags)
2228 hammer2_chain_t *parent;
2232 * Calculate locking flags for upward recursion.
2234 how_maybe = HAMMER2_RESOLVE_MAYBE;
2235 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2236 how_maybe |= HAMMER2_RESOLVE_SHARED;
2241 * Calculate the next index and recalculate the parent if necessary.
2244 key_beg = chain->bref.key +
2245 ((hammer2_key_t)1 << chain->bref.keybits);
2246 if (flags & HAMMER2_LOOKUP_NOLOCK)
2247 hammer2_chain_drop(chain);
2249 hammer2_chain_unlock(chain);
2252 * Any scan where the lookup returned degenerate data embedded
2253 * in the inode has an invalid index and must terminate.
2255 if (chain == parent)
2257 if (key_beg == 0 || key_beg > key_end)
2260 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2261 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2263 * We reached the end of the iteration.
2268 * Continue iteration with next parent unless the current
2269 * parent covers the range.
2271 key_beg = parent->bref.key +
2272 ((hammer2_key_t)1 << parent->bref.keybits);
2273 if (key_beg == 0 || key_beg > key_end)
2275 parent = hammer2_chain_getparent(parentp, how_maybe);
2281 return (hammer2_chain_lookup(parentp, key_nextp,
2283 cache_indexp, flags));
2287 * Raw scan functions are similar to lookup/next but do not seek the parent
2288 * chain and do not skip stale chains. These functions are primarily used
2289 * by the recovery code.
2291 * Parent and chain are locked, parent's data must be resolved. To acquire
2292 * the first sub-chain under parent pass chain == NULL.
2295 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2296 int *cache_indexp, int flags)
2298 hammer2_mount_t *hmp;
2299 hammer2_blockref_t *base;
2300 hammer2_blockref_t *bref;
2301 hammer2_blockref_t bcopy;
2302 hammer2_chain_core_t *above;
2304 hammer2_key_t next_key;
2306 int how_always = HAMMER2_RESOLVE_ALWAYS;
2307 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2310 int maxloops = 300000;
2316 * Scan flags borrowed from lookup
2318 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2319 how_maybe = how_always;
2320 how = HAMMER2_RESOLVE_ALWAYS;
2321 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2322 how = HAMMER2_RESOLVE_NEVER;
2324 how = HAMMER2_RESOLVE_MAYBE;
2326 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2327 how_maybe |= HAMMER2_RESOLVE_SHARED;
2328 how_always |= HAMMER2_RESOLVE_SHARED;
2329 how |= HAMMER2_RESOLVE_SHARED;
2333 * Calculate key to locate first/next element, unlocking the previous
2334 * element as we go. Be careful, the key calculation can overflow.
2337 key = chain->bref.key +
2338 ((hammer2_key_t)1 << chain->bref.keybits);
2339 hammer2_chain_unlock(chain);
2348 if (--maxloops == 0)
2349 panic("hammer2_chain_scan: maxloops");
2351 * Locate the blockref array. Currently we do a fully associative
2352 * search through the array.
2354 switch(parent->bref.type) {
2355 case HAMMER2_BREF_TYPE_INODE:
2357 * An inode with embedded data has no sub-chains.
2359 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2361 base = &parent->data->ipdata.u.blockset.blockref[0];
2362 count = HAMMER2_SET_COUNT;
2364 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2365 case HAMMER2_BREF_TYPE_INDIRECT:
2367 * Optimize indirect blocks in the INITIAL state to avoid
2370 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2373 if (parent->data == NULL)
2374 panic("parent->data is NULL");
2375 base = &parent->data->npdata[0];
2377 count = parent->bytes / sizeof(hammer2_blockref_t);
2379 case HAMMER2_BREF_TYPE_VOLUME:
2380 base = &hmp->voldata.sroot_blockset.blockref[0];
2381 count = HAMMER2_SET_COUNT;
2383 case HAMMER2_BREF_TYPE_FREEMAP:
2384 base = &hmp->voldata.freemap_blockset.blockref[0];
2385 count = HAMMER2_SET_COUNT;
2388 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2390 base = NULL; /* safety */
2391 count = 0; /* safety */
2395 * Merged scan to find next candidate.
2397 * hammer2_base_*() functions require the above->live_* fields
2398 * to be synchronized.
2400 * We need to hold the spinlock to access the block array and RB tree
2401 * and to interlock chain creation.
2403 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2404 hammer2_chain_countbrefs(parent, base, count);
2406 above = parent->core;
2408 spin_lock(&above->cst.spin);
2409 chain = hammer2_combined_find(parent, base, count,
2410 cache_indexp, &next_key,
2411 key, HAMMER2_MAX_KEY, &bref);
2412 generation = above->generation;
2415 * Exhausted parent chain, we're done.
2418 spin_unlock(&above->cst.spin);
2419 KKASSERT(chain == NULL);
2424 * Selected from blockref or in-memory chain.
2426 if (chain == NULL) {
2428 spin_unlock(&above->cst.spin);
2429 chain = hammer2_chain_get(parent, &bcopy, generation);
2430 if (chain == NULL) {
2431 kprintf("retry scan parent %p keys %016jx\n",
2435 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2436 hammer2_chain_drop(chain);
2442 hammer2_chain_ref(chain);
2443 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2444 spin_unlock(&above->cst.spin);
2448 * chain is referenced but not locked. We must lock the chain
2449 * to obtain definitive DUPLICATED/DELETED state
2451 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2454 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2456 * NOTE: chain's key range is not relevant as there might be
2457 * one-offs within the range that are not deleted.
2459 * NOTE: XXX this could create problems with scans used in
2460 * situations other than mount-time recovery.
2462 * NOTE: Lookups can race delete-duplicate because
2463 * delete-duplicate does not lock the parent's core
2464 * (they just use the spinlock on the core). We must
2465 * check for races by comparing the DUPLICATED flag before
2466 * releasing the spinlock with the flag after locking the
2469 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2470 hammer2_chain_unlock(chain);
2473 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2483 * All done, return the chain or NULL
2489 * Create and return a new hammer2 system memory structure of the specified
2490 * key, type and size and insert it under (*parentp). This is a full
2491 * insertion, based on the supplied key/keybits, and may involve creating
2492 * indirect blocks and moving other chains around via delete/duplicate.
2494 * (*parentp) must be exclusive locked and may be replaced on return
2495 * depending on how much work the function had to do.
2497 * (*chainp) usually starts out NULL and returns the newly created chain,
2498 * but if the caller desires the caller may allocate a disconnected chain
2499 * and pass it in instead. (It is also possible for the caller to use
2500 * chain_duplicate() to create a disconnected chain, manipulate it, then
2501 * pass it into this function to insert it).
2503 * This function should NOT be used to insert INDIRECT blocks. It is
2504 * typically used to create/insert inodes and data blocks.
2506 * Caller must pass-in an exclusively locked parent the new chain is to
2507 * be inserted under, and optionally pass-in a disconnected, exclusively
2508 * locked chain to insert (else we create a new chain). The function will
2509 * adjust (*parentp) as necessary, create or connect the chain, and
2510 * return an exclusively locked chain in *chainp.
2513 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2514 hammer2_chain_t **chainp,
2515 hammer2_key_t key, int keybits, int type, size_t bytes)
2517 hammer2_mount_t *hmp;
2518 hammer2_chain_t *chain;
2519 hammer2_chain_t *parent = *parentp;
2520 hammer2_chain_core_t *above;
2521 hammer2_blockref_t *base;
2522 hammer2_blockref_t dummy;
2526 int maxloops = 300000;
2528 above = parent->core;
2529 KKASSERT(ccms_thread_lock_owned(&above->cst));
2533 if (chain == NULL) {
2535 * First allocate media space and construct the dummy bref,
2536 * then allocate the in-memory chain structure. Set the
2537 * INITIAL flag for fresh chains which do not have embedded
2540 bzero(&dummy, sizeof(dummy));
2543 dummy.keybits = keybits;
2544 dummy.data_off = hammer2_getradix(bytes);
2545 dummy.methods = parent->bref.methods;
2546 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2547 hammer2_chain_core_alloc(trans, chain, NULL);
2550 * Lock the chain manually, chain_lock will load the chain
2551 * which we do NOT want to do. (note: chain->refs is set
2552 * to 1 by chain_alloc() for us, but lockcnt is not).
2555 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2559 * We do NOT set INITIAL here (yet). INITIAL is only
2560 * used for indirect blocks.
2562 * Recalculate bytes to reflect the actual media block
2565 bytes = (hammer2_off_t)1 <<
2566 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2567 chain->bytes = bytes;
2570 case HAMMER2_BREF_TYPE_VOLUME:
2571 case HAMMER2_BREF_TYPE_FREEMAP:
2572 panic("hammer2_chain_create: called with volume type");
2574 case HAMMER2_BREF_TYPE_INDIRECT:
2575 panic("hammer2_chain_create: cannot be used to"
2576 "create indirect block");
2578 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2579 panic("hammer2_chain_create: cannot be used to"
2580 "create freemap root or node");
2582 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2583 KKASSERT(bytes == sizeof(chain->data->bmdata));
2585 case HAMMER2_BREF_TYPE_INODE:
2586 case HAMMER2_BREF_TYPE_DATA:
2589 * leave chain->data NULL, set INITIAL
2591 KKASSERT(chain->data == NULL);
2592 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2597 * We are reattaching a chain that has been duplicated and
2598 * left disconnected under a DIFFERENT parent with potentially
2599 * different key/keybits.
2601 * The chain must be modified in the current transaction
2602 * (the duplication code should have done that for us),
2603 * and it's modify_tid should be greater than the parent's
2604 * bref.mirror_tid. This should cause it to be created under
2607 * If deleted in the same transaction, the create/delete TIDs
2608 * will be the same and effective the chain will not have
2609 * existed at all from the point of view of the parent.
2611 * Do NOT mess with the current state of the INITIAL flag.
2613 KKASSERT(chain->modify_tid > parent->bref.mirror_tid);
2614 KKASSERT(chain->modify_tid == trans->sync_tid);
2615 chain->bref.key = key;
2616 chain->bref.keybits = keybits;
2617 /* chain->modify_tid = chain->bref.mirror_tid; */
2618 KKASSERT(chain->above == NULL);
2622 * Calculate how many entries we have in the blockref array and
2623 * determine if an indirect block is required.
2626 if (--maxloops == 0)
2627 panic("hammer2_chain_create: maxloops");
2628 above = parent->core;
2630 switch(parent->bref.type) {
2631 case HAMMER2_BREF_TYPE_INODE:
2632 KKASSERT((parent->data->ipdata.op_flags &
2633 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2634 KKASSERT(parent->data != NULL);
2635 base = &parent->data->ipdata.u.blockset.blockref[0];
2636 count = HAMMER2_SET_COUNT;
2638 case HAMMER2_BREF_TYPE_INDIRECT:
2639 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2640 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2643 base = &parent->data->npdata[0];
2644 count = parent->bytes / sizeof(hammer2_blockref_t);
2646 case HAMMER2_BREF_TYPE_VOLUME:
2647 KKASSERT(parent->data != NULL);
2648 base = &hmp->voldata.sroot_blockset.blockref[0];
2649 count = HAMMER2_SET_COUNT;
2651 case HAMMER2_BREF_TYPE_FREEMAP:
2652 KKASSERT(parent->data != NULL);
2653 base = &hmp->voldata.freemap_blockset.blockref[0];
2654 count = HAMMER2_SET_COUNT;
2657 panic("hammer2_chain_create: unrecognized blockref type: %d",
2665 * Make sure we've counted the brefs
2667 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2668 hammer2_chain_countbrefs(parent, base, count);
2670 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2673 * If no free blockref could be found we must create an indirect
2674 * block and move a number of blockrefs into it. With the parent
2675 * locked we can safely lock each child in order to delete+duplicate
2676 * it without causing a deadlock.
2678 * This may return the new indirect block or the old parent depending
2679 * on where the key falls. NULL is returned on error.
2681 if (above->live_count == count) {
2682 hammer2_chain_t *nparent;
2684 nparent = hammer2_chain_create_indirect(trans, parent,
2687 if (nparent == NULL) {
2689 hammer2_chain_drop(chain);
2693 if (parent != nparent) {
2694 hammer2_chain_unlock(parent);
2695 parent = *parentp = nparent;
2701 * Link the chain into its parent. Later on we will have to set
2702 * the MOVED bit in situations where we don't mark the new chain
2703 * as being modified.
2705 if (chain->above != NULL)
2706 panic("hammer2: hammer2_chain_create: chain already connected");
2707 KKASSERT(chain->above == NULL);
2708 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2709 hammer2_chain_insert(above, NULL, chain,
2710 HAMMER2_CHAIN_INSERT_SPIN |
2711 HAMMER2_CHAIN_INSERT_LIVE,
2716 * Mark the newly created chain modified.
2718 * Device buffers are not instantiated for DATA elements
2719 * as these are handled by logical buffers.
2721 * Indirect and freemap node indirect blocks are handled
2722 * by hammer2_chain_create_indirect() and not by this
2725 * Data for all other bref types is expected to be
2726 * instantiated (INODE, LEAF).
2728 switch(chain->bref.type) {
2729 case HAMMER2_BREF_TYPE_DATA:
2730 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2731 case HAMMER2_BREF_TYPE_INODE:
2732 hammer2_chain_modify(trans, &chain,
2733 HAMMER2_MODIFY_OPTDATA |
2734 HAMMER2_MODIFY_ASSERTNOCOPY);
2738 * Remaining types are not supported by this function.
2739 * In particular, INDIRECT and LEAF_NODE types are
2740 * handled by create_indirect().
2742 panic("hammer2_chain_create: bad type: %d",
2749 * When reconnecting a chain we must set MOVED and setsubmod
2750 * so the flush recognizes that it must update the bref in
2753 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2754 hammer2_chain_ref(chain);
2755 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2758 hammer2_chain_setsubmod(trans, chain);
2767 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2768 * the same core and media state as the orignal. The original *chainp is
2769 * unlocked and the replacement will be returned locked.
2771 * The old chain must be in a DELETED state unless snapshot is non-zero.
2773 * The new chain will be live (i.e. not deleted), and modified.
2775 * If (parent) is non-NULL then the new duplicated chain is inserted under
2778 * If (parent) is NULL then the newly duplicated chain is not inserted
2779 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2780 * passing into hammer2_chain_create() after this function returns).
2782 * WARNING! This function cannot take snapshots all by itself. The caller
2783 * needs to do other massaging for snapshots.
2785 * WARNING! This function calls create which means it can insert indirect
2786 * blocks. Callers may have to refactor locked chains held across
2787 * the call (other than the ones passed into the call).
2790 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2791 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2792 int snapshot, int duplicate_reason)
2794 hammer2_mount_t *hmp;
2795 hammer2_chain_t *parent;
2796 hammer2_chain_t *ochain;
2797 hammer2_chain_t *nchain;
2798 hammer2_chain_core_t *above;
2802 * We want nchain to be our go-to live chain, but ochain may be in
2803 * a MODIFIED state within the current flush synchronization segment.
2804 * Force any further modifications of ochain to do another COW
2805 * operation even if modify_tid indicates that one is not needed.
2807 * We don't want to set FORCECOW on nchain simply as an optimization,
2808 * as many duplication calls simply move chains into ichains and
2809 * then delete the original.
2811 * WARNING! We should never resolve DATA to device buffers
2812 * (XXX allow it if the caller did?), and since
2813 * we currently do not have the logical buffer cache
2814 * buffer in-hand to fix its cached physical offset
2815 * we also force the modify code to not COW it. XXX
2819 KKASSERT(snapshot == 1 || (ochain->flags & HAMMER2_CHAIN_DELETED));
2821 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2824 * Now create a duplicate of the chain structure, associating
2825 * it with the same core, making it the same size, pointing it
2826 * to the same bref (the same media block).
2828 * Give the duplicate the same modify_tid that we previously
2829 * ensured was sufficiently advanced to trigger a block table
2830 * insertion on flush.
2832 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2833 * hammer2_chain_alloc()
2836 bref = &ochain->bref;
2838 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2839 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2841 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2843 hammer2_chain_core_alloc(trans, nchain, ochain);
2844 bytes = (hammer2_off_t)1 <<
2845 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2846 nchain->bytes = bytes;
2847 nchain->modify_tid = ochain->modify_tid;
2848 nchain->inode_reason = ochain->inode_reason + 0x100000;
2849 if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2850 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2851 if (ochain->flags & HAMMER2_CHAIN_UNLINKED)
2852 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_UNLINKED);
2855 * Switch from ochain to nchain
2857 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2858 HAMMER2_RESOLVE_NOREF);
2859 /* nchain has 1 ref */
2860 hammer2_chain_unlock(ochain);
2863 * Place nchain in the modified state, instantiate media data
2864 * if necessary. Because modify_tid is already completely
2865 * synchronized this should not result in a delete-duplicate.
2867 * We want nchain at the target to look like a new insertion.
2868 * Forcing the modification to be INPLACE accomplishes this
2869 * because we get the same nchain with an updated modify_tid.
2871 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2872 hammer2_chain_modify(trans, &nchain,
2873 HAMMER2_MODIFY_OPTDATA |
2874 HAMMER2_MODIFY_NOREALLOC |
2875 HAMMER2_MODIFY_INPLACE);
2876 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2877 hammer2_chain_modify(trans, &nchain,
2878 HAMMER2_MODIFY_OPTDATA |
2879 HAMMER2_MODIFY_INPLACE);
2881 hammer2_chain_modify(trans, &nchain,
2882 HAMMER2_MODIFY_INPLACE);
2886 * If parent is not NULL the duplicated chain will be entered under
2887 * the parent and the MOVED bit set.
2889 * Having both chains locked is extremely important for atomicy.
2891 if (parentp && (parent = *parentp) != NULL) {
2892 above = parent->core;
2893 KKASSERT(ccms_thread_lock_owned(&above->cst));
2894 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2895 KKASSERT(parent->refs > 0);
2897 hammer2_chain_create(trans, parentp, &nchain,
2898 nchain->bref.key, nchain->bref.keybits,
2899 nchain->bref.type, nchain->bytes);
2902 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2903 hammer2_chain_ref(nchain);
2904 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2906 hammer2_chain_setsubmod(trans, nchain);
2911 * Unconditionally set MOVED to force the parent blockrefs to
2912 * update, and adjust update_hi below nchain so nchain's
2913 * blockrefs are updated with the new attachment.
2915 if (nchain->core->update_hi < trans->sync_tid) {
2916 spin_lock(&nchain->core->cst.spin);
2917 if (nchain->core->update_hi < trans->sync_tid)
2918 nchain->core->update_hi = trans->sync_tid;
2919 spin_unlock(&nchain->core->cst.spin);
2927 * Special in-place delete-duplicate sequence which does not require a
2928 * locked parent. (*chainp) is marked DELETED and atomically replaced
2929 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2930 * order to ensure that lookups do not race us.
2932 * If the old chain is already marked deleted the new chain will also be
2933 * marked deleted. This case can occur when an inode is removed from the
2934 * filesystem but programs still have an open descriptor to it, and during
2935 * flushes when the flush needs to operate on a chain that is deleted in
2936 * the live view but still alive in the flush view.
2938 * The new chain will be marked modified for the current transaction.
2941 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2944 hammer2_mount_t *hmp;
2945 hammer2_chain_t *ochain;
2946 hammer2_chain_t *nchain;
2947 hammer2_chain_core_t *above;
2950 if (hammer2_debug & 0x20000)
2954 * Note that we do not have to call setsubmod on ochain, calling it
2955 * on nchain is sufficient.
2960 if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2961 KKASSERT(ochain->data);
2965 * First create a duplicate of the chain structure.
2966 * (nchain is allocated with one ref).
2968 * In the case where nchain inherits ochains core, nchain is
2969 * effectively locked due to ochain being locked (and sharing the
2970 * core), until we can give nchain its own official ock.
2972 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2973 if (flags & HAMMER2_DELDUP_RECORE)
2974 hammer2_chain_core_alloc(trans, nchain, NULL);
2976 hammer2_chain_core_alloc(trans, nchain, ochain);
2977 above = ochain->above;
2979 bytes = (hammer2_off_t)1 <<
2980 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2981 nchain->bytes = bytes;
2984 * Duplicate inherits ochain's live state including its modification
2985 * state. This function disposes of the original. Because we are
2986 * doing this in-place under the same parent the block array
2987 * inserted/deleted state does not change.
2989 * The caller isn't expected to make further modifications of ochain
2990 * but set the FORCECOW bit anyway, just in case it does. If ochain
2991 * was previously marked FORCECOW we also flag nchain FORCECOW
2992 * (used during hardlink splits). FORCECOW forces a reallocation
2993 * of the block when we modify the chain a little later, it does
2994 * not force another delete-duplicate.
2996 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2997 * hammer2_chain_alloc()
2999 nchain->data_count += ochain->data_count;
3000 nchain->inode_count += ochain->inode_count;
3001 atomic_set_int(&nchain->flags,
3002 ochain->flags & (HAMMER2_CHAIN_INITIAL |
3003 HAMMER2_CHAIN_FORCECOW |
3004 HAMMER2_CHAIN_UNLINKED));
3005 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
3006 nchain->inode_reason = ochain->inode_reason + 0x1000;
3009 * Lock nchain so both chains are now locked (extremely important
3010 * for atomicy). Mark ochain deleted and reinsert into the topology
3011 * and insert nchain all in one go.
3013 * If the ochain is already deleted it is left alone and nchain
3014 * is inserted into the topology as a deleted chain. This is
3015 * important because it allows ongoing operations to be executed
3016 * on a deleted inode which still has open descriptors.
3018 * The deleted case can also occur when a flush delete-duplicates
3019 * a node which is being concurrently modified by ongoing operations
3020 * in a later transaction. This creates a problem because the flush
3021 * is intended to update blockrefs which then propagate, allowing
3022 * the original covering in-memory chains to be freed up. In this
3023 * situation the flush code does NOT free the original covering
3024 * chains and will re-apply them to successive copies.
3026 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
3027 /* extra ref still present from original allocation */
3029 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
3030 spin_lock(&above->cst.spin);
3031 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
3034 * Ultimately nchain->modify_tid will be set to trans->sync_tid,
3035 * but we can't do that here because we want to call
3036 * hammer2_chain_modify() to reallocate the block (if necessary).
3038 nchain->modify_tid = ochain->modify_tid;
3040 if (ochain->flags & HAMMER2_CHAIN_DELETED) {
3042 * ochain was deleted
3044 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
3045 if (ochain->delete_tid > trans->sync_tid) {
3047 * delete-duplicate a chain deleted in a later
3048 * transaction. Only allowed on chains created
3049 * before or during the current transaction (flush
3050 * code should filter out chains created after the
3051 * current transaction).
3053 * To make this work is a bit of a hack. We convert
3054 * ochain's delete_tid to the current sync_tid and
3055 * create a nchain which sets up ochains original
3058 * This effectively forces ochain to flush as a
3059 * deletion and nchain as a creation. Thus MOVED
3060 * must be set in ochain (it should already be
3061 * set since it's original delete_tid could not
3062 * have been flushed yet). Since ochain's delete_tid
3063 * has been moved down to sync_tid, a re-flush at
3064 * sync_tid won't try to delete-duplicate ochain
3067 KKASSERT(ochain->modify_tid <= trans->sync_tid);
3068 nchain->delete_tid = ochain->delete_tid;
3069 ochain->delete_tid = trans->sync_tid;
3070 KKASSERT(ochain->flags & HAMMER2_CHAIN_MOVED);
3071 } else if (ochain->delete_tid == trans->sync_tid) {
3073 * ochain was deleted in the current transaction
3075 nchain->delete_tid = trans->sync_tid;
3078 * ochain was deleted in a prior transaction.
3079 * create and delete nchain in the current
3082 * (delete_tid might represent a deleted inode
3083 * which still has an open descriptor).
3085 nchain->delete_tid = trans->sync_tid;
3087 hammer2_chain_insert(above, ochain->inlayer, nchain, 0, 0);
3090 * ochain was not deleted, delete it in the current
3093 KKASSERT(trans->sync_tid >= ochain->modify_tid);
3094 ochain->delete_tid = trans->sync_tid;
3095 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
3096 atomic_add_int(&above->live_count, -1);
3097 hammer2_chain_insert(above, NULL, nchain,
3098 HAMMER2_CHAIN_INSERT_LIVE, 0);
3101 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3102 hammer2_chain_ref(ochain);
3103 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
3105 spin_unlock(&above->cst.spin);
3108 * ochain must be unlocked because ochain and nchain might share
3109 * a buffer cache buffer, so we need to release it so nchain can
3110 * potentially obtain it.
3112 hammer2_chain_unlock(ochain);
3115 * Finishing fixing up nchain. A new block will be allocated if
3116 * crossing a synchronization point (meta-data only).
3118 * Calling hammer2_chain_modify() will update modify_tid to
3119 * (typically) trans->sync_tid.
3121 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3122 hammer2_chain_modify(trans, &nchain,
3123 HAMMER2_MODIFY_OPTDATA |
3124 HAMMER2_MODIFY_NOREALLOC |
3125 HAMMER2_MODIFY_INPLACE);
3126 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3127 hammer2_chain_modify(trans, &nchain,
3128 HAMMER2_MODIFY_OPTDATA |
3129 HAMMER2_MODIFY_INPLACE);
3131 hammer2_chain_modify(trans, &nchain,
3132 HAMMER2_MODIFY_INPLACE);
3134 hammer2_chain_drop(nchain);
3137 * Unconditionally set MOVED to force the parent blockrefs to
3138 * update as the chain_modify() above won't necessarily do it.
3140 * Adjust update_hi below nchain so nchain's blockrefs are updated
3141 * with the new attachment.
3143 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3144 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
3145 hammer2_chain_ref(nchain);
3148 if (nchain->core->update_hi < trans->sync_tid) {
3149 spin_lock(&nchain->core->cst.spin);
3150 if (nchain->core->update_hi < trans->sync_tid)
3151 nchain->core->update_hi = trans->sync_tid;
3152 spin_unlock(&nchain->core->cst.spin);
3155 hammer2_chain_setsubmod(trans, nchain);
3160 * Create a snapshot of the specified {parent, ochain} with the specified
3161 * label. The originating hammer2_inode must be exclusively locked for
3164 * The ioctl code has already synced the filesystem.
3167 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
3168 hammer2_ioc_pfs_t *pfs)
3170 hammer2_mount_t *hmp;
3171 hammer2_chain_t *ochain = *ochainp;
3172 hammer2_chain_t *nchain;
3173 hammer2_inode_data_t *ipdata;
3174 hammer2_inode_t *nip;
3181 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
3182 pfs->name, ochain->refs, ochain->flags);
3184 name_len = strlen(pfs->name);
3185 lhc = hammer2_dirhash(pfs->name, name_len);
3188 opfs_clid = ochain->data->ipdata.pfs_clid;
3193 * Create the snapshot directory under the super-root
3195 * Set PFS type, generate a unique filesystem id, and generate
3196 * a cluster id. Use the same clid when snapshotting a PFS root,
3197 * which theoretically allows the snapshot to be used as part of
3198 * the same cluster (perhaps as a cache).
3200 * Copy the (flushed) ochain's blockref array. Theoretically we
3201 * could use chain_duplicate() but it becomes difficult to disentangle
3202 * the shared core so for now just brute-force it.
3208 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
3209 pfs->name, name_len, &nchain, &error);
3212 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
3213 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
3214 kern_uuidgen(&ipdata->pfs_fsid, 1);
3215 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
3216 ipdata->pfs_clid = opfs_clid;
3218 kern_uuidgen(&ipdata->pfs_clid, 1);
3219 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
3220 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
3222 hammer2_inode_unlock_ex(nip, nchain);
3228 * Create an indirect block that covers one or more of the elements in the
3229 * current parent. Either returns the existing parent with no locking or
3230 * ref changes or returns the new indirect block locked and referenced
3231 * and leaving the original parent lock/ref intact as well.
3233 * If an error occurs, NULL is returned and *errorp is set to the error.
3235 * The returned chain depends on where the specified key falls.
3237 * The key/keybits for the indirect mode only needs to follow three rules:
3239 * (1) That all elements underneath it fit within its key space and
3241 * (2) That all elements outside it are outside its key space.
3243 * (3) When creating the new indirect block any elements in the current
3244 * parent that fit within the new indirect block's keyspace must be
3245 * moved into the new indirect block.
3247 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3248 * keyspace the the current parent, but lookup/iteration rules will
3249 * ensure (and must ensure) that rule (2) for all parents leading up
3250 * to the nearest inode or the root volume header is adhered to. This
3251 * is accomplished by always recursing through matching keyspaces in
3252 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3254 * The current implementation calculates the current worst-case keyspace by
3255 * iterating the current parent and then divides it into two halves, choosing
3256 * whichever half has the most elements (not necessarily the half containing
3257 * the requested key).
3259 * We can also opt to use the half with the least number of elements. This
3260 * causes lower-numbered keys (aka logical file offsets) to recurse through
3261 * fewer indirect blocks and higher-numbered keys to recurse through more.
3262 * This also has the risk of not moving enough elements to the new indirect
3263 * block and being forced to create several indirect blocks before the element
3266 * Must be called with an exclusively locked parent.
3268 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3269 hammer2_key_t *keyp, int keybits,
3270 hammer2_blockref_t *base, int count);
3271 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3272 hammer2_key_t *keyp, int keybits,
3273 hammer2_blockref_t *base, int count);
3276 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3277 hammer2_key_t create_key, int create_bits,
3278 int for_type, int *errorp)
3280 hammer2_mount_t *hmp;
3281 hammer2_chain_core_t *above;
3282 hammer2_chain_core_t *icore;
3283 hammer2_blockref_t *base;
3284 hammer2_blockref_t *bref;
3285 hammer2_blockref_t bcopy;
3286 hammer2_chain_t *chain;
3287 hammer2_chain_t *ichain;
3288 hammer2_chain_t dummy;
3289 hammer2_key_t key = create_key;
3290 hammer2_key_t key_beg;
3291 hammer2_key_t key_end;
3292 hammer2_key_t key_next;
3293 int keybits = create_bits;
3300 int maxloops = 300000;
3303 hammer2_chain_t * volatile xxchain = NULL;
3306 * Calculate the base blockref pointer or NULL if the chain
3307 * is known to be empty. We need to calculate the array count
3308 * for RB lookups either way.
3312 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3313 above = parent->core;
3315 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3316 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3319 switch(parent->bref.type) {
3320 case HAMMER2_BREF_TYPE_INODE:
3321 count = HAMMER2_SET_COUNT;
3323 case HAMMER2_BREF_TYPE_INDIRECT:
3324 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3325 count = parent->bytes / sizeof(hammer2_blockref_t);
3327 case HAMMER2_BREF_TYPE_VOLUME:
3328 count = HAMMER2_SET_COUNT;
3330 case HAMMER2_BREF_TYPE_FREEMAP:
3331 count = HAMMER2_SET_COUNT;
3334 panic("hammer2_chain_create_indirect: "
3335 "unrecognized blockref type: %d",
3341 switch(parent->bref.type) {
3342 case HAMMER2_BREF_TYPE_INODE:
3343 base = &parent->data->ipdata.u.blockset.blockref[0];
3344 count = HAMMER2_SET_COUNT;
3346 case HAMMER2_BREF_TYPE_INDIRECT:
3347 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3348 base = &parent->data->npdata[0];
3349 count = parent->bytes / sizeof(hammer2_blockref_t);
3351 case HAMMER2_BREF_TYPE_VOLUME:
3352 base = &hmp->voldata.sroot_blockset.blockref[0];
3353 count = HAMMER2_SET_COUNT;
3355 case HAMMER2_BREF_TYPE_FREEMAP:
3356 base = &hmp->voldata.freemap_blockset.blockref[0];
3357 count = HAMMER2_SET_COUNT;
3360 panic("hammer2_chain_create_indirect: "
3361 "unrecognized blockref type: %d",
3369 * dummy used in later chain allocation (no longer used for lookups).
3371 bzero(&dummy, sizeof(dummy));
3372 dummy.delete_tid = HAMMER2_MAX_TID;
3375 * When creating an indirect block for a freemap node or leaf
3376 * the key/keybits must be fitted to static radix levels because
3377 * particular radix levels use particular reserved blocks in the
3380 * This routine calculates the key/radix of the indirect block
3381 * we need to create, and whether it is on the high-side or the
3384 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3385 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3386 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3389 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3394 * Normalize the key for the radix being represented, keeping the
3395 * high bits and throwing away the low bits.
3397 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3400 * How big should our new indirect block be? It has to be at least
3401 * as large as its parent.
3403 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3404 nbytes = HAMMER2_IND_BYTES_MIN;
3406 nbytes = HAMMER2_IND_BYTES_MAX;
3407 if (nbytes < count * sizeof(hammer2_blockref_t))
3408 nbytes = count * sizeof(hammer2_blockref_t);
3411 * Ok, create our new indirect block
3413 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3414 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3415 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3417 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3419 dummy.bref.key = key;
3420 dummy.bref.keybits = keybits;
3421 dummy.bref.data_off = hammer2_getradix(nbytes);
3422 dummy.bref.methods = parent->bref.methods;
3424 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3425 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3426 hammer2_chain_core_alloc(trans, ichain, NULL);
3427 icore = ichain->core;
3428 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3429 hammer2_chain_drop(ichain); /* excess ref from alloc */
3432 * We have to mark it modified to allocate its block, but use
3433 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3434 * it won't be acted upon by the flush code.
3436 * XXX leave the node unmodified, depend on the update_hi
3437 * flush to assign and modify parent blocks.
3439 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3442 * Iterate the original parent and move the matching brefs into
3443 * the new indirect block.
3445 * XXX handle flushes.
3448 key_end = HAMMER2_MAX_KEY;
3450 spin_lock(&above->cst.spin);
3456 if (++loops > 100000) {
3457 spin_unlock(&above->cst.spin);
3458 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3459 reason, parent, base, count, key_next);
3463 * NOTE: spinlock stays intact, returned chain (if not NULL)
3464 * is not referenced or locked which means that we
3465 * cannot safely check its flagged / deletion status
3468 chain = hammer2_combined_find(parent, base, count,
3469 &cache_index, &key_next,
3472 generation = above->generation;
3475 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3478 * Skip keys that are not within the key/radix of the new
3479 * indirect block. They stay in the parent.
3481 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3482 (key ^ bref->key)) != 0) {
3483 goto next_key_spinlocked;
3487 * Load the new indirect block by acquiring the related
3488 * chains (potentially from media as it might not be
3489 * in-memory). Then move it to the new parent (ichain)
3490 * via DELETE-DUPLICATE.
3492 * chain is referenced but not locked. We must lock the
3493 * chain to obtain definitive DUPLICATED/DELETED state
3497 * Use chain already present in the RBTREE
3499 hammer2_chain_ref(chain);
3500 wasdup = ((chain->flags &
3501 HAMMER2_CHAIN_DUPLICATED) != 0);
3502 spin_unlock(&above->cst.spin);
3503 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3504 HAMMER2_RESOLVE_NOREF);
3507 * Get chain for blockref element. _get returns NULL
3508 * on insertion race.
3511 spin_unlock(&above->cst.spin);
3512 chain = hammer2_chain_get(parent, &bcopy, generation);
3513 if (chain == NULL) {
3515 spin_lock(&above->cst.spin);
3518 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3520 hammer2_chain_drop(chain);
3521 spin_lock(&above->cst.spin);
3524 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3525 HAMMER2_RESOLVE_NOREF);
3530 * This is always live so if the chain has been delete-
3531 * duplicated we raced someone and we have to retry.
3533 * NOTE: Lookups can race delete-duplicate because
3534 * delete-duplicate does not lock the parent's core
3535 * (they just use the spinlock on the core). We must
3536 * check for races by comparing the DUPLICATED flag before
3537 * releasing the spinlock with the flag after locking the
3540 * (note reversed logic for this one)
3542 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3543 hammer2_chain_unlock(chain);
3544 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) &&
3553 * Shift the chain to the indirect block.
3555 * WARNING! Can cause held-over chains to require a refactor.
3556 * Fortunately we have none (our locked chains are
3557 * passed into and modified by the call).
3559 hammer2_chain_delete(trans, chain, 0);
3560 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0, 1);
3561 hammer2_chain_unlock(chain);
3562 KKASSERT(parent->refs > 0);
3565 spin_lock(&above->cst.spin);
3566 next_key_spinlocked:
3567 if (--maxloops == 0)
3568 panic("hammer2_chain_create_indirect: maxloops");
3570 if (retry_same == 0) {
3571 if (key_next == 0 || key_next > key_end)
3577 spin_unlock(&above->cst.spin);
3580 * Insert the new indirect block into the parent now that we've
3581 * cleared out some entries in the parent. We calculated a good
3582 * insertion index in the loop above (ichain->index).
3584 * We don't have to set MOVED here because we mark ichain modified
3585 * down below (so the normal modified -> flush -> set-moved sequence
3588 * The insertion shouldn't race as this is a completely new block
3589 * and the parent is locked.
3591 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3592 hammer2_chain_insert(above, NULL, ichain,
3593 HAMMER2_CHAIN_INSERT_SPIN |
3594 HAMMER2_CHAIN_INSERT_LIVE,
3598 * Mark the new indirect block modified after insertion, which
3599 * will propagate up through parent all the way to the root and
3600 * also allocate the physical block in ichain for our caller,
3601 * and assign ichain->data to a pre-zero'd space (because there
3602 * is not prior data to copy into it).
3604 * We have to set update_hi in ichain's flags manually so the
3605 * flusher knows it has to recurse through it to get to all of
3606 * our moved blocks, then call setsubmod() to set the bit
3609 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3610 if (ichain->core->update_hi < trans->sync_tid) {
3611 spin_lock(&ichain->core->cst.spin);
3612 if (ichain->core->update_hi < trans->sync_tid)
3613 ichain->core->update_hi = trans->sync_tid;
3614 spin_unlock(&ichain->core->cst.spin);
3616 hammer2_chain_setsubmod(trans, ichain);
3619 * Figure out what to return.
3621 if (~(((hammer2_key_t)1 << keybits) - 1) &
3622 (create_key ^ key)) {
3624 * Key being created is outside the key range,
3625 * return the original parent.
3627 hammer2_chain_unlock(ichain);
3630 * Otherwise its in the range, return the new parent.
3631 * (leave both the new and old parent locked).
3641 * Calculate the keybits and highside/lowside of the freemap node the
3642 * caller is creating.
3644 * This routine will specify the next higher-level freemap key/radix
3645 * representing the lowest-ordered set. By doing so, eventually all
3646 * low-ordered sets will be moved one level down.
3648 * We have to be careful here because the freemap reserves a limited
3649 * number of blocks for a limited number of levels. So we can't just
3650 * push indiscriminately.
3653 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3654 int keybits, hammer2_blockref_t *base, int count)
3656 hammer2_chain_core_t *above;
3657 hammer2_chain_t *chain;
3658 hammer2_blockref_t *bref;
3660 hammer2_key_t key_beg;
3661 hammer2_key_t key_end;
3662 hammer2_key_t key_next;
3666 int maxloops = 300000;
3669 above = parent->core;
3675 * Calculate the range of keys in the array being careful to skip
3676 * slots which are overridden with a deletion.
3679 key_end = HAMMER2_MAX_KEY;
3681 spin_lock(&above->cst.spin);
3684 if (--maxloops == 0) {
3685 panic("indkey_freemap shit %p %p:%d\n",
3686 parent, base, count);
3688 chain = hammer2_combined_find(parent, base, count,
3689 &cache_index, &key_next,
3690 key_beg, key_end, &bref);
3699 * NOTE: No need to check DUPLICATED here because we do
3700 * not release the spinlock.
3702 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3703 if (key_next == 0 || key_next > key_end)
3710 * Use the full live (not deleted) element for the scan
3711 * iteration. HAMMER2 does not allow partial replacements.
3713 * XXX should be built into hammer2_combined_find().
3715 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3717 if (keybits > bref->keybits) {
3719 keybits = bref->keybits;
3720 } else if (keybits == bref->keybits && bref->key < key) {
3727 spin_unlock(&above->cst.spin);
3730 * Return the keybits for a higher-level FREEMAP_NODE covering
3734 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3735 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3737 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3738 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3740 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3741 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3743 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3744 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3746 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3747 panic("hammer2_chain_indkey_freemap: level too high");
3750 panic("hammer2_chain_indkey_freemap: bad radix");
3759 * Calculate the keybits and highside/lowside of the indirect block the
3760 * caller is creating.
3763 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3764 int keybits, hammer2_blockref_t *base, int count)
3766 hammer2_chain_core_t *above;
3767 hammer2_blockref_t *bref;
3768 hammer2_chain_t *chain;
3769 hammer2_key_t key_beg;
3770 hammer2_key_t key_end;
3771 hammer2_key_t key_next;
3777 int maxloops = 300000;
3780 above = parent->core;
3785 * Calculate the range of keys in the array being careful to skip
3786 * slots which are overridden with a deletion. Once the scan
3787 * completes we will cut the key range in half and shift half the
3788 * range into the new indirect block.
3791 key_end = HAMMER2_MAX_KEY;
3793 spin_lock(&above->cst.spin);
3796 if (--maxloops == 0) {
3797 panic("indkey_freemap shit %p %p:%d\n",
3798 parent, base, count);
3800 chain = hammer2_combined_find(parent, base, count,
3801 &cache_index, &key_next,
3802 key_beg, key_end, &bref);
3811 * NOTE: No need to check DUPLICATED here because we do
3812 * not release the spinlock.
3814 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3815 if (key_next == 0 || key_next > key_end)
3822 * Use the full live (not deleted) element for the scan
3823 * iteration. HAMMER2 does not allow partial replacements.
3825 * XXX should be built into hammer2_combined_find().
3827 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3830 * Expand our calculated key range (key, keybits) to fit
3831 * the scanned key. nkeybits represents the full range
3832 * that we will later cut in half (two halves @ nkeybits - 1).
3835 if (nkeybits < bref->keybits) {
3836 if (bref->keybits > 64) {
3837 kprintf("bad bref chain %p bref %p\n",
3841 nkeybits = bref->keybits;
3843 while (nkeybits < 64 &&
3844 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3845 (key ^ bref->key)) != 0) {
3850 * If the new key range is larger we have to determine
3851 * which side of the new key range the existing keys fall
3852 * under by checking the high bit, then collapsing the
3853 * locount into the hicount or vise-versa.
3855 if (keybits != nkeybits) {
3856 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3867 * The newly scanned key will be in the lower half or the
3868 * upper half of the (new) key range.
3870 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3879 spin_unlock(&above->cst.spin);
3880 bref = NULL; /* now invalid (safety) */
3883 * Adjust keybits to represent half of the full range calculated
3884 * above (radix 63 max)
3889 * Select whichever half contains the most elements. Theoretically
3890 * we can select either side as long as it contains at least one
3891 * element (in order to ensure that a free slot is present to hold
3892 * the indirect block).
3894 if (hammer2_indirect_optimize) {
3896 * Insert node for least number of keys, this will arrange
3897 * the first few blocks of a large file or the first few
3898 * inodes in a directory with fewer indirect blocks when
3901 if (hicount < locount && hicount != 0)
3902 key |= (hammer2_key_t)1 << keybits;
3904 key &= ~(hammer2_key_t)1 << keybits;
3907 * Insert node for most number of keys, best for heavily
3910 if (hicount > locount)
3911 key |= (hammer2_key_t)1 << keybits;
3913 key &= ~(hammer2_key_t)1 << keybits;
3921 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3922 * set chain->delete_tid. The chain is not actually marked possibly-free
3923 * in the freemap until the deletion is completely flushed out (because
3924 * a flush which doesn't cover the entire deletion is flushing the deleted
3925 * chain as if it were live).
3927 * This function does NOT generate a modification to the parent. It
3928 * would be nearly impossible to figure out which parent to modify anyway.
3929 * Such modifications are handled top-down by the flush code and are
3930 * properly merged using the flush synchronization point.
3932 * The find/get code will properly overload the RBTREE check on top of
3933 * the bref check to detect deleted entries.
3935 * This function is NOT recursive. Any entity already pushed into the
3936 * chain (such as an inode) may still need visibility into its contents,
3937 * as well as the ability to read and modify the contents. For example,
3938 * for an unlinked file which is still open.
3940 * NOTE: This function does NOT set chain->modify_tid, allowing future
3941 * code to distinguish between live and deleted chains by testing
3942 * trans->sync_tid vs chain->modify_tid and chain->delete_tid.
3944 * NOTE: Deletions normally do not occur in the middle of a duplication
3945 * chain but we use a trick for hardlink migration that refactors
3946 * the originating inode without deleting it, so we make no assumptions
3950 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3952 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3955 * Nothing to do if already marked.
3957 if (chain->flags & HAMMER2_CHAIN_DELETED)
3961 * The setting of DELETED causes finds, lookups, and _next iterations
3962 * to no longer recognize the chain. RB_SCAN()s will still have
3963 * visibility (needed for flush serialization points).
3965 * We need the spinlock on the core whos RBTREE contains chain
3966 * to protect against races.
3968 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3969 spin_lock(&chain->above->cst.spin);
3971 KKASSERT(trans->sync_tid >= chain->modify_tid);
3972 chain->delete_tid = trans->sync_tid;
3973 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3974 atomic_add_int(&chain->above->live_count, -1);
3975 ++chain->above->generation;
3978 * We must set MOVED along with DELETED for the flush code to
3979 * recognize the operation and properly disconnect the chain
3982 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3983 hammer2_chain_ref(chain);
3984 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3986 spin_unlock(&chain->above->cst.spin);
3988 hammer2_chain_setsubmod(trans, chain);
3992 * Called with the core spinlock held to check for freeable layers.
3993 * Used by the flush code. Layers can wind up not being freed due
3994 * to the temporary layer->refs count. This function frees up any
3995 * layers that were missed.
3998 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3999 hammer2_chain_core_t *core)
4001 hammer2_chain_layer_t *layer;
4002 hammer2_chain_layer_t *tmp;
4004 tmp = TAILQ_FIRST(&core->layerq);
4005 while ((layer = tmp) != NULL) {
4006 tmp = TAILQ_NEXT(tmp, entry);
4007 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
4008 TAILQ_REMOVE(&core->layerq, layer, entry);
4011 spin_unlock(&core->cst.spin);
4012 kfree(layer, hmp->mchain);
4013 spin_lock(&core->cst.spin);
4021 * Returns the index of the nearest element in the blockref array >= elm.
4022 * Returns (count) if no element could be found.
4024 * Sets *key_nextp to the next key for loop purposes but does not modify
4025 * it if the next key would be higher than the current value of *key_nextp.
4026 * Note that *key_nexp can overflow to 0, which should be tested by the
4029 * (*cache_indexp) is a heuristic and can be any value without effecting
4032 * The spin lock on the related chain must be held.
4035 hammer2_base_find(hammer2_chain_t *chain,
4036 hammer2_blockref_t *base, int count,
4037 int *cache_indexp, hammer2_key_t *key_nextp,
4038 hammer2_key_t key_beg, hammer2_key_t key_end)
4040 hammer2_chain_core_t *core = chain->core;
4041 hammer2_blockref_t *scan;
4042 hammer2_key_t scan_end;
4047 * Require the live chain's already have their core's counted
4048 * so we can optimize operations.
4050 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) ||
4051 core->flags & HAMMER2_CORE_COUNTEDBREFS);
4056 if (count == 0 || base == NULL)
4060 * Sequential optimization using *cache_indexp. This is the most
4063 * We can avoid trailing empty entries on live chains, otherwise
4064 * we might have to check the whole block array.
4068 if (chain->flags & HAMMER2_CHAIN_DUPLICATED)
4071 limit = core->live_zero;
4076 KKASSERT(i < count);
4082 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4089 * Search forwards, stop when we find a scan element which
4090 * encloses the key or until we know that there are no further
4094 if (scan->type != 0) {
4095 if (scan->key > key_beg)
4097 scan_end = scan->key +
4098 ((hammer2_key_t)1 << scan->keybits) - 1;
4099 if (scan_end >= key_beg)
4112 scan_end = scan->key +
4113 ((hammer2_key_t)1 << scan->keybits);
4114 if (scan_end && (*key_nextp > scan_end ||
4116 *key_nextp = scan_end;
4124 * Do a combined search and return the next match either from the blockref
4125 * array or from the in-memory chain. Sets *bresp to the returned bref in
4126 * both cases, or sets it to NULL if the search exhausted. Only returns
4127 * a non-NULL chain if the search matched from the in-memory chain.
4129 * Must be called with above's spinlock held. Spinlock remains held
4130 * through the operation.
4132 * The returned chain is not locked or referenced. Use the returned bref
4133 * to determine if the search exhausted or not.
4135 static hammer2_chain_t *
4136 hammer2_combined_find(hammer2_chain_t *parent,
4137 hammer2_blockref_t *base, int count,
4138 int *cache_indexp, hammer2_key_t *key_nextp,
4139 hammer2_key_t key_beg, hammer2_key_t key_end,
4140 hammer2_blockref_t **bresp)
4142 hammer2_blockref_t *bref;
4143 hammer2_chain_t *chain;
4146 *key_nextp = key_end + 1;
4147 i = hammer2_base_find(parent, base, count, cache_indexp,
4148 key_nextp, key_beg, key_end);
4149 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4154 if (i == count && chain == NULL) {
4156 return(chain); /* NULL */
4160 * Only chain matched
4163 bref = &chain->bref;
4168 * Only blockref matched.
4170 if (chain == NULL) {
4176 * Both in-memory and blockref match. Select the nearer element.
4177 * If both are flush with the left-hand side they are considered
4178 * to be the same distance.
4180 * When both are the same distance away select the chain if it is
4181 * live or if it's delete_tid is greater than the parent's
4182 * synchronized bref.mirror_tid (a single test suffices for both
4183 * conditions), otherwise select the element.
4185 * (It is possible for an old deletion to linger after a rename-over
4186 * and flush, which would make the media copy the correct choice).
4190 * Either both are flush with the left-hand side or they are the
4191 * same distance away. Select the chain if it is not deleted
4192 * or it has a higher delete_tid, else select the media.
4194 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4195 chain->bref.key == base[i].key) {
4196 if (chain->delete_tid > base[i].mirror_tid) {
4197 bref = &chain->bref;
4199 KKASSERT(chain->flags & HAMMER2_CHAIN_DELETED);
4207 * Select the nearer key.
4209 if (chain->bref.key < base[i].key) {
4210 bref = &chain->bref;
4217 * If the bref is out of bounds we've exhausted our search.
4220 if (bref->key > key_end) {
4230 * Locate the specified block array element and delete it. The element
4233 * The spin lock on the related chain must be held.
4235 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4236 * need to be adjusted when we commit the media change.
4239 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
4240 hammer2_blockref_t *base, int count,
4241 int *cache_indexp, hammer2_chain_t *child)
4243 hammer2_blockref_t *elm = &child->bref;
4244 hammer2_chain_core_t *core = parent->core;
4245 hammer2_key_t key_next;
4249 * Delete element. Expect the element to exist.
4251 * XXX see caller, flush code not yet sophisticated enough to prevent
4252 * re-flushed in some cases.
4254 key_next = 0; /* max range */
4255 i = hammer2_base_find(parent, base, count, cache_indexp,
4256 &key_next, elm->key, elm->key);
4257 if (i == count || base[i].type == 0 ||
4258 base[i].key != elm->key || base[i].keybits != elm->keybits) {
4259 panic("delete base %p element not found at %d/%d elm %p\n",
4260 base, i, count, elm);
4263 bzero(&base[i], sizeof(*base));
4264 base[i].mirror_tid = (intptr_t)parent; /* debug */
4265 base[i].modify_tid = (intptr_t)child; /* debug */
4266 base[i].check.debug.sync_tid = trans->sync_tid; /* debug */
4269 * We can only optimize core->live_zero for live chains.
4271 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4272 if (core->live_zero == i + 1) {
4273 while (--i >= 0 && base[i].type == 0)
4275 core->live_zero = i + 1;
4281 * Insert the specified element. The block array must not already have the
4282 * element and must have space available for the insertion.
4284 * The spin lock on the related chain must be held.
4286 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4287 * need to be adjusted when we commit the media change.
4290 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
4291 hammer2_blockref_t *base, int count,
4292 int *cache_indexp, hammer2_chain_t *child)
4294 hammer2_blockref_t *elm = &child->bref;
4295 hammer2_chain_core_t *core = parent->core;
4296 hammer2_key_t key_next;
4305 * Insert new element. Expect the element to not already exist
4306 * unless we are replacing it.
4308 * XXX see caller, flush code not yet sophisticated enough to prevent
4309 * re-flushed in some cases.
4311 key_next = 0; /* max range */
4312 i = hammer2_base_find(parent, base, count, cache_indexp,
4313 &key_next, elm->key, elm->key);
4316 * Shortcut fill optimization, typical ordered insertion(s) may not
4319 KKASSERT(i >= 0 && i <= count);
4322 * We can only optimize core->live_zero for live chains.
4324 if (i == count && core->live_zero < count) {
4325 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4326 i = core->live_zero++;
4332 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4333 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4334 panic("insert base %p overlapping elements at %d elm %p\n",
4339 * Try to find an empty slot before or after.
4343 while (j > 0 || k < count) {
4345 if (j >= 0 && base[j].type == 0) {
4349 bcopy(&base[j+1], &base[j],
4350 (i - j - 1) * sizeof(*base));
4356 if (k < count && base[k].type == 0) {
4357 bcopy(&base[i], &base[i+1],
4358 (k - i) * sizeof(hammer2_blockref_t));
4362 * We can only update core->live_zero for live
4365 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4366 if (core->live_zero <= k)
4367 core->live_zero = k + 1;
4373 panic("hammer2_base_insert: no room!");
4380 for (l = 0; l < count; ++l) {
4382 key_next = base[l].key +
4383 ((hammer2_key_t)1 << base[l].keybits) - 1;
4387 while (++l < count) {
4389 if (base[l].key <= key_next)
4390 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4391 key_next = base[l].key +
4392 ((hammer2_key_t)1 << base[l].keybits) - 1;
4402 * Sort the blockref array for the chain. Used by the flush code to
4403 * sort the blockref[] array.
4405 * The chain must be exclusively locked AND spin-locked.
4407 typedef hammer2_blockref_t *hammer2_blockref_p;
4411 hammer2_base_sort_callback(const void *v1, const void *v2)
4413 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4414 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4417 * Make sure empty elements are placed at the end of the array
4419 if (bref1->type == 0) {
4420 if (bref2->type == 0)
4423 } else if (bref2->type == 0) {
4430 if (bref1->key < bref2->key)
4432 if (bref1->key > bref2->key)
4438 hammer2_base_sort(hammer2_chain_t *chain)
4440 hammer2_blockref_t *base;
4443 switch(chain->bref.type) {
4444 case HAMMER2_BREF_TYPE_INODE:
4446 * Special shortcut for embedded data returns the inode
4447 * itself. Callers must detect this condition and access
4448 * the embedded data (the strategy code does this for us).
4450 * This is only applicable to regular files and softlinks.
4452 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4454 base = &chain->data->ipdata.u.blockset.blockref[0];
4455 count = HAMMER2_SET_COUNT;
4457 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4458 case HAMMER2_BREF_TYPE_INDIRECT:
4460 * Optimize indirect blocks in the INITIAL state to avoid
4463 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4464 base = &chain->data->npdata[0];
4465 count = chain->bytes / sizeof(hammer2_blockref_t);
4467 case HAMMER2_BREF_TYPE_VOLUME:
4468 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4469 count = HAMMER2_SET_COUNT;
4471 case HAMMER2_BREF_TYPE_FREEMAP:
4472 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4473 count = HAMMER2_SET_COUNT;
4476 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4478 base = NULL; /* safety */
4479 count = 0; /* safety */
4481 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4487 * Chain memory management
4490 hammer2_chain_wait(hammer2_chain_t *chain)
4492 tsleep(chain, 0, "chnflw", 1);
4496 * Manage excessive memory resource use for chain and related
4500 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4510 * Atomic check condition and wait. Also do an early speedup of
4511 * the syncer to try to avoid hitting the wait.
4514 waiting = pmp->inmem_dirty_chains;
4516 count = waiting & HAMMER2_DIRTYCHAIN_MASK;
4518 limit = pmp->mp->mnt_nvnodelistsize / 10;
4519 if (limit < hammer2_limit_dirty_chains)
4520 limit = hammer2_limit_dirty_chains;
4525 if ((int)(ticks - zzticks) > hz) {
4527 kprintf("count %ld %ld\n", count, limit);
4532 * Block if there are too many dirty chains present, wait
4533 * for the flush to clean some out.
4535 if (count > limit) {
4536 tsleep_interlock(&pmp->inmem_dirty_chains, 0);
4537 if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4539 waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
4540 speedup_syncer(pmp->mp);
4541 tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
4544 continue; /* loop on success or fail */
4548 * Try to start an early flush before we are forced to block.
4550 if (count > limit * 7 / 10)
4551 speedup_syncer(pmp->mp);
4557 hammer2_chain_memory_inc(hammer2_pfsmount_t *pmp)
4560 atomic_add_long(&pmp->inmem_dirty_chains, 1);
4564 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4572 waiting = pmp->inmem_dirty_chains;
4574 if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4577 ~HAMMER2_DIRTYCHAIN_WAITING)) {
4581 if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
4582 wakeup(&pmp->inmem_dirty_chains);
4587 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4591 switch(bref->type) {
4592 case HAMMER2_BREF_TYPE_DATA:
4593 counterp = &hammer2_iod_file_read;
4595 case HAMMER2_BREF_TYPE_INODE:
4596 counterp = &hammer2_iod_meta_read;
4598 case HAMMER2_BREF_TYPE_INDIRECT:
4599 counterp = &hammer2_iod_indr_read;
4601 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4602 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4603 counterp = &hammer2_iod_fmap_read;
4606 counterp = &hammer2_iod_volu_read;