2 * Copyright (c) 2011-2013 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This subsystem implements most of the core support functions for
37 * the hammer2_chain structure.
39 * Chains are the in-memory version on media objects (volume header, inodes,
40 * indirect blocks, data blocks, etc). Chains represent a portion of the
43 * A chain is topologically stable once it has been inserted into the
44 * in-memory topology. Modifications which copy, move, or resize the chain
45 * are handled via the DELETE-DUPLICATE mechanic where the original chain
46 * stays intact but is marked deleted and a new chain is allocated which
47 * shares the old chain's children.
49 * This sharing is handled via the hammer2_chain_core structure.
51 * The DELETE-DUPLICATE mechanism allows the same topological level to contain
52 * many overloadings. However, our RBTREE mechanics require that there be
53 * no overlaps so we accomplish the overloading by moving conflicting chains
54 * with smaller or equal radii into a sub-RBTREE under the chain being
57 * DELETE-DUPLICATE is also used when a modification to a chain crosses a
58 * flush synchronization boundary, allowing the flush code to continue flushing
59 * the older version of the topology and not be disrupted by new frontend
64 * All lookup and iterate operations and most modifications are done on the
65 * live view. During flushes lookups are not normally done and modifications
66 * may be run on the flush view. However, flushes often needs to allocate
67 * blocks and the freemap_alloc/free code issues lookups. This code is
68 * special cased to use the live view when called from a flush.
70 * General chain lookup/iteration functions are NOT aware of the flush view,
71 * they only know about live views.
73 #include <sys/cdefs.h>
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/types.h>
78 #include <sys/kern_syscall.h>
83 static int hammer2_indirect_optimize; /* XXX SYSCTL */
85 static hammer2_chain_t *hammer2_chain_create_indirect(
86 hammer2_trans_t *trans, hammer2_chain_t *parent,
87 hammer2_key_t key, int keybits, int for_type, int *errorp);
88 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
89 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
90 static hammer2_chain_t *hammer2_combined_find(
91 hammer2_chain_t *parent,
92 hammer2_blockref_t *base, int count,
93 int *cache_indexp, hammer2_key_t *key_nextp,
94 hammer2_key_t key_beg, hammer2_key_t key_end,
95 hammer2_blockref_t **bresp);
98 * Basic RBTree for chains. Chains cannot overlap within any given
99 * core->rbtree without recursing through chain->rbtree. We effectively
100 * guarantee this by checking the full range rather than just the first
101 * key element. By matching on the full range callers can detect when
102 * recursrion through chain->rbtree is needed.
104 * NOTE: This also means the a delete-duplicate on the same key will
105 * overload by placing the deleted element in the new element's
106 * chain->rbtree (when doing a direct replacement).
108 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
111 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
113 hammer2_key_t c1_beg;
114 hammer2_key_t c1_end;
115 hammer2_key_t c2_beg;
116 hammer2_key_t c2_end;
118 c1_beg = chain1->bref.key;
119 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
120 c2_beg = chain2->bref.key;
121 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
123 if (c1_end < c2_beg) /* fully to the left */
125 if (c1_beg > c2_end) /* fully to the right */
127 return(0); /* overlap (must not cross edge boundary) */
132 hammer2_isclusterable(hammer2_chain_t *chain)
134 if (hammer2_cluster_enable) {
135 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
136 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
137 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
145 * Recursively set the update_hi flag up to the root starting at chain's
146 * parent->core. update_hi is not set in chain's core.
148 * This controls top-down visibility for flushes. The child has just one
149 * 'above' core, but the core itself can be multi-homed with parents iterated
152 * This function is not used during a flush (except when the flush is
153 * allocating which requires the live tree). The flush keeps track of its
156 * XXX needs to be optimized to use roll-up TIDs. update_hi is only really
157 * compared against bref.mirror_tid which itself is only updated by a flush.
160 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
162 hammer2_chain_core_t *above;
164 while ((above = chain->above) != NULL) {
165 spin_lock(&above->cst.spin);
167 if (above->update_hi < trans->sync_tid)
168 above->update_hi = trans->sync_tid;
169 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
171 TAILQ_FOREACH_REVERSE(chain, &above->ownerq,
172 h2_core_list, core_entry) {
173 if (trans->sync_tid >= chain->modify_tid &&
174 trans->sync_tid <= chain->delete_tid) {
179 spin_unlock(&above->cst.spin);
184 * Allocate a new disconnected chain element representing the specified
185 * bref. chain->refs is set to 1 and the passed bref is copied to
186 * chain->bref. chain->bytes is derived from the bref.
188 * chain->core is NOT allocated and the media data and bp pointers are left
189 * NULL. The caller must call chain_core_alloc() to allocate or associate
190 * a core with the chain.
192 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
195 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
196 hammer2_trans_t *trans, hammer2_blockref_t *bref)
198 hammer2_chain_t *chain;
199 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
202 * Construct the appropriate system structure.
205 case HAMMER2_BREF_TYPE_INODE:
206 case HAMMER2_BREF_TYPE_INDIRECT:
207 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
208 case HAMMER2_BREF_TYPE_DATA:
209 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
211 * Chain's are really only associated with the hmp but we
212 * maintain a pmp association for per-mount memory tracking
213 * purposes. The pmp can be NULL.
215 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
218 atomic_add_long(&pmp->inmem_chains, 1);
221 case HAMMER2_BREF_TYPE_VOLUME:
222 case HAMMER2_BREF_TYPE_FREEMAP:
224 panic("hammer2_chain_alloc volume type illegal for op");
227 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
233 chain->bytes = bytes;
235 chain->flags = HAMMER2_CHAIN_ALLOCATED;
236 chain->delete_tid = HAMMER2_MAX_TID;
239 * Set modify_tid if a transaction is creating the chain. When
240 * loading a chain from backing store trans is passed as NULL and
241 * modify_tid is left set to 0.
244 chain->modify_tid = trans->sync_tid;
250 * Associate an existing core with the chain or allocate a new core.
252 * The core is not locked. No additional refs on the chain are made.
253 * (trans) must not be NULL if (core) is not NULL.
255 * When chains are delete-duplicated during flushes we insert nchain on
256 * the ownerq after ochain instead of at the end in order to give the
257 * drop code visibility in the correct order, otherwise drops can be missed.
260 hammer2_chain_core_alloc(hammer2_trans_t *trans,
261 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
263 hammer2_chain_core_t *core;
265 KKASSERT(nchain->core == NULL);
267 if (ochain == NULL) {
269 * Fresh core under nchain (no multi-homing of ochain's
272 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
274 TAILQ_INIT(&core->layerq);
275 TAILQ_INIT(&core->ownerq);
279 core->update_hi = trans->sync_tid;
281 core->update_hi = nchain->bref.mirror_tid;
283 ccms_cst_init(&core->cst, nchain);
284 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
287 * Propagate the PFSROOT flag which we set on all subdirs
288 * under the super-root.
290 atomic_set_int(&nchain->flags,
291 ochain->flags & HAMMER2_CHAIN_PFSROOT);
294 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
295 * ochain if nchain is not a snapshot.
297 * It is possible for the DUPLICATED flag to already be
298 * set when called via a flush operation because flush
299 * operations may have to work on elements with delete_tid's
300 * beyond the flush sync_tid. In this situation we must
301 * ensure that nchain is placed just after ochain in the
302 * ownerq and that the DUPLICATED flag is set on nchain so
303 * 'live' operations skip past it to the correct chain.
305 * The flusher understands the blockref synchronization state
306 * for any stale chains by observing bref.mirror_tid, which
307 * delete-duplicate replicates.
309 * WARNING! However, the case is disallowed when the flusher
310 * is allocating freemap space because this entails
311 * more than just adjusting a block table.
313 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
314 KKASSERT((trans->flags &
315 (HAMMER2_TRANS_ISFLUSH |
316 HAMMER2_TRANS_ISALLOCATING)) ==
317 HAMMER2_TRANS_ISFLUSH);
318 atomic_set_int(&nchain->flags,
319 HAMMER2_CHAIN_DUPLICATED);
321 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
322 atomic_set_int(&ochain->flags,
323 HAMMER2_CHAIN_DUPLICATED);
326 atomic_add_int(&core->sharecnt, 1);
328 spin_lock(&core->cst.spin);
332 if (core->update_hi < trans->sync_tid)
333 core->update_hi = trans->sync_tid;
337 * Maintain ordering for refactor test so we don't skip over
338 * a snapshot. Also, during flushes, delete-duplications
339 * for block-table updates can occur on blocks already
340 * deleted (delete-duplicated by a later transaction). We
341 * must insert nchain after ochain but before the later
342 * transaction's copy.
344 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
346 spin_unlock(&core->cst.spin);
351 * Add a reference to a chain element, preventing its destruction.
354 hammer2_chain_ref(hammer2_chain_t *chain)
356 atomic_add_int(&chain->refs, 1);
360 * Insert the chain in the core rbtree at the first layer
361 * which accepts it (for now we don't sort layers by the transaction tid)
363 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
364 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
365 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
369 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_layer_t *layer,
370 hammer2_chain_t *chain, int flags, int generation)
372 hammer2_chain_t *xchain;
373 hammer2_chain_layer_t *nlayer;
376 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
377 spin_lock(&above->cst.spin);
378 chain->above = above;
381 * Special case, place the chain in the next most-recent layer as the
382 * specified layer, inserting a layer inbetween if necessary.
385 KKASSERT((flags & HAMMER2_CHAIN_INSERT_RACE) == 0);
386 nlayer = TAILQ_PREV(layer, h2_layer_list, entry);
387 if (nlayer && RB_INSERT(hammer2_chain_tree,
388 &nlayer->rbtree, chain) == NULL) {
393 spin_unlock(&above->cst.spin);
394 KKASSERT((flags & HAMMER2_CHAIN_INSERT_LIVE) == 0);
395 nlayer = kmalloc(sizeof(*nlayer), chain->hmp->mchain,
397 RB_INIT(&nlayer->rbtree);
398 nlayer->good = 0xABCD;
399 spin_lock(&above->cst.spin);
401 TAILQ_INSERT_BEFORE(layer, nlayer, entry);
402 RB_INSERT(hammer2_chain_tree, &nlayer->rbtree, chain);
408 * Interlocked by spinlock, check for race
410 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
411 above->generation != generation) {
417 * Try to insert, allocate a new layer if a nominal collision
418 * occurs (a collision is different from a SMP race).
420 layer = TAILQ_FIRST(&above->layerq);
424 (xchain = RB_INSERT(hammer2_chain_tree,
425 &layer->rbtree, chain)) != NULL) {
428 * Allocate a new layer to resolve the issue.
430 spin_unlock(&above->cst.spin);
431 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
433 RB_INIT(&layer->rbtree);
434 layer->good = 0xABCD;
435 spin_lock(&above->cst.spin);
437 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
438 above->generation != generation) {
439 spin_unlock(&above->cst.spin);
440 kfree(layer, chain->hmp->mchain);
441 spin_lock(&above->cst.spin);
446 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
447 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
450 chain->inlayer = layer;
451 ++above->chain_count;
454 if ((flags & HAMMER2_CHAIN_INSERT_LIVE) &&
455 (chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
456 atomic_add_int(&above->live_count, 1);
458 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
460 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
461 spin_unlock(&above->cst.spin);
466 * Drop the caller's reference to the chain. When the ref count drops to
467 * zero this function will disassociate the chain from its parent and
468 * deallocate it, then recursely drop the parent using the implied ref
469 * from the chain's chain->parent.
471 * WARNING! Just because we are able to deallocate a chain doesn't mean
472 * that chain->core->rbtree is empty. There can still be a sharecnt
473 * on chain->core and RBTREE entries that refer to different parents.
475 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
476 struct h2_core_list *delayq);
479 hammer2_chain_drop(hammer2_chain_t *chain)
481 struct h2_core_list delayq;
482 hammer2_chain_t *scan;
486 if (hammer2_debug & 0x200000)
489 if (chain->flags & HAMMER2_CHAIN_MOVED)
491 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
493 KKASSERT(chain->refs > need);
503 chain = hammer2_chain_lastdrop(chain, &delayq);
505 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
507 /* retry the same chain */
511 * When we've exhausted lastdrop chaining pull off of delayq.
512 * chains on delayq are dead but are used to placehold other
513 * chains which we added a ref to for the purpose of dropping.
516 hammer2_mount_t *hmp;
518 if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
519 chain = (void *)scan->data;
520 TAILQ_REMOVE(&delayq, scan, core_entry);
521 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
524 kfree(scan, hmp->mchain);
531 * Safe handling of the 1->0 transition on chain. Returns a chain for
532 * recursive drop or NULL, possibly returning the same chain if the atomic
535 * Whem two chains need to be recursively dropped we use the chain
536 * we would otherwise free to placehold the additional chain. It's a bit
537 * convoluted but we can't just recurse without potentially blowing out
540 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
544 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
546 hammer2_pfsmount_t *pmp;
547 hammer2_mount_t *hmp;
548 hammer2_chain_core_t *above;
549 hammer2_chain_core_t *core;
550 hammer2_chain_layer_t *layer;
551 hammer2_chain_t *rdrop1;
552 hammer2_chain_t *rdrop2;
555 * Spinlock the core and check to see if it is empty. If it is
556 * not empty we leave chain intact with refs == 0. The elements
557 * in core->rbtree are associated with other chains contemporary
558 * with ours but not with our chain directly.
560 if ((core = chain->core) != NULL) {
561 spin_lock(&core->cst.spin);
564 * We can't free chains with children because there might
565 * be a flush dependency.
567 * NOTE: We return (chain) on failure to retry.
569 if (core->chain_count) {
570 if (atomic_cmpset_int(&chain->refs, 1, 0))
571 chain = NULL; /* success */
572 spin_unlock(&core->cst.spin);
575 /* no chains left under us */
578 * Because various parts of the code, including the inode
579 * structure, might be holding a stale chain and need to
580 * iterate to a non-stale sibling, we cannot remove siblings
581 * unless they are at the head of chain.
583 * We can't free a live chain unless it is a the head
584 * of its ownerq. If we were to then the go-to chain
585 * would revert to the prior deleted chain.
587 if (TAILQ_FIRST(&core->ownerq) != chain) {
588 if (atomic_cmpset_int(&chain->refs, 1, 0))
589 chain = NULL; /* success */
590 spin_unlock(&core->cst.spin);
596 * chain->core has no children left so no accessors can get to our
597 * chain from there. Now we have to lock the above core to interlock
598 * remaining possible accessors that might bump chain's refs before
599 * we can safely drop chain's refs with intent to free the chain.
602 pmp = chain->pmp; /* can be NULL */
608 * Spinlock the parent and try to drop the last ref on chain.
609 * On success remove chain from its parent, otherwise return NULL.
611 * (normal core locks are top-down recursive but we define core
612 * spinlocks as bottom-up recursive, so this is safe).
614 if ((above = chain->above) != NULL) {
615 spin_lock(&above->cst.spin);
616 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
617 /* 1->0 transition failed */
618 spin_unlock(&above->cst.spin);
620 spin_unlock(&core->cst.spin);
621 return(chain); /* retry */
625 * 1->0 transition successful, remove chain from its
626 * above core. Track layer for removal/freeing.
628 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
629 layer = chain->inlayer;
630 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
631 --above->chain_count;
632 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
634 chain->inlayer = NULL;
636 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
637 TAILQ_REMOVE(&above->layerq, layer, entry);
643 * If our chain was the last chain in the parent's core the
644 * core is now empty and its parents might now be droppable.
645 * Try to drop the first multi-homed parent by gaining a
646 * ref on it here and then dropping it below.
648 if (above->chain_count == 0) {
649 rdrop1 = TAILQ_FIRST(&above->ownerq);
651 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
655 spin_unlock(&above->cst.spin);
656 above = NULL; /* safety */
660 * Successful 1->0 transition and the chain can be destroyed now.
662 * We still have the core spinlock (if core is non-NULL), and core's
663 * chain_count is 0. The above spinlock is gone.
665 * Remove chain from ownerq. Once core has no more owners (and no
666 * children which is already the case) we can destroy core.
668 * If core has more owners we may be able to continue a bottom-up
669 * drop with our next sibling.
674 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
675 rdrop2 = TAILQ_FIRST(&core->ownerq);
676 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
678 spin_unlock(&core->cst.spin);
681 * We can do the final 1->0 transition with an atomic op
682 * after releasing core's spinlock.
684 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
686 * On the 1->0 transition of core we can destroy
687 * it. Any remaining layers should no longer be
688 * referenced or visibile to other threads.
690 KKASSERT(TAILQ_EMPTY(&core->ownerq));
692 layer->good = 0xEF00;
693 kfree(layer, hmp->mchain);
695 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
696 KKASSERT(layer->refs == 0 &&
697 RB_EMPTY(&layer->rbtree));
698 TAILQ_REMOVE(&core->layerq, layer, entry);
699 layer->good = 0xEF01;
700 kfree(layer, hmp->mchain);
703 KKASSERT(core->cst.count == 0);
704 KKASSERT(core->cst.upgrade == 0);
706 kfree(core, hmp->mchain);
708 core = NULL; /* safety */
712 * All spin locks are gone, finish freeing stuff.
714 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
715 HAMMER2_CHAIN_MODIFIED)) == 0);
716 hammer2_chain_drop_data(chain, 1);
718 KKASSERT(chain->dio == NULL);
721 * Free saved empty layer and return chained drop.
724 layer->good = 0xEF02;
725 kfree(layer, hmp->mchain);
729 * Once chain resources are gone we can use the now dead chain
730 * structure to placehold what might otherwise require a recursive
731 * drop, because we have potentially two things to drop and can only
732 * return one directly.
734 if (rdrop1 && rdrop2) {
735 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
736 chain->data = (void *)rdrop1;
737 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
739 } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
740 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
742 kfree(chain, hmp->mchain);
745 atomic_add_long(&pmp->inmem_chains, -1);
746 hammer2_chain_memory_wakeup(pmp);
750 * Either or both can be NULL. We already handled the case where
751 * both might not have been NULL.
760 * On either last lock release or last drop
763 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
765 hammer2_mount_t *hmp = chain->hmp;
767 switch(chain->bref.type) {
768 case HAMMER2_BREF_TYPE_VOLUME:
769 case HAMMER2_BREF_TYPE_FREEMAP:
773 case HAMMER2_BREF_TYPE_INODE:
775 kfree(chain->data, hmp->mchain);
779 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
781 kfree(chain->data, hmp->mchain);
786 KKASSERT(chain->data == NULL);
792 * Ref and lock a chain element, acquiring its data with I/O if necessary,
793 * and specify how you would like the data to be resolved.
795 * Returns 0 on success or an error code if the data could not be acquired.
796 * The chain element is locked on return regardless of whether an error
799 * The lock is allowed to recurse, multiple locking ops will aggregate
800 * the requested resolve types. Once data is assigned it will not be
801 * removed until the last unlock.
803 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
804 * (typically used to avoid device/logical buffer
807 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
808 * the INITIAL-create state (indirect blocks only).
810 * Do not resolve data elements for DATA chains.
811 * (typically used to avoid device/logical buffer
814 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
816 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
817 * it will be locked exclusive.
819 * NOTE: Embedded elements (volume header, inodes) are always resolved
822 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
823 * element will instantiate and zero its buffer, and flush it on
826 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
827 * so as not to instantiate a device buffer, which could alias against
828 * a logical file buffer. However, if ALWAYS is specified the
829 * device buffer will be instantiated anyway.
831 * WARNING! If data must be fetched a shared lock will temporarily be
832 * upgraded to exclusive. However, a deadlock can occur if
833 * the caller owns more than one shared lock.
836 hammer2_chain_lock(hammer2_chain_t *chain, int how)
838 hammer2_mount_t *hmp;
839 hammer2_chain_core_t *core;
840 hammer2_blockref_t *bref;
846 * Ref and lock the element. Recursive locks are allowed.
848 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
849 hammer2_chain_ref(chain);
850 atomic_add_int(&chain->lockcnt, 1);
853 KKASSERT(hmp != NULL);
856 * Get the appropriate lock.
859 if (how & HAMMER2_RESOLVE_SHARED)
860 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
862 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
865 * If we already have a valid data pointer no further action is
872 * Do we have to resolve the data?
874 switch(how & HAMMER2_RESOLVE_MASK) {
875 case HAMMER2_RESOLVE_NEVER:
877 case HAMMER2_RESOLVE_MAYBE:
878 if (chain->flags & HAMMER2_CHAIN_INITIAL)
880 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
883 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
886 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
889 case HAMMER2_RESOLVE_ALWAYS:
894 * Upgrade to an exclusive lock so we can safely manipulate the
895 * buffer cache. If another thread got to it before us we
898 ostate = ccms_thread_lock_upgrade(&core->cst);
900 ccms_thread_lock_downgrade(&core->cst, ostate);
905 * We must resolve to a device buffer, either by issuing I/O or
906 * by creating a zero-fill element. We do not mark the buffer
907 * dirty when creating a zero-fill element (the hammer2_chain_modify()
908 * API must still be used to do that).
910 * The device buffer is variable-sized in powers of 2 down
911 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
912 * chunk always contains buffers of the same size. (XXX)
914 * The minimum physical IO size may be larger than the variable
920 * The getblk() optimization can only be used on newly created
921 * elements if the physical block size matches the request.
923 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
924 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
927 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
929 adjreadcounter(&chain->bref, chain->bytes);
933 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
934 (intmax_t)bref->data_off, error);
935 hammer2_io_bqrelse(&chain->dio);
936 ccms_thread_lock_downgrade(&core->cst, ostate);
941 * We can clear the INITIAL state now, we've resolved the buffer
942 * to zeros and marked it dirty with hammer2_io_new().
944 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
945 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
946 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
950 * Setup the data pointer, either pointing it to an embedded data
951 * structure and copying the data from the buffer, or pointing it
954 * The buffer is not retained when copying to an embedded data
955 * structure in order to avoid potential deadlocks or recursions
956 * on the same physical buffer.
958 switch (bref->type) {
959 case HAMMER2_BREF_TYPE_VOLUME:
960 case HAMMER2_BREF_TYPE_FREEMAP:
962 * Copy data from bp to embedded buffer
964 panic("hammer2_chain_lock: called on unresolved volume header");
966 case HAMMER2_BREF_TYPE_INODE:
968 * Copy data from dio to embedded buffer, do not retain the
971 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
972 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
973 chain->data = kmalloc(sizeof(chain->data->ipdata),
974 hmp->mchain, M_WAITOK | M_ZERO);
975 bcopy(bdata, &chain->data->ipdata, chain->bytes);
976 hammer2_io_bqrelse(&chain->dio);
978 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
979 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
980 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
981 chain->data = kmalloc(sizeof(chain->data->bmdata),
982 hmp->mchain, M_WAITOK | M_ZERO);
983 bcopy(bdata, &chain->data->bmdata, chain->bytes);
984 hammer2_io_bqrelse(&chain->dio);
986 case HAMMER2_BREF_TYPE_INDIRECT:
987 case HAMMER2_BREF_TYPE_DATA:
988 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
991 * Point data at the device buffer and leave bp intact.
993 chain->data = (void *)bdata;
996 ccms_thread_lock_downgrade(&core->cst, ostate);
1001 * This basically calls hammer2_io_breadcb() but does some pre-processing
1002 * of the chain first to handle certain cases.
1005 hammer2_chain_load_async(hammer2_chain_t *chain,
1006 void (*callback)(hammer2_io_t *dio,
1007 hammer2_chain_t *chain,
1008 void *arg_p, off_t arg_o),
1009 void *arg_p, off_t arg_o)
1011 hammer2_mount_t *hmp;
1012 struct hammer2_io *dio;
1013 hammer2_blockref_t *bref;
1017 callback(NULL, chain, arg_p, arg_o);
1022 * We must resolve to a device buffer, either by issuing I/O or
1023 * by creating a zero-fill element. We do not mark the buffer
1024 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1025 * API must still be used to do that).
1027 * The device buffer is variable-sized in powers of 2 down
1028 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1029 * chunk always contains buffers of the same size. (XXX)
1031 * The minimum physical IO size may be larger than the variable
1034 bref = &chain->bref;
1038 * The getblk() optimization can only be used on newly created
1039 * elements if the physical block size matches the request.
1041 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1042 chain->bytes == hammer2_devblksize(chain->bytes)) {
1043 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
1044 KKASSERT(error == 0);
1045 callback(dio, chain, arg_p, arg_o);
1050 * Otherwise issue a read
1052 adjreadcounter(&chain->bref, chain->bytes);
1053 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
1054 callback, chain, arg_p, arg_o);
1058 * Unlock and deref a chain element.
1060 * On the last lock release any non-embedded data (chain->dio) will be
1064 hammer2_chain_unlock(hammer2_chain_t *chain)
1066 hammer2_chain_core_t *core = chain->core;
1067 ccms_state_t ostate;
1072 * The core->cst lock can be shared across several chains so we
1073 * need to track the per-chain lockcnt separately.
1075 * If multiple locks are present (or being attempted) on this
1076 * particular chain we can just unlock, drop refs, and return.
1078 * Otherwise fall-through on the 1->0 transition.
1081 lockcnt = chain->lockcnt;
1082 KKASSERT(lockcnt > 0);
1085 if (atomic_cmpset_int(&chain->lockcnt,
1086 lockcnt, lockcnt - 1)) {
1087 ccms_thread_unlock(&core->cst);
1088 hammer2_chain_drop(chain);
1092 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1099 * On the 1->0 transition we upgrade the core lock (if necessary)
1100 * to exclusive for terminal processing. If after upgrading we find
1101 * that lockcnt is non-zero, another thread is racing us and will
1102 * handle the unload for us later on, so just cleanup and return
1103 * leaving the data/io intact
1105 * Otherwise if lockcnt is still 0 it is possible for it to become
1106 * non-zero and race, but since we hold the core->cst lock
1107 * exclusively all that will happen is that the chain will be
1108 * reloaded after we unload it.
1110 ostate = ccms_thread_lock_upgrade(&core->cst);
1111 if (chain->lockcnt) {
1112 ccms_thread_unlock_upgraded(&core->cst, ostate);
1113 hammer2_chain_drop(chain);
1118 * Shortcut the case if the data is embedded or not resolved.
1120 * Do NOT NULL out chain->data (e.g. inode data), it might be
1123 if (chain->dio == NULL) {
1124 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1125 hammer2_chain_drop_data(chain, 0);
1126 ccms_thread_unlock_upgraded(&core->cst, ostate);
1127 hammer2_chain_drop(chain);
1134 if (hammer2_io_isdirty(chain->dio) == 0) {
1136 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1137 switch(chain->bref.type) {
1138 case HAMMER2_BREF_TYPE_DATA:
1139 counterp = &hammer2_ioa_file_write;
1141 case HAMMER2_BREF_TYPE_INODE:
1142 counterp = &hammer2_ioa_meta_write;
1144 case HAMMER2_BREF_TYPE_INDIRECT:
1145 counterp = &hammer2_ioa_indr_write;
1147 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1148 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1149 counterp = &hammer2_ioa_fmap_write;
1152 counterp = &hammer2_ioa_volu_write;
1155 *counterp += chain->bytes;
1157 switch(chain->bref.type) {
1158 case HAMMER2_BREF_TYPE_DATA:
1159 counterp = &hammer2_iod_file_write;
1161 case HAMMER2_BREF_TYPE_INODE:
1162 counterp = &hammer2_iod_meta_write;
1164 case HAMMER2_BREF_TYPE_INDIRECT:
1165 counterp = &hammer2_iod_indr_write;
1167 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1168 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1169 counterp = &hammer2_iod_fmap_write;
1172 counterp = &hammer2_iod_volu_write;
1175 *counterp += chain->bytes;
1179 * Clean out the dio.
1181 * If a device buffer was used for data be sure to destroy the
1182 * buffer when we are done to avoid aliases (XXX what about the
1183 * underlying VM pages?).
1185 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1188 * NOTE: The isdirty check tracks whether we have to bdwrite() the
1189 * buffer or not. The buffer might already be dirty. The
1190 * flag is re-set when chain_modify() is called, even if
1191 * MODIFIED is already set, allowing the OS to retire the
1192 * buffer independent of a hammer2 flush.
1195 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
1196 hammer2_io_isdirty(chain->dio)) {
1197 hammer2_io_bawrite(&chain->dio);
1199 hammer2_io_bqrelse(&chain->dio);
1201 ccms_thread_unlock_upgraded(&core->cst, ostate);
1202 hammer2_chain_drop(chain);
1206 * This counts the number of live blockrefs in a block array and
1207 * also calculates the point at which all remaining blockrefs are empty.
1208 * This routine can only be called on a live chain (DUPLICATED flag not set).
1210 * NOTE: Flag is not set until after the count is complete, allowing
1211 * callers to test the flag without holding the spinlock.
1213 * NOTE: If base is NULL the related chain is still in the INITIAL
1214 * state and there are no blockrefs to count.
1216 * NOTE: live_count may already have some counts accumulated due to
1217 * creation and deletion and could even be initially negative.
1220 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1221 hammer2_blockref_t *base, int count)
1223 hammer2_chain_core_t *core = chain->core;
1225 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
1227 spin_lock(&core->cst.spin);
1228 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1230 while (--count >= 0) {
1231 if (base[count].type)
1234 core->live_zero = count + 1;
1235 while (count >= 0) {
1236 if (base[count].type)
1237 atomic_add_int(&core->live_count, 1);
1241 core->live_zero = 0;
1243 /* else do not modify live_count */
1244 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1246 spin_unlock(&core->cst.spin);
1250 * Resize the chain's physical storage allocation in-place. This may
1251 * replace the passed-in chain with a new chain.
1253 * Chains can be resized smaller without reallocating the storage.
1254 * Resizing larger will reallocate the storage.
1256 * Must be passed an exclusively locked parent and chain, returns a new
1257 * exclusively locked chain at the same index and unlocks the old chain.
1258 * Flushes the buffer if necessary.
1260 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1261 * to avoid instantiating a device buffer that conflicts with the vnode
1262 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1263 * any chain-oriented bp would be a device buffer.
1265 * XXX return error if cannot resize.
1268 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1269 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1270 int nradix, int flags)
1272 hammer2_mount_t *hmp;
1273 hammer2_chain_t *chain;
1281 * Only data and indirect blocks can be resized for now.
1282 * (The volu root, inodes, and freemap elements use a fixed size).
1284 KKASSERT(chain != &hmp->vchain);
1285 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1286 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1289 * Nothing to do if the element is already the proper size
1291 obytes = chain->bytes;
1292 nbytes = 1U << nradix;
1293 if (obytes == nbytes)
1297 * Delete the old chain and duplicate it at the same (parent, index),
1298 * returning a new chain. This allows the old chain to still be
1299 * used by the flush code. The new chain will be returned in a
1302 * The parent does not have to be locked for the delete/duplicate call,
1303 * but is in this particular code path.
1305 * NOTE: If we are not crossing a synchronization point the
1306 * duplication code will simply reuse the existing chain
1309 hammer2_chain_delete_duplicate(trans, &chain, 0);
1312 * Relocate the block, even if making it smaller (because different
1313 * block sizes may be in different regions).
1315 hammer2_freemap_alloc(trans, chain, nbytes);
1316 chain->bytes = nbytes;
1317 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1318 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1321 * For now just support it on DATA chains (and not on indirect
1324 KKASSERT(chain->dio == NULL);
1328 * Make sure the chain is marked MOVED and propagate the update
1329 * to the root for flush.
1331 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1332 hammer2_chain_ref(chain);
1333 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1335 hammer2_chain_setsubmod(trans, chain);
1341 * Set a chain modified, making it read-write and duplicating it if necessary.
1342 * This function will assign a new physical block to the chain if necessary
1344 * Duplication of already-modified chains is possible when the modification
1345 * crosses a flush synchronization boundary.
1347 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1348 * level or the COW operation will not work.
1350 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1351 * run the data through the device buffers.
1353 * This function may return a different chain than was passed, in which case
1354 * the old chain will be unlocked and the new chain will be locked.
1356 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1358 hammer2_inode_data_t *
1359 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1360 hammer2_chain_t **chainp, int flags)
1362 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1363 hammer2_chain_modify(trans, chainp, flags);
1364 if (ip->chain != *chainp)
1365 hammer2_inode_repoint(ip, NULL, *chainp);
1367 vsetisdirty(ip->vp);
1368 return(&ip->chain->data->ipdata);
1372 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1375 hammer2_mount_t *hmp;
1376 hammer2_chain_t *chain;
1386 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP ||
1387 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1388 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1389 kprintf("trans %04jx/%08x MODIFY1 %p.%d [%08x] %016jx/%d %016jx C/D %016jx/%016jx\n",
1390 trans->sync_tid, trans->flags,
1391 chain, chain->bref.type, chain->flags,
1392 chain->bref.key, chain->bref.keybits,
1393 chain->bref.data_off,
1394 chain->modify_tid, chain->delete_tid);
1398 kprintf("MODIFY %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1401 * Data must be resolved if already assigned unless explicitly
1402 * flagged otherwise.
1404 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1405 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1406 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1407 hammer2_chain_unlock(chain);
1411 * data is not optional for freemap chains (we must always be sure
1412 * to copy the data on COW storage allocations).
1414 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1415 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1416 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1417 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1421 * Determine if a delete-duplicate is needed.
1423 * (a) Modify_tid is part of a prior flush
1424 * (b) Transaction is concurrent with a flush (has higher tid)
1425 * (c) and chain is not in the initial state (freshly created)
1426 * (d) and caller didn't request an in-place modification.
1428 * The freemap and volume header special chains are never D-Dd.
1430 if (chain->modify_tid != trans->sync_tid && /* cross boundary */
1431 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1432 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1433 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1434 hammer2_chain_delete_duplicate(trans, chainp, 0);
1437 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP ||
1438 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1439 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1440 kprintf("trans %04jx/%08x MODIFY2 %p.%d [%08x] %016jx/%d %016jx\n",
1441 trans->sync_tid, trans->flags,
1442 chain, chain->bref.type, chain->flags,
1443 chain->bref.key, chain->bref.keybits,
1444 chain->bref.data_off);
1451 * Fall through if fchain or vchain, clearing the CHAIN_FLUSHED
1452 * flag. Basically other chains are delete-duplicated and so
1453 * the duplicated chains of course will not have the FLUSHED
1454 * flag set, but fchain and vchain are special-cased and the
1455 * flag must be cleared when changing modify_tid.
1457 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FLUSHED);
1461 * Otherwise do initial-chain handling
1463 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1464 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1465 hammer2_chain_ref(chain);
1469 * The modification or re-modification requires an allocation and
1472 * We normally always allocate new storage here. If storage exists
1473 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1475 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1476 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1477 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1478 chain->modify_tid != trans->sync_tid)
1480 hammer2_freemap_alloc(trans, chain, chain->bytes);
1481 /* XXX failed allocation */
1482 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1483 hammer2_freemap_alloc(trans, chain, chain->bytes);
1484 /* XXX failed allocation */
1486 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1490 * Update modify_tid. XXX special-case vchain/fchain because they
1491 * are always modified in-place. Otherwise the chain being modified
1492 * must not be part of a future transaction.
1494 if (chain == &hmp->vchain || chain == &hmp->fchain) {
1495 if (chain->modify_tid <= trans->sync_tid)
1496 chain->modify_tid = trans->sync_tid;
1498 KKASSERT(chain->modify_tid <= trans->sync_tid);
1499 chain->modify_tid = trans->sync_tid;
1502 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1503 chain->bref.modify_tid = trans->sync_tid;
1506 * Do not COW if OPTDATA is set. INITIAL flag remains unchanged.
1507 * (OPTDATA does not prevent [re]allocation of storage, only the
1508 * related copy-on-write op).
1510 if (flags & HAMMER2_MODIFY_OPTDATA)
1514 * Clearing the INITIAL flag (for indirect blocks) indicates that
1515 * we've processed the uninitialized storage allocation.
1517 * If this flag is already clear we are likely in a copy-on-write
1518 * situation but we have to be sure NOT to bzero the storage if
1519 * no data is present.
1521 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1522 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1529 * Instantiate data buffer and possibly execute COW operation
1531 switch(chain->bref.type) {
1532 case HAMMER2_BREF_TYPE_VOLUME:
1533 case HAMMER2_BREF_TYPE_FREEMAP:
1534 case HAMMER2_BREF_TYPE_INODE:
1535 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1537 * The data is embedded, no copy-on-write operation is
1540 KKASSERT(chain->dio == NULL);
1542 case HAMMER2_BREF_TYPE_DATA:
1543 case HAMMER2_BREF_TYPE_INDIRECT:
1544 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1546 * Perform the copy-on-write operation
1548 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1551 error = hammer2_io_new(hmp, chain->bref.data_off,
1552 chain->bytes, &dio);
1554 error = hammer2_io_bread(hmp, chain->bref.data_off,
1555 chain->bytes, &dio);
1557 adjreadcounter(&chain->bref, chain->bytes);
1558 KKASSERT(error == 0);
1560 bdata = hammer2_io_data(dio, chain->bref.data_off);
1563 * Copy or zero-fill on write depending on whether
1564 * chain->data exists or not and set the dirty state for
1565 * the new buffer. Retire the existing buffer.
1568 KKASSERT(chain->dio != NULL);
1569 if (chain->data != (void *)bdata) {
1570 bcopy(chain->data, bdata, chain->bytes);
1572 } else if (wasinitial == 0) {
1574 * We have a problem. We were asked to COW but
1575 * we don't have any data to COW with!
1577 panic("hammer2_chain_modify: having a COW %p\n",
1580 hammer2_io_brelse(&chain->dio);
1581 chain->data = (void *)bdata;
1583 hammer2_io_setdirty(dio); /* modified by bcopy above */
1586 panic("hammer2_chain_modify: illegal non-embedded type %d",
1593 kprintf("RET2 %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1595 hammer2_chain_setsubmod(trans, chain);
1599 * Mark the volume as having been modified. This short-cut version
1600 * does not have to lock the volume's chain, which allows the ioctl
1601 * code to make adjustments to connections without deadlocking. XXX
1603 * No ref is made on vchain when flagging it MODIFIED.
1606 hammer2_modify_volume(hammer2_mount_t *hmp)
1608 hammer2_voldata_lock(hmp);
1609 hammer2_voldata_unlock(hmp, 1);
1613 * This function returns the chain at the nearest key within the specified
1614 * range with the highest delete_tid. The core spinlock must be held on
1615 * call and the returned chain will be referenced but not locked.
1617 * The returned chain may or may not be in a deleted state. Note that
1618 * live chains have a delete_tid = MAX_TID.
1620 * This function will recurse through chain->rbtree as necessary and will
1621 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1622 * the iteration value is less than the current value of *key_nextp.
1624 * The caller should use (*key_nextp) to calculate the actual range of
1625 * the returned element, which will be (key_beg to *key_nextp - 1), because
1626 * there might be another element which is superior to the returned element
1629 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1630 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1631 * it will wind up being (key_end + 1).
1633 struct hammer2_chain_find_info {
1634 hammer2_chain_t *best;
1635 hammer2_key_t key_beg;
1636 hammer2_key_t key_end;
1637 hammer2_key_t key_next;
1640 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1641 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1645 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1646 hammer2_key_t key_beg, hammer2_key_t key_end)
1648 struct hammer2_chain_find_info info;
1649 hammer2_chain_layer_t *layer;
1652 info.key_beg = key_beg;
1653 info.key_end = key_end;
1654 info.key_next = *key_nextp;
1656 KKASSERT(parent->core->good == 0x1234);
1657 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1658 KKASSERT(layer->good == 0xABCD);
1659 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1660 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1663 *key_nextp = info.key_next;
1665 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1666 parent, key_beg, key_end, *key_nextp);
1674 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1676 struct hammer2_chain_find_info *info = data;
1677 hammer2_key_t child_beg;
1678 hammer2_key_t child_end;
1680 child_beg = child->bref.key;
1681 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1683 if (child_end < info->key_beg)
1685 if (child_beg > info->key_end)
1692 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1694 struct hammer2_chain_find_info *info = data;
1695 hammer2_chain_t *best;
1696 hammer2_key_t child_end;
1699 * WARNING! Do not discard DUPLICATED chains, it is possible that
1700 * we are catching an insertion half-way done. If a
1701 * duplicated chain turns out to be the best choice the
1702 * caller will re-check its flags after locking it.
1704 * WARNING! Layerq is scanned forwards, exact matches should keep
1705 * the existing info->best.
1707 if ((best = info->best) == NULL) {
1709 * No previous best. Assign best
1712 } else if (best->bref.key <= info->key_beg &&
1713 child->bref.key <= info->key_beg) {
1715 * If our current best is flush with key_beg and child is
1716 * also flush with key_beg choose based on delete_tid.
1718 * key_next will automatically be limited to the smaller of
1719 * the two end-points.
1721 if (child->delete_tid > best->delete_tid)
1723 } else if (child->bref.key < best->bref.key) {
1725 * Child has a nearer key and best is not flush with key_beg.
1726 * Truncate key_next to the old best key iff it had a better
1730 if (best->delete_tid >= child->delete_tid &&
1731 (info->key_next > best->bref.key || info->key_next == 0))
1732 info->key_next = best->bref.key;
1733 } else if (child->bref.key == best->bref.key) {
1735 * If our current best is flush with the child then choose
1736 * based on delete_tid.
1738 * key_next will automatically be limited to the smaller of
1739 * the two end-points.
1741 if (child->delete_tid > best->delete_tid)
1745 * Keep the current best but truncate key_next to the child's
1746 * base iff the child has a higher delete_tid.
1748 * key_next will also automatically be limited to the smaller
1749 * of the two end-points (probably not necessary for this case
1750 * but we do it anyway).
1752 if (child->delete_tid >= best->delete_tid &&
1753 (info->key_next > child->bref.key || info->key_next == 0))
1754 info->key_next = child->bref.key;
1758 * Always truncate key_next based on child's end-of-range.
1760 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1761 if (child_end && (info->key_next > child_end || info->key_next == 0))
1762 info->key_next = child_end;
1768 * Retrieve the specified chain from a media blockref, creating the
1769 * in-memory chain structure which reflects it. modify_tid will be
1770 * left 0 which forces any modifications to issue a delete-duplicate.
1772 * To handle insertion races pass the INSERT_RACE flag along with the
1773 * generation number of the core. NULL will be returned if the generation
1774 * number changes before we have a chance to insert the chain. Insert
1775 * races can occur because the parent might be held shared.
1777 * Caller must hold the parent locked shared or exclusive since we may
1778 * need the parent's bref array to find our block.
1781 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref,
1784 hammer2_mount_t *hmp = parent->hmp;
1785 hammer2_chain_core_t *above = parent->core;
1786 hammer2_chain_t *chain;
1790 * Allocate a chain structure representing the existing media
1791 * entry. Resulting chain has one ref and is not locked.
1793 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1794 chain->dst_reason = 100;
1795 hammer2_chain_core_alloc(NULL, chain, NULL);
1796 /* ref'd chain returned */
1797 chain->modify_tid = chain->bref.mirror_tid;
1800 * Link the chain into its parent. A spinlock is required to safely
1801 * access the RBTREE, and it is possible to collide with another
1802 * hammer2_chain_get() operation because the caller might only hold
1803 * a shared lock on the parent.
1805 KKASSERT(parent->refs > 0);
1806 error = hammer2_chain_insert(above, NULL, chain,
1807 HAMMER2_CHAIN_INSERT_SPIN |
1808 HAMMER2_CHAIN_INSERT_RACE,
1811 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1812 kprintf("chain %p get race\n", chain);
1813 hammer2_chain_drop(chain);
1816 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1820 * Return our new chain referenced but not locked, or NULL if
1827 * Lookup initialization/completion API
1830 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1832 if (flags & HAMMER2_LOOKUP_SHARED) {
1833 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1834 HAMMER2_RESOLVE_SHARED);
1836 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1842 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1845 hammer2_chain_unlock(parent);
1850 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1852 hammer2_chain_t *oparent;
1853 hammer2_chain_t *bparent;
1854 hammer2_chain_t *nparent;
1855 hammer2_chain_core_t *above;
1858 above = oparent->above;
1860 spin_lock(&above->cst.spin);
1861 bparent = TAILQ_FIRST(&above->ownerq);
1862 hammer2_chain_ref(bparent);
1865 * Be careful of order, oparent must be unlocked before nparent
1866 * is locked below to avoid a deadlock. We might as well delay its
1867 * unlocking until we conveniently no longer have the spinlock (instead
1868 * of cycling the spinlock).
1870 * Theoretically our ref on bparent should prevent elements of the
1871 * following chain from going away and prevent above from going away,
1872 * but we still need the spinlock to safely scan the list.
1876 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1877 nparent = TAILQ_NEXT(nparent, core_entry);
1878 hammer2_chain_ref(nparent);
1879 spin_unlock(&above->cst.spin);
1882 hammer2_chain_unlock(oparent);
1885 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1886 hammer2_chain_drop(bparent);
1889 * We might have raced a delete-duplicate.
1891 if ((nparent->flags & HAMMER2_CHAIN_DUPLICATED) == 0)
1894 hammer2_chain_ref(bparent);
1895 hammer2_chain_unlock(nparent);
1896 spin_lock(&above->cst.spin);
1905 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1906 * (*parentp) typically points to an inode but can also point to a related
1907 * indirect block and this function will recurse upwards and find the inode
1910 * (*parentp) must be exclusively locked and referenced and can be an inode
1911 * or an existing indirect block within the inode.
1913 * On return (*parentp) will be modified to point at the deepest parent chain
1914 * element encountered during the search, as a helper for an insertion or
1915 * deletion. The new (*parentp) will be locked and referenced and the old
1916 * will be unlocked and dereferenced (no change if they are both the same).
1918 * The matching chain will be returned exclusively locked. If NOLOCK is
1919 * requested the chain will be returned only referenced.
1921 * NULL is returned if no match was found, but (*parentp) will still
1922 * potentially be adjusted.
1924 * On return (*key_nextp) will point to an iterative value for key_beg.
1925 * (If NULL is returned (*key_nextp) is set to key_end).
1927 * This function will also recurse up the chain if the key is not within the
1928 * current parent's range. (*parentp) can never be set to NULL. An iteration
1929 * can simply allow (*parentp) to float inside the loop.
1931 * NOTE! chain->data is not always resolved. By default it will not be
1932 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1933 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1934 * BREF_TYPE_DATA as the device buffer can alias the logical file
1938 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1939 hammer2_key_t key_beg, hammer2_key_t key_end,
1940 int *cache_indexp, int flags)
1942 hammer2_mount_t *hmp;
1943 hammer2_chain_t *parent;
1944 hammer2_chain_t *chain;
1945 hammer2_blockref_t *base;
1946 hammer2_blockref_t *bref;
1947 hammer2_blockref_t bcopy;
1948 hammer2_key_t scan_beg;
1949 hammer2_key_t scan_end;
1950 hammer2_chain_core_t *above;
1952 int how_always = HAMMER2_RESOLVE_ALWAYS;
1953 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1956 int maxloops = 300000;
1958 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1959 how_maybe = how_always;
1960 how = HAMMER2_RESOLVE_ALWAYS;
1961 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1962 how = HAMMER2_RESOLVE_NEVER;
1964 how = HAMMER2_RESOLVE_MAYBE;
1966 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1967 how_maybe |= HAMMER2_RESOLVE_SHARED;
1968 how_always |= HAMMER2_RESOLVE_SHARED;
1969 how |= HAMMER2_RESOLVE_SHARED;
1973 * Recurse (*parentp) upward if necessary until the parent completely
1974 * encloses the key range or we hit the inode.
1976 * This function handles races against the flusher doing a delete-
1977 * duplicate above us and re-homes the parent to the duplicate in
1978 * that case, otherwise we'd wind up recursing down a stale chain.
1983 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1984 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1985 scan_beg = parent->bref.key;
1986 scan_end = scan_beg +
1987 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1988 if (key_beg >= scan_beg && key_end <= scan_end)
1990 parent = hammer2_chain_getparent(parentp, how_maybe);
1994 if (--maxloops == 0)
1995 panic("hammer2_chain_lookup: maxloops");
1997 * Locate the blockref array. Currently we do a fully associative
1998 * search through the array.
2000 switch(parent->bref.type) {
2001 case HAMMER2_BREF_TYPE_INODE:
2003 * Special shortcut for embedded data returns the inode
2004 * itself. Callers must detect this condition and access
2005 * the embedded data (the strategy code does this for us).
2007 * This is only applicable to regular files and softlinks.
2009 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2010 if (flags & HAMMER2_LOOKUP_NOLOCK)
2011 hammer2_chain_ref(parent);
2013 hammer2_chain_lock(parent, how_always);
2014 *key_nextp = key_end + 1;
2017 base = &parent->data->ipdata.u.blockset.blockref[0];
2018 count = HAMMER2_SET_COUNT;
2020 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2021 case HAMMER2_BREF_TYPE_INDIRECT:
2023 * Handle MATCHIND on the parent
2025 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2026 scan_beg = parent->bref.key;
2027 scan_end = scan_beg +
2028 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2029 if (key_beg == scan_beg && key_end == scan_end) {
2031 hammer2_chain_lock(chain, how_maybe);
2032 *key_nextp = scan_end + 1;
2037 * Optimize indirect blocks in the INITIAL state to avoid
2040 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2043 if (parent->data == NULL)
2044 panic("parent->data is NULL");
2045 base = &parent->data->npdata[0];
2047 count = parent->bytes / sizeof(hammer2_blockref_t);
2049 case HAMMER2_BREF_TYPE_VOLUME:
2050 base = &hmp->voldata.sroot_blockset.blockref[0];
2051 count = HAMMER2_SET_COUNT;
2053 case HAMMER2_BREF_TYPE_FREEMAP:
2054 base = &hmp->voldata.freemap_blockset.blockref[0];
2055 count = HAMMER2_SET_COUNT;
2058 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2060 base = NULL; /* safety */
2061 count = 0; /* safety */
2065 * Merged scan to find next candidate.
2067 * hammer2_base_*() functions require the above->live_* fields
2068 * to be synchronized.
2070 * We need to hold the spinlock to access the block array and RB tree
2071 * and to interlock chain creation.
2073 above = parent->core;
2074 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2075 hammer2_chain_countbrefs(parent, base, count);
2080 spin_lock(&above->cst.spin);
2081 chain = hammer2_combined_find(parent, base, count,
2082 cache_indexp, key_nextp,
2083 key_beg, key_end, &bref);
2084 generation = above->generation;
2087 * Exhausted parent chain, iterate.
2090 spin_unlock(&above->cst.spin);
2091 if (key_beg == key_end) /* short cut single-key case */
2093 return (hammer2_chain_next(parentp, NULL, key_nextp,
2095 cache_indexp, flags));
2099 * Selected from blockref or in-memory chain.
2101 if (chain == NULL) {
2103 spin_unlock(&above->cst.spin);
2104 chain = hammer2_chain_get(parent, &bcopy, generation);
2105 if (chain == NULL) {
2106 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2107 parent, key_beg, key_end);
2110 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2111 hammer2_chain_drop(chain);
2115 hammer2_chain_ref(chain);
2116 spin_unlock(&above->cst.spin);
2120 * chain is referenced but not locked. We must lock the chain
2121 * to obtain definitive DUPLICATED/DELETED state
2123 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2124 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2125 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2127 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2131 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2133 * NOTE: Chain's key range is not relevant as there might be
2134 * one-offs within the range that are not deleted.
2136 * NOTE: Ignore the DUPLICATED flag, the lock above resolves
2137 * the chain's terminal state so if it is duplicated it
2138 * is virtually certain to be either deleted or live.
2140 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2141 hammer2_chain_unlock(chain);
2142 key_beg = *key_nextp;
2143 if (key_beg == 0 || key_beg > key_end)
2149 * If the chain element is an indirect block it becomes the new
2150 * parent and we loop on it. We must maintain our top-down locks
2151 * to prevent the flusher from interfering (i.e. doing a
2152 * delete-duplicate and leaving us recursing down a deleted chain).
2154 * The parent always has to be locked with at least RESOLVE_MAYBE
2155 * so we can access its data. It might need a fixup if the caller
2156 * passed incompatible flags. Be careful not to cause a deadlock
2157 * as a data-load requires an exclusive lock.
2159 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2160 * range is within the requested key range we return the indirect
2161 * block and do NOT loop. This is usually only used to acquire
2164 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2165 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2166 hammer2_chain_unlock(parent);
2167 *parentp = parent = chain;
2172 * All done, return the chain
2178 * After having issued a lookup we can iterate all matching keys.
2180 * If chain is non-NULL we continue the iteration from just after it's index.
2182 * If chain is NULL we assume the parent was exhausted and continue the
2183 * iteration at the next parent.
2185 * parent must be locked on entry and remains locked throughout. chain's
2186 * lock status must match flags. Chain is always at least referenced.
2188 * WARNING! The MATCHIND flag does not apply to this function.
2191 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2192 hammer2_key_t *key_nextp,
2193 hammer2_key_t key_beg, hammer2_key_t key_end,
2194 int *cache_indexp, int flags)
2196 hammer2_chain_t *parent;
2200 * Calculate locking flags for upward recursion.
2202 how_maybe = HAMMER2_RESOLVE_MAYBE;
2203 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2204 how_maybe |= HAMMER2_RESOLVE_SHARED;
2209 * Calculate the next index and recalculate the parent if necessary.
2212 key_beg = chain->bref.key +
2213 ((hammer2_key_t)1 << chain->bref.keybits);
2214 if (flags & HAMMER2_LOOKUP_NOLOCK)
2215 hammer2_chain_drop(chain);
2217 hammer2_chain_unlock(chain);
2220 * Any scan where the lookup returned degenerate data embedded
2221 * in the inode has an invalid index and must terminate.
2223 if (chain == parent)
2225 if (key_beg == 0 || key_beg > key_end)
2228 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2229 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2231 * We reached the end of the iteration.
2236 * Continue iteration with next parent unless the current
2237 * parent covers the range.
2239 key_beg = parent->bref.key +
2240 ((hammer2_key_t)1 << parent->bref.keybits);
2241 if (key_beg == 0 || key_beg > key_end)
2243 parent = hammer2_chain_getparent(parentp, how_maybe);
2249 return (hammer2_chain_lookup(parentp, key_nextp,
2251 cache_indexp, flags));
2255 * Raw scan functions are similar to lookup/next but do not seek the parent
2256 * chain and do not skip stale chains. These functions are primarily used
2257 * by the recovery code.
2259 * Parent and chain are locked, parent's data must be resolved. To acquire
2260 * the first sub-chain under parent pass chain == NULL.
2263 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2264 int *cache_indexp, int flags)
2266 hammer2_mount_t *hmp;
2267 hammer2_blockref_t *base;
2268 hammer2_blockref_t *bref;
2269 hammer2_blockref_t bcopy;
2270 hammer2_chain_core_t *above;
2272 hammer2_key_t next_key;
2274 int how_always = HAMMER2_RESOLVE_ALWAYS;
2275 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2278 int maxloops = 300000;
2283 * Scan flags borrowed from lookup
2285 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2286 how_maybe = how_always;
2287 how = HAMMER2_RESOLVE_ALWAYS;
2288 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2289 how = HAMMER2_RESOLVE_NEVER;
2291 how = HAMMER2_RESOLVE_MAYBE;
2293 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2294 how_maybe |= HAMMER2_RESOLVE_SHARED;
2295 how_always |= HAMMER2_RESOLVE_SHARED;
2296 how |= HAMMER2_RESOLVE_SHARED;
2300 * Calculate key to locate first/next element, unlocking the previous
2301 * element as we go. Be careful, the key calculation can overflow.
2304 key = chain->bref.key +
2305 ((hammer2_key_t)1 << chain->bref.keybits);
2306 hammer2_chain_unlock(chain);
2315 if (--maxloops == 0)
2316 panic("hammer2_chain_scan: maxloops");
2318 * Locate the blockref array. Currently we do a fully associative
2319 * search through the array.
2321 switch(parent->bref.type) {
2322 case HAMMER2_BREF_TYPE_INODE:
2324 * An inode with embedded data has no sub-chains.
2326 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2328 base = &parent->data->ipdata.u.blockset.blockref[0];
2329 count = HAMMER2_SET_COUNT;
2331 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2332 case HAMMER2_BREF_TYPE_INDIRECT:
2334 * Optimize indirect blocks in the INITIAL state to avoid
2337 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2340 if (parent->data == NULL)
2341 panic("parent->data is NULL");
2342 base = &parent->data->npdata[0];
2344 count = parent->bytes / sizeof(hammer2_blockref_t);
2346 case HAMMER2_BREF_TYPE_VOLUME:
2347 base = &hmp->voldata.sroot_blockset.blockref[0];
2348 count = HAMMER2_SET_COUNT;
2350 case HAMMER2_BREF_TYPE_FREEMAP:
2351 base = &hmp->voldata.freemap_blockset.blockref[0];
2352 count = HAMMER2_SET_COUNT;
2355 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2357 base = NULL; /* safety */
2358 count = 0; /* safety */
2362 * Merged scan to find next candidate.
2364 * hammer2_base_*() functions require the above->live_* fields
2365 * to be synchronized.
2367 * We need to hold the spinlock to access the block array and RB tree
2368 * and to interlock chain creation.
2370 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2371 hammer2_chain_countbrefs(parent, base, count);
2373 above = parent->core;
2375 spin_lock(&above->cst.spin);
2376 chain = hammer2_combined_find(parent, base, count,
2377 cache_indexp, &next_key,
2378 key, HAMMER2_MAX_KEY, &bref);
2379 generation = above->generation;
2382 * Exhausted parent chain, we're done.
2385 spin_unlock(&above->cst.spin);
2386 KKASSERT(chain == NULL);
2391 * Selected from blockref or in-memory chain.
2393 if (chain == NULL) {
2395 spin_unlock(&above->cst.spin);
2396 chain = hammer2_chain_get(parent, &bcopy, generation);
2397 if (chain == NULL) {
2398 kprintf("retry scan parent %p keys %016jx\n",
2402 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2403 hammer2_chain_drop(chain);
2408 hammer2_chain_ref(chain);
2409 spin_unlock(&above->cst.spin);
2413 * chain is referenced but not locked. We must lock the chain
2414 * to obtain definitive DUPLICATED/DELETED state
2416 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2419 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2421 * NOTE: chain's key range is not relevant as there might be
2422 * one-offs within the range that are not deleted.
2424 * NOTE: XXX this could create problems with scans used in
2425 * situations other than mount-time recovery.
2427 * NOTE: Ignore the DUPLICATED flag, the lock above resolves
2428 * the chain's terminal state so if it is duplicated it
2429 * is virtually certain to be either deleted or live.
2431 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2432 hammer2_chain_unlock(chain);
2443 * All done, return the chain or NULL
2449 * Create and return a new hammer2 system memory structure of the specified
2450 * key, type and size and insert it under (*parentp). This is a full
2451 * insertion, based on the supplied key/keybits, and may involve creating
2452 * indirect blocks and moving other chains around via delete/duplicate.
2454 * (*parentp) must be exclusive locked and may be replaced on return
2455 * depending on how much work the function had to do.
2457 * (*chainp) usually starts out NULL and returns the newly created chain,
2458 * but if the caller desires the caller may allocate a disconnected chain
2459 * and pass it in instead. (It is also possible for the caller to use
2460 * chain_duplicate() to create a disconnected chain, manipulate it, then
2461 * pass it into this function to insert it).
2463 * This function should NOT be used to insert INDIRECT blocks. It is
2464 * typically used to create/insert inodes and data blocks.
2466 * Caller must pass-in an exclusively locked parent the new chain is to
2467 * be inserted under, and optionally pass-in a disconnected, exclusively
2468 * locked chain to insert (else we create a new chain). The function will
2469 * adjust (*parentp) as necessary, create or connect the chain, and
2470 * return an exclusively locked chain in *chainp.
2473 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2474 hammer2_chain_t **chainp,
2475 hammer2_key_t key, int keybits, int type, size_t bytes)
2477 hammer2_mount_t *hmp;
2478 hammer2_chain_t *chain;
2479 hammer2_chain_t *parent = *parentp;
2480 hammer2_chain_core_t *above;
2481 hammer2_blockref_t *base;
2482 hammer2_blockref_t dummy;
2486 int maxloops = 300000;
2488 above = parent->core;
2489 KKASSERT(ccms_thread_lock_owned(&above->cst));
2493 if (chain == NULL) {
2495 * First allocate media space and construct the dummy bref,
2496 * then allocate the in-memory chain structure. Set the
2497 * INITIAL flag for fresh chains which do not have embedded
2500 bzero(&dummy, sizeof(dummy));
2503 dummy.keybits = keybits;
2504 dummy.data_off = hammer2_getradix(bytes);
2505 dummy.methods = parent->bref.methods;
2506 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2507 chain->dst_reason = 101;
2508 hammer2_chain_core_alloc(trans, chain, NULL);
2511 * Lock the chain manually, chain_lock will load the chain
2512 * which we do NOT want to do. (note: chain->refs is set
2513 * to 1 by chain_alloc() for us, but lockcnt is not).
2516 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2520 * We do NOT set INITIAL here (yet). INITIAL is only
2521 * used for indirect blocks.
2523 * Recalculate bytes to reflect the actual media block
2526 bytes = (hammer2_off_t)1 <<
2527 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2528 chain->bytes = bytes;
2531 case HAMMER2_BREF_TYPE_VOLUME:
2532 case HAMMER2_BREF_TYPE_FREEMAP:
2533 panic("hammer2_chain_create: called with volume type");
2535 case HAMMER2_BREF_TYPE_INODE:
2536 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2537 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2538 chain->data = kmalloc(sizeof(chain->data->ipdata),
2539 hmp->mchain, M_WAITOK | M_ZERO);
2541 case HAMMER2_BREF_TYPE_INDIRECT:
2542 panic("hammer2_chain_create: cannot be used to"
2543 "create indirect block");
2545 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2546 panic("hammer2_chain_create: cannot be used to"
2547 "create freemap root or node");
2549 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2550 KKASSERT(bytes == sizeof(chain->data->bmdata));
2551 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2552 chain->data = kmalloc(sizeof(chain->data->bmdata),
2553 hmp->mchain, M_WAITOK | M_ZERO);
2555 case HAMMER2_BREF_TYPE_DATA:
2558 * leave chain->data NULL, set INITIAL
2560 KKASSERT(chain->data == NULL);
2561 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2566 * We are reattaching a chain that has been duplicated and
2567 * left disconnected under a DIFFERENT parent with potentially
2568 * different key/keybits.
2570 * The chain must be modified in the current transaction
2571 * (the duplication code should have done that for us),
2572 * and it's modify_tid should be greater than the parent's
2573 * bref.mirror_tid. This should cause it to be created under
2576 * If deleted in the same transaction, the create/delete TIDs
2577 * will be the same and effective the chain will not have
2578 * existed at all from the point of view of the parent.
2580 * Do NOT mess with the current state of the INITIAL flag.
2582 KKASSERT(chain->modify_tid > parent->bref.mirror_tid);
2583 KKASSERT(chain->modify_tid == trans->sync_tid);
2584 chain->bref.key = key;
2585 chain->bref.keybits = keybits;
2586 /* chain->modify_tid = chain->bref.mirror_tid; */
2587 KKASSERT(chain->above == NULL);
2591 * Calculate how many entries we have in the blockref array and
2592 * determine if an indirect block is required.
2595 if (--maxloops == 0)
2596 panic("hammer2_chain_create: maxloops");
2597 above = parent->core;
2599 switch(parent->bref.type) {
2600 case HAMMER2_BREF_TYPE_INODE:
2601 KKASSERT((parent->data->ipdata.op_flags &
2602 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2603 KKASSERT(parent->data != NULL);
2604 base = &parent->data->ipdata.u.blockset.blockref[0];
2605 count = HAMMER2_SET_COUNT;
2607 case HAMMER2_BREF_TYPE_INDIRECT:
2608 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2609 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2612 base = &parent->data->npdata[0];
2613 count = parent->bytes / sizeof(hammer2_blockref_t);
2615 case HAMMER2_BREF_TYPE_VOLUME:
2616 KKASSERT(parent->data != NULL);
2617 base = &hmp->voldata.sroot_blockset.blockref[0];
2618 count = HAMMER2_SET_COUNT;
2620 case HAMMER2_BREF_TYPE_FREEMAP:
2621 KKASSERT(parent->data != NULL);
2622 base = &hmp->voldata.freemap_blockset.blockref[0];
2623 count = HAMMER2_SET_COUNT;
2626 panic("hammer2_chain_create: unrecognized blockref type: %d",
2634 * Make sure we've counted the brefs
2636 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2637 hammer2_chain_countbrefs(parent, base, count);
2639 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2642 * If no free blockref could be found we must create an indirect
2643 * block and move a number of blockrefs into it. With the parent
2644 * locked we can safely lock each child in order to delete+duplicate
2645 * it without causing a deadlock.
2647 * This may return the new indirect block or the old parent depending
2648 * on where the key falls. NULL is returned on error.
2650 if (above->live_count == count) {
2651 hammer2_chain_t *nparent;
2653 nparent = hammer2_chain_create_indirect(trans, parent,
2656 if (nparent == NULL) {
2658 hammer2_chain_drop(chain);
2662 if (parent != nparent) {
2663 hammer2_chain_unlock(parent);
2664 parent = *parentp = nparent;
2670 * Link the chain into its parent. Later on we will have to set
2671 * the MOVED bit in situations where we don't mark the new chain
2672 * as being modified.
2674 if (chain->above != NULL)
2675 panic("hammer2: hammer2_chain_create: chain already connected");
2676 KKASSERT(chain->above == NULL);
2677 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2678 hammer2_chain_insert(above, NULL, chain,
2679 HAMMER2_CHAIN_INSERT_SPIN |
2680 HAMMER2_CHAIN_INSERT_LIVE,
2685 * Mark the newly created chain modified.
2687 * Device buffers are not instantiated for DATA elements
2688 * as these are handled by logical buffers.
2690 * Indirect and freemap node indirect blocks are handled
2691 * by hammer2_chain_create_indirect() and not by this
2694 * Data for all other bref types is expected to be
2695 * instantiated (INODE, LEAF).
2697 switch(chain->bref.type) {
2698 case HAMMER2_BREF_TYPE_DATA:
2699 hammer2_chain_modify(trans, &chain,
2700 HAMMER2_MODIFY_OPTDATA |
2701 HAMMER2_MODIFY_ASSERTNOCOPY);
2703 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2704 case HAMMER2_BREF_TYPE_INODE:
2705 hammer2_chain_modify(trans, &chain,
2706 HAMMER2_MODIFY_ASSERTNOCOPY);
2710 * Remaining types are not supported by this function.
2711 * In particular, INDIRECT and LEAF_NODE types are
2712 * handled by create_indirect().
2714 panic("hammer2_chain_create: bad type: %d",
2721 * When reconnecting a chain we must set MOVED and setsubmod
2722 * so the flush recognizes that it must update the bref in
2725 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2726 hammer2_chain_ref(chain);
2727 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2730 hammer2_chain_setsubmod(trans, chain);
2739 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2740 * the same core and media state as the orignal. The original *chainp is
2741 * unlocked and the replacement will be returned locked.
2743 * The old chain may or may not be in a DELETED state. This new chain will
2744 * be live (not deleted).
2746 * The new chain will be marked modified for the current transaction.
2748 * If (parent) is non-NULL then the new duplicated chain is inserted under
2751 * If (parent) is NULL then the new duplicated chain is not inserted anywhere,
2752 * similar to if it had just been chain_alloc()'d (suitable for passing into
2753 * hammer2_chain_create() after this function returns).
2755 * WARNING! This is not a snapshot. Changes made underneath either the old
2756 * or new chain will affect both.
2758 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2759 hammer2_chain_t *nchain);
2762 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2763 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2764 int snapshot, int duplicate_reason)
2766 hammer2_mount_t *hmp;
2767 hammer2_chain_t *parent;
2768 hammer2_chain_t *ochain;
2769 hammer2_chain_t *nchain;
2770 hammer2_chain_core_t *above;
2774 * We want nchain to be our go-to live chain, but ochain may be in
2775 * a MODIFIED state within the current flush synchronization segment.
2776 * Force any further modifications of ochain to do another COW
2777 * operation even if modify_tid indicates that one is not needed.
2779 * WARNING! We should never resolve DATA to device buffers
2780 * (XXX allow it if the caller did?), and since
2781 * we currently do not have the logical buffer cache
2782 * buffer in-hand to fix its cached physical offset
2783 * we also force the modify code to not COW it. XXX
2788 ochain->debug_reason += 0x10000;
2790 ochain->debug_reason += 0x100000;
2791 ochain->src_reason = duplicate_reason;
2793 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2796 * Now create a duplicate of the chain structure, associating
2797 * it with the same core, making it the same size, pointing it
2798 * to the same bref (the same media block).
2800 * Give the duplicate the same modify_tid that we previously
2801 * ensured was sufficiently advanced to trigger a block table
2802 * insertion on flush.
2804 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2805 * hammer2_chain_alloc()
2808 bref = &ochain->bref;
2810 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2811 nchain->dst_reason = 102;
2812 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2814 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2815 nchain->dst_reason = 103;
2817 nchain->debug_previous = ochain;
2818 hammer2_chain_core_alloc(trans, nchain, ochain);
2819 bytes = (hammer2_off_t)1 <<
2820 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2821 nchain->bytes = bytes;
2822 nchain->modify_tid = ochain->modify_tid;
2823 if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2824 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2827 * Fixup (copy) any embedded data. Non-embedded data relies on the
2828 * media block. We must unlock ochain before we can access nchain's
2829 * media block because they might share the same bp and deadlock if
2832 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2833 HAMMER2_RESOLVE_NOREF);
2834 hammer2_chain_dup_fixup(ochain, nchain);
2835 /* nchain has 1 ref */
2836 hammer2_chain_unlock(ochain);
2837 KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2838 ochain->data == NULL);
2841 * Place nchain in the modified state, instantiate media data
2842 * if necessary. Because modify_tid is already completely
2843 * synchronized this should not result in a delete-duplicate.
2845 * We want nchain at the target to look like a new insertion.
2846 * Forcing the modification to be INPLACE accomplishes this
2847 * because we get the same nchain with an updated modify_tid.
2849 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2850 hammer2_chain_modify(trans, &nchain,
2851 HAMMER2_MODIFY_OPTDATA |
2852 HAMMER2_MODIFY_NOREALLOC |
2853 HAMMER2_MODIFY_INPLACE);
2854 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2855 hammer2_chain_modify(trans, &nchain,
2856 HAMMER2_MODIFY_OPTDATA |
2857 HAMMER2_MODIFY_INPLACE);
2859 hammer2_chain_modify(trans, &nchain,
2860 HAMMER2_MODIFY_INPLACE);
2864 * If parent is not NULL the duplicated chain will be entered under
2865 * the parent and the MOVED bit set.
2867 * Having both chains locked is extremely important for atomicy.
2869 if (parentp && (parent = *parentp) != NULL) {
2870 above = parent->core;
2871 KKASSERT(ccms_thread_lock_owned(&above->cst));
2872 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2873 KKASSERT(parent->refs > 0);
2875 hammer2_chain_create(trans, parentp, &nchain,
2876 nchain->bref.key, nchain->bref.keybits,
2877 nchain->bref.type, nchain->bytes);
2880 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2881 hammer2_chain_ref(nchain);
2882 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2884 hammer2_chain_setsubmod(trans, nchain);
2889 * Unconditionally set MOVED to force the parent blockrefs to
2890 * update, and adjust update_hi below nchain so nchain's
2891 * blockrefs are updated with the new attachment.
2893 if (nchain->core->update_hi < trans->sync_tid) {
2894 spin_lock(&nchain->core->cst.spin);
2895 if (nchain->core->update_hi < trans->sync_tid)
2896 nchain->core->update_hi = trans->sync_tid;
2897 spin_unlock(&nchain->core->cst.spin);
2905 * Special in-place delete-duplicate sequence which does not require a
2906 * locked parent. (*chainp) is marked DELETED and atomically replaced
2907 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2908 * order to ensure that lookups do not race us.
2910 * If the old chain is already marked deleted the new chain will also be
2911 * marked deleted. This case can occur when an inode is removed from the
2912 * filesystem but programs still have an open descriptor to it, and during
2913 * flushes when the flush needs to operate on a chain that is deleted in
2914 * the live view but still alive in the flush view.
2916 * The new chain will be marked modified for the current transaction.
2919 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2922 hammer2_mount_t *hmp;
2923 hammer2_chain_t *ochain;
2924 hammer2_chain_t *nchain;
2925 hammer2_chain_core_t *above;
2928 if (hammer2_debug & 0x20000)
2932 * Note that we do not have to call setsubmod on ochain, calling it
2933 * on nchain is sufficient.
2938 ochain->debug_reason += 0x1000;
2939 ochain->src_reason = 99;
2940 if ((ochain->debug_reason & 0xF000) > 0x4000) {
2941 kprintf("ochain %p\n", ochain);
2944 if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2945 KKASSERT(ochain->data);
2949 * First create a duplicate of the chain structure.
2950 * (nchain is allocated with one ref).
2952 * In the case where nchain inherits ochains core, nchain is
2953 * effectively locked due to ochain being locked (and sharing the
2954 * core), until we can give nchain its own official ock.
2956 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2957 nchain->dst_reason = 104;
2958 nchain->debug_previous = ochain;
2959 if (flags & HAMMER2_DELDUP_RECORE)
2960 hammer2_chain_core_alloc(trans, nchain, NULL);
2962 hammer2_chain_core_alloc(trans, nchain, ochain);
2963 above = ochain->above;
2965 bytes = (hammer2_off_t)1 <<
2966 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2967 nchain->bytes = bytes;
2970 * Duplicate inherits ochain's live state including its modification
2971 * state. This function disposes of the original. Because we are
2972 * doing this in-place under the same parent the block array
2973 * inserted/deleted state does not change.
2975 * The caller isn't expected to make further modifications of ochain
2976 * but set the FORCECOW bit anyway, just in case it does. If ochain
2977 * was previously marked FORCECOW we also flag nchain FORCECOW
2978 * (used during hardlink splits).
2980 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2981 * hammer2_chain_alloc()
2983 nchain->data_count += ochain->data_count;
2984 nchain->inode_count += ochain->inode_count;
2985 atomic_set_int(&nchain->flags,
2986 ochain->flags & (HAMMER2_CHAIN_INITIAL |
2987 HAMMER2_CHAIN_FORCECOW));
2988 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2991 * Lock nchain so both chains are now locked (extremely important
2992 * for atomicy). Mark ochain deleted and reinsert into the topology
2993 * and insert nchain all in one go.
2995 * If the ochain is already deleted it is left alone and nchain
2996 * is inserted into the topology as a deleted chain. This is
2997 * important because it allows ongoing operations to be executed
2998 * on a deleted inode which still has open descriptors.
3000 * The deleted case can also occur when a flush delete-duplicates
3001 * a node which is being concurrently modified by ongoing operations
3002 * in a later transaction. This creates a problem because the flush
3003 * is intended to update blockrefs which then propagate, allowing
3004 * the original covering in-memory chains to be freed up. In this
3005 * situation the flush code does NOT free the original covering
3006 * chains and will re-apply them to successive copies.
3008 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
3009 hammer2_chain_dup_fixup(ochain, nchain);
3010 /* extra ref still present from original allocation */
3012 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
3013 spin_lock(&above->cst.spin);
3014 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
3017 * Ultimately nchain->modify_tid will be set to trans->sync_tid,
3018 * but we can't do that here because we want to call
3019 * hammer2_chain_modify() to reallocate the block (if necessary).
3021 nchain->modify_tid = ochain->modify_tid;
3023 if (ochain->flags & HAMMER2_CHAIN_DELETED) {
3025 * ochain was deleted
3027 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
3028 if (ochain->delete_tid > trans->sync_tid) {
3030 * delete-duplicate a chain deleted in a later
3031 * transaction. Only allowed on chains created
3032 * before or during the current transaction (flush
3033 * code should filter out chains created after the
3034 * current transaction).
3036 * To make this work is a bit of a hack. We convert
3037 * ochain's delete_tid to the current sync_tid and
3038 * create a nchain which sets up ochains original
3041 * This effectively forces ochain to flush as a
3042 * deletion and nchain as a creation. Thus MOVED
3043 * must be set in ochain (it should already be
3044 * set since it's original delete_tid could not
3045 * have been flushed yet). Since ochain's delete_tid
3046 * has been moved down to sync_tid, a re-flush at
3047 * sync_tid won't try to delete-duplicate ochain
3050 KKASSERT(ochain->modify_tid <= trans->sync_tid);
3051 nchain->delete_tid = ochain->delete_tid;
3052 ochain->delete_tid = trans->sync_tid;
3053 KKASSERT(ochain->flags & HAMMER2_CHAIN_MOVED);
3054 } else if (ochain->delete_tid == trans->sync_tid) {
3056 * ochain was deleted in the current transaction
3058 nchain->delete_tid = trans->sync_tid;
3061 * ochain was deleted in a prior transaction.
3062 * create and delete nchain in the current
3065 * (delete_tid might represent a deleted inode
3066 * which still has an open descriptor).
3068 nchain->delete_tid = trans->sync_tid;
3070 hammer2_chain_insert(above, ochain->inlayer, nchain, 0, 0);
3073 * ochain was not deleted, delete it in the current
3076 KKASSERT(trans->sync_tid >= ochain->modify_tid);
3077 ochain->delete_tid = trans->sync_tid;
3078 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
3079 atomic_add_int(&above->live_count, -1);
3080 hammer2_chain_insert(above, NULL, nchain,
3081 HAMMER2_CHAIN_INSERT_LIVE, 0);
3084 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3085 hammer2_chain_ref(ochain);
3086 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
3088 spin_unlock(&above->cst.spin);
3091 * ochain must be unlocked because ochain and nchain might share
3092 * a buffer cache buffer, so we need to release it so nchain can
3093 * potentially obtain it.
3095 hammer2_chain_unlock(ochain);
3098 * Finishing fixing up nchain. A new block will be allocated if
3099 * crossing a synchronization point (meta-data only).
3101 * Calling hammer2_chain_modify() will update modify_tid to
3102 * (typically) trans->sync_tid.
3104 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3105 hammer2_chain_modify(trans, &nchain,
3106 HAMMER2_MODIFY_OPTDATA |
3107 HAMMER2_MODIFY_NOREALLOC |
3108 HAMMER2_MODIFY_INPLACE);
3109 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3110 hammer2_chain_modify(trans, &nchain,
3111 HAMMER2_MODIFY_OPTDATA |
3112 HAMMER2_MODIFY_INPLACE);
3114 hammer2_chain_modify(trans, &nchain,
3115 HAMMER2_MODIFY_INPLACE);
3117 hammer2_chain_drop(nchain);
3120 * Unconditionally set MOVED to force the parent blockrefs to
3121 * update as the chain_modify() above won't necessarily do it.
3123 * Adjust update_hi below nchain so nchain's blockrefs are updated
3124 * with the new attachment.
3126 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3127 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
3128 hammer2_chain_ref(nchain);
3131 if (nchain->core->update_hi < trans->sync_tid) {
3132 spin_lock(&nchain->core->cst.spin);
3133 if (nchain->core->update_hi < trans->sync_tid)
3134 nchain->core->update_hi = trans->sync_tid;
3135 spin_unlock(&nchain->core->cst.spin);
3138 hammer2_chain_setsubmod(trans, nchain);
3143 * Helper function to fixup inodes. The caller procedure stack may hold
3144 * multiple locks on ochain if it represents an inode, preventing our
3145 * unlock from retiring its state to the buffer cache.
3147 * In this situation any attempt to access the buffer cache could result
3148 * either in stale data or a deadlock. Work around the problem by copying
3149 * the embedded data directly.
3153 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
3155 if (ochain->data == NULL)
3157 switch(ochain->bref.type) {
3158 case HAMMER2_BREF_TYPE_INODE:
3159 KKASSERT(nchain->data == NULL);
3160 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
3161 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
3162 ochain->hmp->mchain, M_WAITOK | M_ZERO);
3163 nchain->data->ipdata = ochain->data->ipdata;
3165 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3166 KKASSERT(nchain->data == NULL);
3167 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
3168 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
3169 ochain->hmp->mchain, M_WAITOK | M_ZERO);
3170 bcopy(ochain->data->bmdata,
3171 nchain->data->bmdata,
3172 sizeof(nchain->data->bmdata));
3180 * Create a snapshot of the specified {parent, ochain} with the specified
3181 * label. The originating hammer2_inode must be exclusively locked for
3184 * The ioctl code has already synced the filesystem.
3187 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
3188 hammer2_ioc_pfs_t *pfs)
3190 hammer2_mount_t *hmp;
3191 hammer2_chain_t *ochain = *ochainp;
3192 hammer2_chain_t *nchain;
3193 hammer2_inode_data_t *ipdata;
3194 hammer2_inode_t *nip;
3201 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
3202 pfs->name, ochain->refs, ochain->flags);
3204 name_len = strlen(pfs->name);
3205 lhc = hammer2_dirhash(pfs->name, name_len);
3208 opfs_clid = ochain->data->ipdata.pfs_clid;
3213 * Create the snapshot directory under the super-root
3215 * Set PFS type, generate a unique filesystem id, and generate
3216 * a cluster id. Use the same clid when snapshotting a PFS root,
3217 * which theoretically allows the snapshot to be used as part of
3218 * the same cluster (perhaps as a cache).
3220 * Copy the (flushed) ochain's blockref array. Theoretically we
3221 * could use chain_duplicate() but it becomes difficult to disentangle
3222 * the shared core so for now just brute-force it.
3228 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
3229 pfs->name, name_len, &nchain, &error);
3232 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
3233 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
3234 kern_uuidgen(&ipdata->pfs_fsid, 1);
3235 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
3236 ipdata->pfs_clid = opfs_clid;
3238 kern_uuidgen(&ipdata->pfs_clid, 1);
3239 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
3240 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
3242 hammer2_inode_unlock_ex(nip, nchain);
3248 * Create an indirect block that covers one or more of the elements in the
3249 * current parent. Either returns the existing parent with no locking or
3250 * ref changes or returns the new indirect block locked and referenced
3251 * and leaving the original parent lock/ref intact as well.
3253 * If an error occurs, NULL is returned and *errorp is set to the error.
3255 * The returned chain depends on where the specified key falls.
3257 * The key/keybits for the indirect mode only needs to follow three rules:
3259 * (1) That all elements underneath it fit within its key space and
3261 * (2) That all elements outside it are outside its key space.
3263 * (3) When creating the new indirect block any elements in the current
3264 * parent that fit within the new indirect block's keyspace must be
3265 * moved into the new indirect block.
3267 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3268 * keyspace the the current parent, but lookup/iteration rules will
3269 * ensure (and must ensure) that rule (2) for all parents leading up
3270 * to the nearest inode or the root volume header is adhered to. This
3271 * is accomplished by always recursing through matching keyspaces in
3272 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3274 * The current implementation calculates the current worst-case keyspace by
3275 * iterating the current parent and then divides it into two halves, choosing
3276 * whichever half has the most elements (not necessarily the half containing
3277 * the requested key).
3279 * We can also opt to use the half with the least number of elements. This
3280 * causes lower-numbered keys (aka logical file offsets) to recurse through
3281 * fewer indirect blocks and higher-numbered keys to recurse through more.
3282 * This also has the risk of not moving enough elements to the new indirect
3283 * block and being forced to create several indirect blocks before the element
3286 * Must be called with an exclusively locked parent.
3288 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3289 hammer2_key_t *keyp, int keybits,
3290 hammer2_blockref_t *base, int count);
3291 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3292 hammer2_key_t *keyp, int keybits,
3293 hammer2_blockref_t *base, int count);
3296 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3297 hammer2_key_t create_key, int create_bits,
3298 int for_type, int *errorp)
3300 hammer2_mount_t *hmp;
3301 hammer2_chain_core_t *above;
3302 hammer2_chain_core_t *icore;
3303 hammer2_blockref_t *base;
3304 hammer2_blockref_t *bref;
3305 hammer2_blockref_t bcopy;
3306 hammer2_chain_t *chain;
3307 hammer2_chain_t *ichain;
3308 hammer2_chain_t dummy;
3309 hammer2_key_t key = create_key;
3310 hammer2_key_t key_beg;
3311 hammer2_key_t key_end;
3312 hammer2_key_t key_next;
3313 int keybits = create_bits;
3320 int maxloops = 300000;
3323 * Calculate the base blockref pointer or NULL if the chain
3324 * is known to be empty. We need to calculate the array count
3325 * for RB lookups either way.
3329 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3330 above = parent->core;
3332 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3333 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3336 switch(parent->bref.type) {
3337 case HAMMER2_BREF_TYPE_INODE:
3338 count = HAMMER2_SET_COUNT;
3340 case HAMMER2_BREF_TYPE_INDIRECT:
3341 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3342 count = parent->bytes / sizeof(hammer2_blockref_t);
3344 case HAMMER2_BREF_TYPE_VOLUME:
3345 count = HAMMER2_SET_COUNT;
3347 case HAMMER2_BREF_TYPE_FREEMAP:
3348 count = HAMMER2_SET_COUNT;
3351 panic("hammer2_chain_create_indirect: "
3352 "unrecognized blockref type: %d",
3358 switch(parent->bref.type) {
3359 case HAMMER2_BREF_TYPE_INODE:
3360 base = &parent->data->ipdata.u.blockset.blockref[0];
3361 count = HAMMER2_SET_COUNT;
3363 case HAMMER2_BREF_TYPE_INDIRECT:
3364 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3365 base = &parent->data->npdata[0];
3366 count = parent->bytes / sizeof(hammer2_blockref_t);
3368 case HAMMER2_BREF_TYPE_VOLUME:
3369 base = &hmp->voldata.sroot_blockset.blockref[0];
3370 count = HAMMER2_SET_COUNT;
3372 case HAMMER2_BREF_TYPE_FREEMAP:
3373 base = &hmp->voldata.freemap_blockset.blockref[0];
3374 count = HAMMER2_SET_COUNT;
3377 panic("hammer2_chain_create_indirect: "
3378 "unrecognized blockref type: %d",
3386 * dummy used in later chain allocation (no longer used for lookups).
3388 bzero(&dummy, sizeof(dummy));
3389 dummy.delete_tid = HAMMER2_MAX_TID;
3392 * When creating an indirect block for a freemap node or leaf
3393 * the key/keybits must be fitted to static radix levels because
3394 * particular radix levels use particular reserved blocks in the
3397 * This routine calculates the key/radix of the indirect block
3398 * we need to create, and whether it is on the high-side or the
3401 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3402 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3403 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3406 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3411 * Normalize the key for the radix being represented, keeping the
3412 * high bits and throwing away the low bits.
3414 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3417 * How big should our new indirect block be? It has to be at least
3418 * as large as its parent.
3420 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3421 nbytes = HAMMER2_IND_BYTES_MIN;
3423 nbytes = HAMMER2_IND_BYTES_MAX;
3424 if (nbytes < count * sizeof(hammer2_blockref_t))
3425 nbytes = count * sizeof(hammer2_blockref_t);
3428 * Ok, create our new indirect block
3430 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3431 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3432 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3434 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3436 dummy.bref.key = key;
3437 dummy.bref.keybits = keybits;
3438 dummy.bref.data_off = hammer2_getradix(nbytes);
3439 dummy.bref.methods = parent->bref.methods;
3441 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3442 ichain->dst_reason = 105;
3443 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3444 hammer2_chain_core_alloc(trans, ichain, NULL);
3445 icore = ichain->core;
3446 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3447 hammer2_chain_drop(ichain); /* excess ref from alloc */
3450 * We have to mark it modified to allocate its block, but use
3451 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3452 * it won't be acted upon by the flush code.
3454 * XXX leave the node unmodified, depend on the update_hi
3455 * flush to assign and modify parent blocks.
3457 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3460 * Iterate the original parent and move the matching brefs into
3461 * the new indirect block.
3463 * XXX handle flushes.
3466 key_end = HAMMER2_MAX_KEY;
3468 spin_lock(&above->cst.spin);
3473 if (++loops > 100000) {
3474 spin_unlock(&above->cst.spin);
3475 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3476 reason, parent, base, count, key_next);
3480 * NOTE: spinlock stays intact, returned chain (if not NULL)
3481 * is not referenced or locked which means that we
3482 * cannot safely check its flagged / deletion status
3485 chain = hammer2_combined_find(parent, base, count,
3486 &cache_index, &key_next,
3489 generation = above->generation;
3492 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3495 * Skip keys that are not within the key/radix of the new
3496 * indirect block. They stay in the parent.
3498 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3499 (key ^ bref->key)) != 0) {
3500 goto next_key_spinlocked;
3504 * Load the new indirect block by acquiring the related
3505 * chains (potentially from media as it might not be
3506 * in-memory). Then move it to the new parent (ichain)
3507 * via DELETE-DUPLICATE.
3509 * chain is referenced but not locked. We must lock the
3510 * chain to obtain definitive DUPLICATED/DELETED state
3514 * Use chain already present in the RBTREE
3516 hammer2_chain_ref(chain);
3517 spin_unlock(&above->cst.spin);
3518 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3519 HAMMER2_RESOLVE_NOREF);
3522 * Get chain for blockref element. _get returns NULL
3523 * on insertion race.
3526 spin_unlock(&above->cst.spin);
3527 chain = hammer2_chain_get(parent, &bcopy, generation);
3528 if (chain == NULL) {
3530 spin_lock(&above->cst.spin);
3533 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3535 hammer2_chain_drop(chain);
3536 spin_lock(&above->cst.spin);
3539 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3540 HAMMER2_RESOLVE_NOREF);
3544 * This is always live so if the chain has been delete-
3545 * duplicated we raced someone and we have to retry.
3547 * NOTE: Ignore the DUPLICATED flag, the lock above resolves
3548 * the chain's terminal state so if it is duplicated it
3549 * is virtually certain to be either deleted or live.
3551 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3552 hammer2_chain_unlock(chain);
3557 * Shift the chain to the indirect block.
3559 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
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 (key_next == 0 || key_next > key_end)
3574 spin_unlock(&above->cst.spin);
3577 * Insert the new indirect block into the parent now that we've
3578 * cleared out some entries in the parent. We calculated a good
3579 * insertion index in the loop above (ichain->index).
3581 * We don't have to set MOVED here because we mark ichain modified
3582 * down below (so the normal modified -> flush -> set-moved sequence
3585 * The insertion shouldn't race as this is a completely new block
3586 * and the parent is locked.
3588 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3589 hammer2_chain_insert(above, NULL, ichain,
3590 HAMMER2_CHAIN_INSERT_SPIN |
3591 HAMMER2_CHAIN_INSERT_LIVE,
3595 * Mark the new indirect block modified after insertion, which
3596 * will propagate up through parent all the way to the root and
3597 * also allocate the physical block in ichain for our caller,
3598 * and assign ichain->data to a pre-zero'd space (because there
3599 * is not prior data to copy into it).
3601 * We have to set update_hi in ichain's flags manually so the
3602 * flusher knows it has to recurse through it to get to all of
3603 * our moved blocks, then call setsubmod() to set the bit
3606 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3607 if (ichain->core->update_hi < trans->sync_tid) {
3608 spin_lock(&ichain->core->cst.spin);
3609 if (ichain->core->update_hi < trans->sync_tid)
3610 ichain->core->update_hi = trans->sync_tid;
3611 spin_unlock(&ichain->core->cst.spin);
3613 hammer2_chain_setsubmod(trans, ichain);
3616 * Figure out what to return.
3618 if (~(((hammer2_key_t)1 << keybits) - 1) &
3619 (create_key ^ key)) {
3621 * Key being created is outside the key range,
3622 * return the original parent.
3624 hammer2_chain_unlock(ichain);
3627 * Otherwise its in the range, return the new parent.
3628 * (leave both the new and old parent locked).
3637 * Calculate the keybits and highside/lowside of the freemap node the
3638 * caller is creating.
3640 * This routine will specify the next higher-level freemap key/radix
3641 * representing the lowest-ordered set. By doing so, eventually all
3642 * low-ordered sets will be moved one level down.
3644 * We have to be careful here because the freemap reserves a limited
3645 * number of blocks for a limited number of levels. So we can't just
3646 * push indiscriminately.
3649 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3650 int keybits, hammer2_blockref_t *base, int count)
3652 hammer2_chain_core_t *above;
3653 hammer2_chain_t *chain;
3654 hammer2_blockref_t *bref;
3656 hammer2_key_t key_beg;
3657 hammer2_key_t key_end;
3658 hammer2_key_t key_next;
3662 int maxloops = 300000;
3665 above = parent->core;
3671 * Calculate the range of keys in the array being careful to skip
3672 * slots which are overridden with a deletion.
3675 key_end = HAMMER2_MAX_KEY;
3677 spin_lock(&above->cst.spin);
3680 if (--maxloops == 0) {
3681 panic("indkey_freemap shit %p %p:%d\n",
3682 parent, base, count);
3684 chain = hammer2_combined_find(parent, base, count,
3685 &cache_index, &key_next,
3686 key_beg, key_end, &bref);
3693 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3694 if (key_next == 0 || key_next > key_end)
3701 * Use the full live (not deleted) element for the scan
3702 * iteration. HAMMER2 does not allow partial replacements.
3704 * XXX should be built into hammer2_combined_find().
3706 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3708 if (keybits > bref->keybits) {
3710 keybits = bref->keybits;
3711 } else if (keybits == bref->keybits && bref->key < key) {
3718 spin_unlock(&above->cst.spin);
3721 * Return the keybits for a higher-level FREEMAP_NODE covering
3725 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3726 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3728 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3729 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3731 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3732 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3734 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3735 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3737 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3738 panic("hammer2_chain_indkey_freemap: level too high");
3741 panic("hammer2_chain_indkey_freemap: bad radix");
3750 * Calculate the keybits and highside/lowside of the indirect block the
3751 * caller is creating.
3754 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3755 int keybits, hammer2_blockref_t *base, int count)
3757 hammer2_chain_core_t *above;
3758 hammer2_blockref_t *bref;
3759 hammer2_chain_t *chain;
3760 hammer2_key_t key_beg;
3761 hammer2_key_t key_end;
3762 hammer2_key_t key_next;
3768 int maxloops = 300000;
3771 above = parent->core;
3776 * Calculate the range of keys in the array being careful to skip
3777 * slots which are overridden with a deletion. Once the scan
3778 * completes we will cut the key range in half and shift half the
3779 * range into the new indirect block.
3782 key_end = HAMMER2_MAX_KEY;
3784 spin_lock(&above->cst.spin);
3787 if (--maxloops == 0) {
3788 panic("indkey_freemap shit %p %p:%d\n",
3789 parent, base, count);
3791 chain = hammer2_combined_find(parent, base, count,
3792 &cache_index, &key_next,
3793 key_beg, key_end, &bref);
3800 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3801 if (key_next == 0 || key_next > key_end)
3808 * Use the full live (not deleted) element for the scan
3809 * iteration. HAMMER2 does not allow partial replacements.
3811 * XXX should be built into hammer2_combined_find().
3813 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3816 * Expand our calculated key range (key, keybits) to fit
3817 * the scanned key. nkeybits represents the full range
3818 * that we will later cut in half (two halves @ nkeybits - 1).
3821 if (nkeybits < bref->keybits) {
3822 if (bref->keybits > 64) {
3823 kprintf("bad bref chain %p bref %p\n",
3827 nkeybits = bref->keybits;
3829 while (nkeybits < 64 &&
3830 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3831 (key ^ bref->key)) != 0) {
3836 * If the new key range is larger we have to determine
3837 * which side of the new key range the existing keys fall
3838 * under by checking the high bit, then collapsing the
3839 * locount into the hicount or vise-versa.
3841 if (keybits != nkeybits) {
3842 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3853 * The newly scanned key will be in the lower half or the
3854 * upper half of the (new) key range.
3856 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3865 spin_unlock(&above->cst.spin);
3866 bref = NULL; /* now invalid (safety) */
3869 * Adjust keybits to represent half of the full range calculated
3870 * above (radix 63 max)
3875 * Select whichever half contains the most elements. Theoretically
3876 * we can select either side as long as it contains at least one
3877 * element (in order to ensure that a free slot is present to hold
3878 * the indirect block).
3880 if (hammer2_indirect_optimize) {
3882 * Insert node for least number of keys, this will arrange
3883 * the first few blocks of a large file or the first few
3884 * inodes in a directory with fewer indirect blocks when
3887 if (hicount < locount && hicount != 0)
3888 key |= (hammer2_key_t)1 << keybits;
3890 key &= ~(hammer2_key_t)1 << keybits;
3893 * Insert node for most number of keys, best for heavily
3896 if (hicount > locount)
3897 key |= (hammer2_key_t)1 << keybits;
3899 key &= ~(hammer2_key_t)1 << keybits;
3907 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3908 * set chain->delete_tid. The chain is not actually marked possibly-free
3909 * in the freemap until the deletion is completely flushed out (because
3910 * a flush which doesn't cover the entire deletion is flushing the deleted
3911 * chain as if it were live).
3913 * This function does NOT generate a modification to the parent. It
3914 * would be nearly impossible to figure out which parent to modify anyway.
3915 * Such modifications are handled top-down by the flush code and are
3916 * properly merged using the flush synchronization point.
3918 * The find/get code will properly overload the RBTREE check on top of
3919 * the bref check to detect deleted entries.
3921 * This function is NOT recursive. Any entity already pushed into the
3922 * chain (such as an inode) may still need visibility into its contents,
3923 * as well as the ability to read and modify the contents. For example,
3924 * for an unlinked file which is still open.
3926 * NOTE: This function does NOT set chain->modify_tid, allowing future
3927 * code to distinguish between live and deleted chains by testing
3928 * trans->sync_tid vs chain->modify_tid and chain->delete_tid.
3930 * NOTE: Deletions normally do not occur in the middle of a duplication
3931 * chain but we use a trick for hardlink migration that refactors
3932 * the originating inode without deleting it, so we make no assumptions
3936 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3938 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3941 * Nothing to do if already marked.
3943 if (chain->flags & HAMMER2_CHAIN_DELETED)
3947 * The setting of DELETED causes finds, lookups, and _next iterations
3948 * to no longer recognize the chain. RB_SCAN()s will still have
3949 * visibility (needed for flush serialization points).
3951 * We need the spinlock on the core whos RBTREE contains chain
3952 * to protect against races.
3954 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3955 spin_lock(&chain->above->cst.spin);
3957 KKASSERT(trans->sync_tid >= chain->modify_tid);
3958 chain->delete_tid = trans->sync_tid;
3959 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3960 atomic_add_int(&chain->above->live_count, -1);
3961 ++chain->above->generation;
3964 * We must set MOVED along with DELETED for the flush code to
3965 * recognize the operation and properly disconnect the chain
3968 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3969 hammer2_chain_ref(chain);
3970 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3972 spin_unlock(&chain->above->cst.spin);
3974 if (flags & HAMMER2_DELETE_WILLDUP)
3975 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
3977 hammer2_chain_setsubmod(trans, chain);
3981 * Called with the core spinlock held to check for freeable layers.
3982 * Used by the flush code. Layers can wind up not being freed due
3983 * to the temporary layer->refs count. This function frees up any
3984 * layers that were missed.
3987 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3988 hammer2_chain_core_t *core)
3990 hammer2_chain_layer_t *layer;
3991 hammer2_chain_layer_t *tmp;
3993 tmp = TAILQ_FIRST(&core->layerq);
3994 while ((layer = tmp) != NULL) {
3995 tmp = TAILQ_NEXT(tmp, entry);
3996 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
3997 TAILQ_REMOVE(&core->layerq, layer, entry);
4000 spin_unlock(&core->cst.spin);
4001 kfree(layer, hmp->mchain);
4002 spin_lock(&core->cst.spin);
4010 * Returns the index of the nearest element in the blockref array >= elm.
4011 * Returns (count) if no element could be found.
4013 * Sets *key_nextp to the next key for loop purposes but does not modify
4014 * it if the next key would be higher than the current value of *key_nextp.
4015 * Note that *key_nexp can overflow to 0, which should be tested by the
4018 * (*cache_indexp) is a heuristic and can be any value without effecting
4021 * The spin lock on the related chain must be held.
4024 hammer2_base_find(hammer2_chain_t *chain,
4025 hammer2_blockref_t *base, int count,
4026 int *cache_indexp, hammer2_key_t *key_nextp,
4027 hammer2_key_t key_beg, hammer2_key_t key_end)
4029 hammer2_chain_core_t *core = chain->core;
4030 hammer2_blockref_t *scan;
4031 hammer2_key_t scan_end;
4036 * Require the live chain's already have their core's counted
4037 * so we can optimize operations.
4039 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) ||
4040 core->flags & HAMMER2_CORE_COUNTEDBREFS);
4045 if (count == 0 || base == NULL)
4049 * Sequential optimization using *cache_indexp. This is the most
4052 * We can avoid trailing empty entries on live chains, otherwise
4053 * we might have to check the whole block array.
4057 if (chain->flags & HAMMER2_CHAIN_DUPLICATED)
4060 limit = core->live_zero;
4065 KKASSERT(i < count);
4071 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4078 * Search forwards, stop when we find a scan element which
4079 * encloses the key or until we know that there are no further
4083 if (scan->type != 0) {
4084 if (scan->key > key_beg)
4086 scan_end = scan->key +
4087 ((hammer2_key_t)1 << scan->keybits) - 1;
4088 if (scan_end >= key_beg)
4101 scan_end = scan->key +
4102 ((hammer2_key_t)1 << scan->keybits);
4103 if (scan_end && (*key_nextp > scan_end ||
4105 *key_nextp = scan_end;
4113 * Do a combined search and return the next match either from the blockref
4114 * array or from the in-memory chain. Sets *bresp to the returned bref in
4115 * both cases, or sets it to NULL if the search exhausted. Only returns
4116 * a non-NULL chain if the search matched from the in-memory chain.
4118 * Must be called with above's spinlock held. Spinlock remains held
4119 * through the operation.
4121 * The returned chain is not locked or referenced. Use the returned bref
4122 * to determine if the search exhausted or not.
4124 static hammer2_chain_t *
4125 hammer2_combined_find(hammer2_chain_t *parent,
4126 hammer2_blockref_t *base, int count,
4127 int *cache_indexp, hammer2_key_t *key_nextp,
4128 hammer2_key_t key_beg, hammer2_key_t key_end,
4129 hammer2_blockref_t **bresp)
4131 hammer2_blockref_t *bref;
4132 hammer2_chain_t *chain;
4135 *key_nextp = key_end + 1;
4136 i = hammer2_base_find(parent, base, count, cache_indexp,
4137 key_nextp, key_beg, key_end);
4138 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4143 if (i == count && chain == NULL) {
4145 return(chain); /* NULL */
4149 * Only chain matched
4152 bref = &chain->bref;
4157 * Only blockref matched.
4159 if (chain == NULL) {
4165 * Both in-memory and blockref match.
4167 * If they are both flush with the left hand side select the chain.
4168 * If their starts match select the chain.
4169 * Otherwise the nearer element wins.
4171 if (chain->bref.key <= key_beg && base[i].key <= key_beg) {
4172 bref = &chain->bref;
4175 if (chain->bref.key <= base[i].key) {
4176 bref = &chain->bref;
4184 * If the bref is out of bounds we've exhausted our search.
4187 if (bref->key > key_end) {
4197 * Locate the specified block array element and delete it. The element
4200 * The spin lock on the related chain must be held.
4202 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4203 * need to be adjusted when we commit the media change.
4206 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
4207 hammer2_blockref_t *base, int count,
4208 int *cache_indexp, hammer2_chain_t *child)
4210 hammer2_blockref_t *elm = &child->bref;
4211 hammer2_chain_core_t *core = parent->core;
4212 hammer2_key_t key_next;
4216 * Delete element. Expect the element to exist.
4218 * XXX see caller, flush code not yet sophisticated enough to prevent
4219 * re-flushed in some cases.
4221 key_next = 0; /* max range */
4222 i = hammer2_base_find(parent, base, count, cache_indexp,
4223 &key_next, elm->key, elm->key);
4224 if (i == count || base[i].type == 0 ||
4225 base[i].key != elm->key || base[i].keybits != elm->keybits) {
4226 panic("delete base %p element not found at %d/%d elm %p\n",
4227 base, i, count, elm);
4230 bzero(&base[i], sizeof(*base));
4231 base[i].mirror_tid = (intptr_t)parent;
4232 base[i].modify_tid = (intptr_t)child;
4233 base[i].check.debug.sync_tid = trans->sync_tid;
4236 * We can only optimize core->live_zero for live chains.
4238 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4239 if (core->live_zero == i + 1) {
4240 while (--i >= 0 && base[i].type == 0)
4242 core->live_zero = i + 1;
4248 * Insert the specified element. The block array must not already have the
4249 * element and must have space available for the insertion.
4251 * The spin lock on the related chain must be held.
4253 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4254 * need to be adjusted when we commit the media change.
4257 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
4258 hammer2_blockref_t *base, int count,
4259 int *cache_indexp, hammer2_chain_t *child)
4261 hammer2_blockref_t *elm = &child->bref;
4262 hammer2_chain_core_t *core = parent->core;
4263 hammer2_key_t key_next;
4272 * Insert new element. Expect the element to not already exist
4273 * unless we are replacing it.
4275 * XXX see caller, flush code not yet sophisticated enough to prevent
4276 * re-flushed in some cases.
4278 key_next = 0; /* max range */
4279 i = hammer2_base_find(parent, base, count, cache_indexp,
4280 &key_next, elm->key, elm->key);
4283 * Shortcut fill optimization, typical ordered insertion(s) may not
4286 KKASSERT(i >= 0 && i <= count);
4289 * We can only optimize core->live_zero for live chains.
4291 if (i == count && core->live_zero < count) {
4292 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4293 i = core->live_zero++;
4299 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4300 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4301 panic("insert base %p overlapping elements at %d elm %p\n",
4306 * Try to find an empty slot before or after.
4310 while (j > 0 || k < count) {
4312 if (j >= 0 && base[j].type == 0) {
4316 bcopy(&base[j+1], &base[j],
4317 (i - j - 1) * sizeof(*base));
4323 if (k < count && base[k].type == 0) {
4324 bcopy(&base[i], &base[i+1],
4325 (k - i) * sizeof(hammer2_blockref_t));
4329 * We can only update core->live_zero for live
4332 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4333 if (core->live_zero <= k)
4334 core->live_zero = k + 1;
4340 panic("hammer2_base_insert: no room!");
4347 for (l = 0; l < count; ++l) {
4349 key_next = base[l].key +
4350 ((hammer2_key_t)1 << base[l].keybits) - 1;
4354 while (++l < count) {
4356 if (base[l].key <= key_next)
4357 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4358 key_next = base[l].key +
4359 ((hammer2_key_t)1 << base[l].keybits) - 1;
4369 * Sort the blockref array for the chain. Used by the flush code to
4370 * sort the blockref[] array.
4372 * The chain must be exclusively locked AND spin-locked.
4374 typedef hammer2_blockref_t *hammer2_blockref_p;
4378 hammer2_base_sort_callback(const void *v1, const void *v2)
4380 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4381 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4384 * Make sure empty elements are placed at the end of the array
4386 if (bref1->type == 0) {
4387 if (bref2->type == 0)
4390 } else if (bref2->type == 0) {
4397 if (bref1->key < bref2->key)
4399 if (bref1->key > bref2->key)
4405 hammer2_base_sort(hammer2_chain_t *chain)
4407 hammer2_blockref_t *base;
4410 switch(chain->bref.type) {
4411 case HAMMER2_BREF_TYPE_INODE:
4413 * Special shortcut for embedded data returns the inode
4414 * itself. Callers must detect this condition and access
4415 * the embedded data (the strategy code does this for us).
4417 * This is only applicable to regular files and softlinks.
4419 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4421 base = &chain->data->ipdata.u.blockset.blockref[0];
4422 count = HAMMER2_SET_COUNT;
4424 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4425 case HAMMER2_BREF_TYPE_INDIRECT:
4427 * Optimize indirect blocks in the INITIAL state to avoid
4430 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4431 base = &chain->data->npdata[0];
4432 count = chain->bytes / sizeof(hammer2_blockref_t);
4434 case HAMMER2_BREF_TYPE_VOLUME:
4435 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4436 count = HAMMER2_SET_COUNT;
4438 case HAMMER2_BREF_TYPE_FREEMAP:
4439 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4440 count = HAMMER2_SET_COUNT;
4443 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4445 base = NULL; /* safety */
4446 count = 0; /* safety */
4448 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4454 * Chain memory management
4457 hammer2_chain_wait(hammer2_chain_t *chain)
4459 tsleep(chain, 0, "chnflw", 1);
4463 * Manage excessive memory resource use for chain and related
4467 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4470 while (pmp->inmem_chains > desiredvnodes / 10 &&
4471 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 2) {
4473 speedup_syncer(pmp->mp);
4474 pmp->inmem_waiting = 1;
4475 tsleep(&pmp->inmem_waiting, 0, "chnmem", hz);
4479 if (pmp->inmem_chains > desiredvnodes / 10 &&
4480 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 7 / 4) {
4481 speedup_syncer(pmp->mp);
4487 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4489 if (pmp->inmem_waiting &&
4490 (pmp->inmem_chains <= desiredvnodes / 10 ||
4491 pmp->inmem_chains <= pmp->mp->mnt_nvnodelistsize * 2)) {
4493 pmp->inmem_waiting = 0;
4494 wakeup(&pmp->inmem_waiting);
4500 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4504 switch(bref->type) {
4505 case HAMMER2_BREF_TYPE_DATA:
4506 counterp = &hammer2_iod_file_read;
4508 case HAMMER2_BREF_TYPE_INODE:
4509 counterp = &hammer2_iod_meta_read;
4511 case HAMMER2_BREF_TYPE_INDIRECT:
4512 counterp = &hammer2_iod_indr_read;
4514 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4515 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4516 counterp = &hammer2_iod_fmap_read;
4519 counterp = &hammer2_iod_volu_read;