2 * Copyright (c) 2011-2014 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * 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 hammer2_chain_t *hammer2_combined_find(
90 hammer2_chain_t *parent,
91 hammer2_blockref_t *base, int count,
92 int *cache_indexp, hammer2_key_t *key_nextp,
93 hammer2_key_t key_beg, hammer2_key_t key_end,
94 hammer2_blockref_t **bresp);
97 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
98 * overlap in the RB trees. Deleted chains are moved from rbtree to either
101 * Chains in delete-duplicate sequences can always iterate through core_entry
102 * to locate the live version of the chain.
104 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
107 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
109 hammer2_key_t c1_beg;
110 hammer2_key_t c1_end;
111 hammer2_key_t c2_beg;
112 hammer2_key_t c2_end;
115 * Compare chains. Overlaps are not supposed to happen and catch
116 * any software issues early we count overlaps as a match.
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 update_xhi starting at chain and moving upward. Stop early
146 * if we hit a PFS transition (PFS flush code will have to detect the case
147 * and perform an update within its own transaction). The transaction xid
148 * is only good within the current PFS.
150 * This controls top-down visibility for flushes. The child has just one
151 * 'above' core, but the core itself can be multi-homed with parents iterated
152 * via core->ownerq. The last parent is the 'live' parent (all others had to
153 * have been delete-duplicated). We always propagate upward through the live
156 * This function is not used during a flush (except when the flush is
157 * allocating which requires the live tree). The flush keeps track of its
160 * XXX SMP races. For now we do not allow concurrent transactions with
161 * different transaction ids and there should be no race, but if we do
162 * later on there will be a problem.
165 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
167 hammer2_chain_core_t *above;
169 if (chain->update_xhi < trans->sync_xid)
170 chain->update_xhi = trans->sync_xid;
172 while ((above = chain->above) != NULL) {
173 spin_lock(&above->cst.spin);
174 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
175 if (chain->update_xhi < trans->sync_xid)
176 chain->update_xhi = trans->sync_xid;
177 spin_unlock(&above->cst.spin);
182 * Allocate a new disconnected chain element representing the specified
183 * bref. chain->refs is set to 1 and the passed bref is copied to
184 * chain->bref. chain->bytes is derived from the bref.
186 * chain->core is NOT allocated and the media data and bp pointers are left
187 * NULL. The caller must call chain_core_alloc() to allocate or associate
188 * a core with the chain.
190 * chain->pmp inherits pmp unless the chain is an inode (other than the
193 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
196 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
197 hammer2_trans_t *trans, hammer2_blockref_t *bref)
199 hammer2_chain_t *chain;
200 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
203 * Construct the appropriate system structure.
206 case HAMMER2_BREF_TYPE_INODE:
207 case HAMMER2_BREF_TYPE_INDIRECT:
208 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
209 case HAMMER2_BREF_TYPE_DATA:
210 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
212 * Chain's are really only associated with the hmp but we
213 * maintain a pmp association for per-mount memory tracking
214 * purposes. The pmp can be NULL.
216 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
218 case HAMMER2_BREF_TYPE_VOLUME:
219 case HAMMER2_BREF_TYPE_FREEMAP:
221 panic("hammer2_chain_alloc volume type illegal for op");
224 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
229 * Initialize the new chain structure.
234 chain->bytes = bytes;
236 chain->flags = HAMMER2_CHAIN_ALLOCATED;
237 chain->delete_xid = HAMMER2_XID_MAX;
240 * Set the PFS boundary flag if this chain represents a PFS root.
242 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
243 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
246 * Set modify_xid if a transaction is creating the inode.
247 * Enforce update_xlo = 0 so nearby transactions do not think
248 * it has been flushed when it hasn't.
250 * NOTE: When loading a chain from backing store or creating a
251 * snapshot, trans will be NULL and the caller is responsible
252 * for setting these fields.
255 chain->modify_xid = trans->sync_xid;
256 chain->update_xlo = 0;
263 * Associate an existing core with the chain or allocate a new core.
265 * The core is not locked. No additional refs on the chain are made.
266 * (trans) must not be NULL if (core) is not NULL.
268 * When chains are delete-duplicated during flushes we insert nchain on
269 * the ownerq after ochain instead of at the end in order to give the
270 * drop code visibility in the correct order, otherwise drops can be missed.
273 hammer2_chain_core_alloc(hammer2_trans_t *trans,
274 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
276 hammer2_chain_core_t *core;
278 KKASSERT(nchain->core == NULL);
280 if (ochain == NULL) {
282 * Fresh core under nchain (no multi-homing of ochain's
285 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
287 TAILQ_INIT(&core->ownerq);
288 TAILQ_INIT(&core->dbq);
289 RB_INIT(&core->rbtree); /* live chains */
290 RB_INIT(&core->dbtree); /* deleted original (bmapped) chains */
294 ccms_cst_init(&core->cst, nchain);
295 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
298 * Propagate the PFSROOT flag which we set on all subdirs
299 * under the super-root.
301 atomic_set_int(&nchain->flags,
302 ochain->flags & HAMMER2_CHAIN_PFSROOT);
305 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
306 * ochain if nchain is not a snapshot.
308 * It is possible for the DUPLICATED flag to already be
309 * set when called via a flush operation because flush
310 * operations may have to work on elements with delete_xid's
311 * beyond the flush sync_xid. In this situation we must
312 * ensure that nchain is placed just after ochain in the
313 * ownerq and that the DUPLICATED flag is set on nchain so
314 * 'live' operations skip past it to the correct chain.
316 * The flusher understands the blockref synchronization state
317 * for any stale chains by observing bref.mirror_tid, which
318 * delete-duplicate replicates.
320 * WARNING! However, the case is disallowed when the flusher
321 * is allocating freemap space because this entails
322 * more than just adjusting a block table.
324 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
325 KKASSERT(trans->flags & HAMMER2_TRANS_ISFLUSH);
326 atomic_set_int(&nchain->flags,
327 HAMMER2_CHAIN_DUPLICATED);
329 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
330 atomic_set_int(&ochain->flags,
331 HAMMER2_CHAIN_DUPLICATED);
334 atomic_add_int(&core->sharecnt, 1);
336 spin_lock(&core->cst.spin);
340 * Maintain ordering for refactor test so we don't skip over
341 * a snapshot. Also, during flushes, delete-duplications
342 * for block-table updates can occur on ochains already
343 * deleted (delete-duplicated by a later transaction), or
344 * on forward-indexed ochains. We must properly insert
345 * nchain relative to ochain.
347 if (trans && trans->sync_xid < ochain->modify_xid) {
348 TAILQ_INSERT_BEFORE(ochain, nchain, core_entry);
350 TAILQ_INSERT_AFTER(&core->ownerq, ochain,
353 spin_unlock(&core->cst.spin);
358 * Add a reference to a chain element, preventing its destruction.
361 hammer2_chain_ref(hammer2_chain_t *chain)
363 atomic_add_int(&chain->refs, 1);
367 * Insert the chain in the core rbtree.
369 * Normal insertions are placed in the live rbtree. Insertion of a deleted
370 * chain is a special case used by the flush code that is placed on the
371 * unstaged deleted list to avoid confusing the live view.
373 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
374 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
375 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
379 hammer2_chain_insert(hammer2_chain_core_t *above,
380 hammer2_chain_t *ochain, hammer2_chain_t *nchain,
381 int flags, int generation)
383 hammer2_chain_t *xchain;
386 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
387 spin_lock(&above->cst.spin);
390 * Interlocked by spinlock, check for race
392 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
393 above->generation != generation) {
401 * XXX BMAPPED might not be handled correctly for ochain/nchain
402 * ordering in both DELETED cases (flush and non-flush-term),
403 * so delete-duplicate code.
405 if (nchain->flags & HAMMER2_CHAIN_DELETED) {
406 if (ochain && (ochain->flags & HAMMER2_CHAIN_BMAPPED)) {
407 if (ochain->flags & HAMMER2_CHAIN_ONDBTREE) {
408 RB_REMOVE(hammer2_chain_tree,
409 &above->dbtree, ochain);
410 atomic_clear_int(&ochain->flags,
411 HAMMER2_CHAIN_ONDBTREE);
412 TAILQ_INSERT_TAIL(&above->dbq,
414 atomic_set_int(&ochain->flags,
415 HAMMER2_CHAIN_ONDBQ);
417 /* clear BMAPPED (DBTREE, sometimes RBTREE) */
418 atomic_clear_int(&ochain->flags, HAMMER2_CHAIN_BMAPPED);
420 xchain = RB_INSERT(hammer2_chain_tree,
421 &above->dbtree, nchain);
422 KKASSERT(xchain == NULL);
423 atomic_set_int(&nchain->flags,
424 HAMMER2_CHAIN_ONDBTREE |
425 HAMMER2_CHAIN_BMAPPED);
427 TAILQ_INSERT_TAIL(&above->dbq, nchain, db_entry);
428 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONDBQ);
431 xchain = RB_INSERT(hammer2_chain_tree, &above->rbtree, nchain);
432 KASSERT(xchain == NULL,
433 ("hammer2_chain_insert: collision %p", nchain));
434 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
437 nchain->above = above;
438 ++above->chain_count;
442 * We have to keep track of the effective live-view blockref count
443 * so the create code knows when to push an indirect block.
445 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
446 atomic_add_int(&above->live_count, 1);
448 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
449 spin_unlock(&above->cst.spin);
454 * Drop the caller's reference to the chain. When the ref count drops to
455 * zero this function will try to disassociate the chain from its parent and
456 * deallocate it, then recursely drop the parent using the implied ref
457 * from the chain's chain->parent.
459 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
460 struct h2_core_list *delayq);
463 hammer2_chain_drop(hammer2_chain_t *chain)
465 struct h2_core_list delayq;
466 hammer2_chain_t *scan;
470 if (hammer2_debug & 0x200000)
473 if (chain->flags & HAMMER2_CHAIN_FLUSH_CREATE)
475 if (chain->flags & HAMMER2_CHAIN_FLUSH_DELETE)
477 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
479 KKASSERT(chain->refs > need);
489 chain = hammer2_chain_lastdrop(chain, &delayq);
491 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
493 /* retry the same chain */
497 * When we've exhausted lastdrop chaining pull off of delayq.
498 * chains on delayq are dead but are used to placehold other
499 * chains which we added a ref to for the purpose of dropping.
502 hammer2_mount_t *hmp;
504 if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
505 chain = (void *)scan->data;
506 TAILQ_REMOVE(&delayq, scan, core_entry);
507 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
510 kfree(scan, hmp->mchain);
517 * Safe handling of the 1->0 transition on chain. Returns a chain for
518 * recursive drop or NULL, possibly returning the same chain if the atomic
521 * Whem two chains need to be recursively dropped we use the chain
522 * we would otherwise free to placehold the additional chain. It's a bit
523 * convoluted but we can't just recurse without potentially blowing out
526 * The chain cannot be freed if it has a non-empty core (children) or
527 * it is not at the head of ownerq.
529 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
533 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
535 hammer2_pfsmount_t *pmp;
536 hammer2_mount_t *hmp;
537 hammer2_chain_core_t *above;
538 hammer2_chain_core_t *core;
539 hammer2_chain_t *rdrop1;
540 hammer2_chain_t *rdrop2;
543 * Spinlock the core and check to see if it is empty. If it is
544 * not empty we leave chain intact with refs == 0. The elements
545 * in core->rbtree are associated with other chains contemporary
546 * with ours but not with our chain directly.
548 if ((core = chain->core) != NULL) {
549 spin_lock(&core->cst.spin);
552 * We can't free non-stale chains with children until we are
553 * able to free the children because there might be a flush
554 * dependency. Flushes of stale children (which should also
555 * have their deleted flag set) short-cut recursive flush
556 * dependencies and can be freed here. Any flushes which run
557 * through stale children due to the flush synchronization
558 * point should have a FLUSH_* bit set in the chain and not
559 * reach lastdrop at this time.
561 * NOTE: We return (chain) on failure to retry.
563 if (core->chain_count &&
564 (chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
565 if (atomic_cmpset_int(&chain->refs, 1, 0))
566 chain = NULL; /* success */
567 spin_unlock(&core->cst.spin);
570 /* no chains left under us */
573 * Various parts of the code might be holding a ref on a
574 * stale chain as a placemarker which must be iterated to
575 * locate a later non-stale (live) chain. We must be sure
576 * NOT to free the later non-stale chain (which might have
577 * no refs). Otherwise mass confusion may result.
579 * The DUPLICATED flag tells us whether the chain is stale
580 * or not, so the rule is that any chain whos DUPLICATED flag
581 * is NOT set must also be at the head of the ownerq.
583 * Note that the DELETED flag is not involved. That is, a
584 * live chain can represent a deletion that has not yet been
585 * flushed (or still has refs).
588 if (TAILQ_NEXT(chain, core_entry) == NULL &&
589 TAILQ_FIRST(&core->ownerq) != chain) {
591 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 &&
592 TAILQ_FIRST(&core->ownerq) != chain) {
593 if (atomic_cmpset_int(&chain->refs, 1, 0))
594 chain = NULL; /* success */
595 spin_unlock(&core->cst.spin);
601 * chain->core has no children left so no accessors can get to our
602 * chain from there. Now we have to lock the above core to interlock
603 * remaining possible accessors that might bump chain's refs before
604 * we can safely drop chain's refs with intent to free the chain.
607 pmp = chain->pmp; /* can be NULL */
612 * Spinlock the parent and try to drop the last ref on chain.
613 * On success remove chain from its parent, otherwise return NULL.
615 * (normal core locks are top-down recursive but we define core
616 * spinlocks as bottom-up recursive, so this is safe).
618 if ((above = chain->above) != NULL) {
619 spin_lock(&above->cst.spin);
620 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
621 /* 1->0 transition failed */
622 spin_unlock(&above->cst.spin);
624 spin_unlock(&core->cst.spin);
625 return(chain); /* retry */
629 * 1->0 transition successful, remove chain from its
632 switch (chain->flags & (HAMMER2_CHAIN_ONRBTREE |
633 HAMMER2_CHAIN_ONDBTREE |
634 HAMMER2_CHAIN_ONDBQ)) {
635 case HAMMER2_CHAIN_ONRBTREE:
636 RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
637 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
639 case HAMMER2_CHAIN_ONDBTREE:
640 RB_REMOVE(hammer2_chain_tree, &above->dbtree, chain);
641 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
643 case HAMMER2_CHAIN_ONDBQ:
644 TAILQ_REMOVE(&above->dbq, chain, db_entry);
645 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
648 panic("hammer2_chain_lastdrop: chain %p badflags %08x",
649 chain, chain->flags);
653 --above->chain_count;
657 * If our chain was the last chain in the parent's core the
658 * core is now empty and its parents might now be droppable.
659 * Try to drop the first multi-homed parent by gaining a
660 * ref on it here and then dropping it below.
662 if (above->chain_count == 0) {
663 rdrop1 = TAILQ_FIRST(&above->ownerq);
665 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
669 spin_unlock(&above->cst.spin);
670 above = NULL; /* safety */
674 * Successful 1->0 transition and the chain can be destroyed now.
676 * We still have the core spinlock (if core is non-NULL), and core's
677 * chain_count is 0. The above spinlock is gone.
679 * Remove chain from ownerq. Once core has no more owners (and no
680 * children which is already the case) we can destroy core.
682 * If core has more owners we may be able to continue a bottom-up
683 * drop with our next sibling.
688 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
689 rdrop2 = TAILQ_FIRST(&core->ownerq);
690 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
692 spin_unlock(&core->cst.spin);
695 * We can do the final 1->0 transition with an atomic op
696 * after releasing core's spinlock.
698 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
700 * On the 1->0 transition of core we can destroy
703 KKASSERT(TAILQ_EMPTY(&core->ownerq));
704 KKASSERT(RB_EMPTY(&core->rbtree) &&
705 RB_EMPTY(&core->dbtree) &&
706 TAILQ_EMPTY(&core->dbq) &&
707 core->chain_count == 0);
708 KKASSERT(core->cst.count == 0);
709 KKASSERT(core->cst.upgrade == 0);
711 kfree(core, hmp->mchain);
713 core = NULL; /* safety */
717 * All spin locks are gone, finish freeing stuff.
719 KKASSERT((chain->flags & (HAMMER2_CHAIN_FLUSH_CREATE |
720 HAMMER2_CHAIN_FLUSH_DELETE |
721 HAMMER2_CHAIN_MODIFIED)) == 0);
722 hammer2_chain_drop_data(chain, 1);
724 KKASSERT(chain->dio == NULL);
727 * Once chain resources are gone we can use the now dead chain
728 * structure to placehold what might otherwise require a recursive
729 * drop, because we have potentially two things to drop and can only
730 * return one directly.
732 if (rdrop1 && rdrop2) {
733 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
734 chain->data = (void *)rdrop1;
735 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
737 } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
738 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
740 kfree(chain, hmp->mchain);
744 * Either or both can be NULL. We already handled the case where
745 * both might not have been NULL.
754 * On either last lock release or last drop
757 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
759 /*hammer2_mount_t *hmp = chain->hmp;*/
761 switch(chain->bref.type) {
762 case HAMMER2_BREF_TYPE_VOLUME:
763 case HAMMER2_BREF_TYPE_FREEMAP:
768 KKASSERT(chain->data == NULL);
774 * Ref and lock a chain element, acquiring its data with I/O if necessary,
775 * and specify how you would like the data to be resolved.
777 * Returns 0 on success or an error code if the data could not be acquired.
778 * The chain element is locked on return regardless of whether an error
781 * The lock is allowed to recurse, multiple locking ops will aggregate
782 * the requested resolve types. Once data is assigned it will not be
783 * removed until the last unlock.
785 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
786 * (typically used to avoid device/logical buffer
789 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
790 * the INITIAL-create state (indirect blocks only).
792 * Do not resolve data elements for DATA chains.
793 * (typically used to avoid device/logical buffer
796 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
798 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
799 * it will be locked exclusive.
801 * NOTE: Embedded elements (volume header, inodes) are always resolved
804 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
805 * element will instantiate and zero its buffer, and flush it on
808 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
809 * so as not to instantiate a device buffer, which could alias against
810 * a logical file buffer. However, if ALWAYS is specified the
811 * device buffer will be instantiated anyway.
813 * WARNING! If data must be fetched a shared lock will temporarily be
814 * upgraded to exclusive. However, a deadlock can occur if
815 * the caller owns more than one shared lock.
818 hammer2_chain_lock(hammer2_chain_t *chain, int how)
820 hammer2_mount_t *hmp;
821 hammer2_chain_core_t *core;
822 hammer2_blockref_t *bref;
828 * Ref and lock the element. Recursive locks are allowed.
830 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
831 hammer2_chain_ref(chain);
832 atomic_add_int(&chain->lockcnt, 1);
835 KKASSERT(hmp != NULL);
838 * Get the appropriate lock.
841 if (how & HAMMER2_RESOLVE_SHARED)
842 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
844 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
847 * If we already have a valid data pointer no further action is
854 * Do we have to resolve the data?
856 switch(how & HAMMER2_RESOLVE_MASK) {
857 case HAMMER2_RESOLVE_NEVER:
859 case HAMMER2_RESOLVE_MAYBE:
860 if (chain->flags & HAMMER2_CHAIN_INITIAL)
862 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
865 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
868 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
871 case HAMMER2_RESOLVE_ALWAYS:
876 * Upgrade to an exclusive lock so we can safely manipulate the
877 * buffer cache. If another thread got to it before us we
880 ostate = ccms_thread_lock_upgrade(&core->cst);
882 ccms_thread_lock_downgrade(&core->cst, ostate);
887 * We must resolve to a device buffer, either by issuing I/O or
888 * by creating a zero-fill element. We do not mark the buffer
889 * dirty when creating a zero-fill element (the hammer2_chain_modify()
890 * API must still be used to do that).
892 * The device buffer is variable-sized in powers of 2 down
893 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
894 * chunk always contains buffers of the same size. (XXX)
896 * The minimum physical IO size may be larger than the variable
902 * The getblk() optimization can only be used on newly created
903 * elements if the physical block size matches the request.
905 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
906 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
909 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
911 hammer2_adjreadcounter(&chain->bref, chain->bytes);
915 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
916 (intmax_t)bref->data_off, error);
917 hammer2_io_bqrelse(&chain->dio);
918 ccms_thread_lock_downgrade(&core->cst, ostate);
924 * No need for this, always require that hammer2_chain_modify()
925 * be called before any modifying operations.
927 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
928 !hammer2_io_isdirty(chain->dio)) {
929 hammer2_io_setdirty(chain->dio);
934 * We can clear the INITIAL state now, we've resolved the buffer
935 * to zeros and marked it dirty with hammer2_io_new().
937 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
938 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
939 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
943 * Setup the data pointer, either pointing it to an embedded data
944 * structure and copying the data from the buffer, or pointing it
947 * The buffer is not retained when copying to an embedded data
948 * structure in order to avoid potential deadlocks or recursions
949 * on the same physical buffer.
951 switch (bref->type) {
952 case HAMMER2_BREF_TYPE_VOLUME:
953 case HAMMER2_BREF_TYPE_FREEMAP:
955 * Copy data from bp to embedded buffer
957 panic("hammer2_chain_lock: called on unresolved volume header");
959 case HAMMER2_BREF_TYPE_INODE:
960 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
961 case HAMMER2_BREF_TYPE_INDIRECT:
962 case HAMMER2_BREF_TYPE_DATA:
963 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
966 * Point data at the device buffer and leave dio intact.
968 chain->data = (void *)bdata;
971 ccms_thread_lock_downgrade(&core->cst, ostate);
976 * This basically calls hammer2_io_breadcb() but does some pre-processing
977 * of the chain first to handle certain cases.
980 hammer2_chain_load_async(hammer2_cluster_t *cluster,
981 void (*callback)(hammer2_io_t *dio,
982 hammer2_cluster_t *cluster,
983 hammer2_chain_t *chain,
984 void *arg_p, off_t arg_o),
987 hammer2_chain_t *chain;
988 hammer2_mount_t *hmp;
989 struct hammer2_io *dio;
990 hammer2_blockref_t *bref;
995 * If no chain specified see if any chain data is available and use
996 * that, otherwise begin an I/O iteration using the first chain.
999 for (i = 0; i < cluster->nchains; ++i) {
1000 chain = cluster->array[i];
1001 if (chain && chain->data)
1004 if (i == cluster->nchains) {
1005 chain = cluster->array[0];
1010 callback(NULL, cluster, chain, arg_p, (off_t)i);
1015 * We must resolve to a device buffer, either by issuing I/O or
1016 * by creating a zero-fill element. We do not mark the buffer
1017 * dirty when creating a zero-fill element (the hammer2_chain_modify()
1018 * API must still be used to do that).
1020 * The device buffer is variable-sized in powers of 2 down
1021 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
1022 * chunk always contains buffers of the same size. (XXX)
1024 * The minimum physical IO size may be larger than the variable
1027 bref = &chain->bref;
1031 * The getblk() optimization can only be used on newly created
1032 * elements if the physical block size matches the request.
1034 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1035 chain->bytes == hammer2_devblksize(chain->bytes)) {
1036 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
1037 KKASSERT(error == 0);
1038 callback(dio, cluster, chain, arg_p, (off_t)i);
1043 * Otherwise issue a read
1045 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1046 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
1047 callback, cluster, chain, arg_p, (off_t)i);
1051 * Unlock and deref a chain element.
1053 * On the last lock release any non-embedded data (chain->dio) will be
1057 hammer2_chain_unlock(hammer2_chain_t *chain)
1059 hammer2_chain_core_t *core = chain->core;
1060 ccms_state_t ostate;
1065 * The core->cst lock can be shared across several chains so we
1066 * need to track the per-chain lockcnt separately.
1068 * If multiple locks are present (or being attempted) on this
1069 * particular chain we can just unlock, drop refs, and return.
1071 * Otherwise fall-through on the 1->0 transition.
1074 lockcnt = chain->lockcnt;
1075 KKASSERT(lockcnt > 0);
1078 if (atomic_cmpset_int(&chain->lockcnt,
1079 lockcnt, lockcnt - 1)) {
1080 ccms_thread_unlock(&core->cst);
1081 hammer2_chain_drop(chain);
1085 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1092 * On the 1->0 transition we upgrade the core lock (if necessary)
1093 * to exclusive for terminal processing. If after upgrading we find
1094 * that lockcnt is non-zero, another thread is racing us and will
1095 * handle the unload for us later on, so just cleanup and return
1096 * leaving the data/io intact
1098 * Otherwise if lockcnt is still 0 it is possible for it to become
1099 * non-zero and race, but since we hold the core->cst lock
1100 * exclusively all that will happen is that the chain will be
1101 * reloaded after we unload it.
1103 ostate = ccms_thread_lock_upgrade(&core->cst);
1104 if (chain->lockcnt) {
1105 ccms_thread_unlock_upgraded(&core->cst, ostate);
1106 hammer2_chain_drop(chain);
1111 * Shortcut the case if the data is embedded or not resolved.
1113 * Do NOT NULL out chain->data (e.g. inode data), it might be
1116 if (chain->dio == NULL) {
1117 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1118 hammer2_chain_drop_data(chain, 0);
1119 ccms_thread_unlock_upgraded(&core->cst, ostate);
1120 hammer2_chain_drop(chain);
1127 if (hammer2_io_isdirty(chain->dio) == 0) {
1129 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1130 switch(chain->bref.type) {
1131 case HAMMER2_BREF_TYPE_DATA:
1132 counterp = &hammer2_ioa_file_write;
1134 case HAMMER2_BREF_TYPE_INODE:
1135 counterp = &hammer2_ioa_meta_write;
1137 case HAMMER2_BREF_TYPE_INDIRECT:
1138 counterp = &hammer2_ioa_indr_write;
1140 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1141 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1142 counterp = &hammer2_ioa_fmap_write;
1145 counterp = &hammer2_ioa_volu_write;
1148 *counterp += chain->bytes;
1150 switch(chain->bref.type) {
1151 case HAMMER2_BREF_TYPE_DATA:
1152 counterp = &hammer2_iod_file_write;
1154 case HAMMER2_BREF_TYPE_INODE:
1155 counterp = &hammer2_iod_meta_write;
1157 case HAMMER2_BREF_TYPE_INDIRECT:
1158 counterp = &hammer2_iod_indr_write;
1160 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1161 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1162 counterp = &hammer2_iod_fmap_write;
1165 counterp = &hammer2_iod_volu_write;
1168 *counterp += chain->bytes;
1172 * Clean out the dio.
1174 * If a device buffer was used for data be sure to destroy the
1175 * buffer when we are done to avoid aliases (XXX what about the
1176 * underlying VM pages?).
1178 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1181 * NOTE: The isdirty check tracks whether we have to bdwrite() the
1182 * buffer or not. The buffer might already be dirty. The
1183 * flag is re-set when chain_modify() is called, even if
1184 * MODIFIED is already set, allowing the OS to retire the
1185 * buffer independent of a hammer2 flush.
1188 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
1189 hammer2_io_isdirty(chain->dio)) {
1190 hammer2_io_bawrite(&chain->dio);
1192 hammer2_io_bqrelse(&chain->dio);
1194 ccms_thread_unlock_upgraded(&core->cst, ostate);
1195 hammer2_chain_drop(chain);
1199 * This counts the number of live blockrefs in a block array and
1200 * also calculates the point at which all remaining blockrefs are empty.
1201 * This routine can only be called on a live chain (DUPLICATED flag not set).
1203 * NOTE: Flag is not set until after the count is complete, allowing
1204 * callers to test the flag without holding the spinlock.
1206 * NOTE: If base is NULL the related chain is still in the INITIAL
1207 * state and there are no blockrefs to count.
1209 * NOTE: live_count may already have some counts accumulated due to
1210 * creation and deletion and could even be initially negative.
1213 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1214 hammer2_blockref_t *base, int count)
1216 hammer2_chain_core_t *core = chain->core;
1218 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
1220 spin_lock(&core->cst.spin);
1221 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1223 while (--count >= 0) {
1224 if (base[count].type)
1227 core->live_zero = count + 1;
1228 while (count >= 0) {
1229 if (base[count].type)
1230 atomic_add_int(&core->live_count, 1);
1234 core->live_zero = 0;
1236 /* else do not modify live_count */
1237 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1239 spin_unlock(&core->cst.spin);
1243 * Resize the chain's physical storage allocation in-place. This may
1244 * replace the passed-in chain with a new chain.
1246 * Chains can be resized smaller without reallocating the storage.
1247 * Resizing larger will reallocate the storage.
1249 * Must be passed an exclusively locked parent and chain, returns a new
1250 * exclusively locked chain at the same index and unlocks the old chain.
1251 * Flushes the buffer if necessary.
1253 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1254 * to avoid instantiating a device buffer that conflicts with the vnode
1255 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1256 * any chain-oriented bp would be a device buffer.
1258 * XXX return error if cannot resize.
1261 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1262 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1263 int nradix, int flags)
1265 hammer2_mount_t *hmp;
1266 hammer2_chain_t *chain;
1274 * Only data and indirect blocks can be resized for now.
1275 * (The volu root, inodes, and freemap elements use a fixed size).
1277 KKASSERT(chain != &hmp->vchain);
1278 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1279 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1282 * Nothing to do if the element is already the proper size
1284 obytes = chain->bytes;
1285 nbytes = 1U << nradix;
1286 if (obytes == nbytes)
1290 * Delete the old chain and duplicate it at the same (parent, index),
1291 * returning a new chain. This allows the old chain to still be
1292 * used by the flush code. The new chain will be returned in a
1295 * The parent does not have to be locked for the delete/duplicate call,
1296 * but is in this particular code path.
1298 * NOTE: If we are not crossing a synchronization point the
1299 * duplication code will simply reuse the existing chain
1302 hammer2_chain_delete_duplicate(trans, &chain, 0);
1305 * Relocate the block, even if making it smaller (because different
1306 * block sizes may be in different regions).
1308 * (data blocks only, we aren't copying the storage here).
1310 hammer2_freemap_alloc(trans, chain, nbytes);
1311 chain->bytes = nbytes;
1312 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1313 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1316 * For now just support it on DATA chains (and not on indirect
1319 KKASSERT(chain->dio == NULL);
1327 * REMOVED - see cluster code
1329 * Set a chain modified, making it read-write and duplicating it if necessary.
1330 * This function will assign a new physical block to the chain if necessary
1332 * Duplication of already-modified chains is possible when the modification
1333 * crosses a flush synchronization boundary.
1335 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1336 * level or the COW operation will not work.
1338 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1339 * run the data through the device buffers.
1341 * This function may return a different chain than was passed, in which case
1342 * the old chain will be unlocked and the new chain will be locked.
1344 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1346 hammer2_inode_data_t *
1347 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1348 hammer2_chain_t **chainp, int flags)
1350 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1351 hammer2_chain_modify(trans, chainp, flags);
1352 if (ip->chain != *chainp)
1353 hammer2_inode_repoint(ip, NULL, *chainp);
1355 vsetisdirty(ip->vp);
1356 return(&ip->chain->data->ipdata);
1362 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1365 hammer2_mount_t *hmp;
1366 hammer2_chain_t *chain;
1376 * data is not optional for freemap chains (we must always be sure
1377 * to copy the data on COW storage allocations).
1379 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1380 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1381 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1382 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1386 * Determine if a delete-duplicate is needed.
1388 * (a) Modify_tid is part of a prior flush
1389 * (b) Transaction is concurrent with a flush (has higher tid)
1390 * (c) and chain is not in the initial state (freshly created)
1391 * (d) and caller didn't request an in-place modification.
1393 * The freemap and volume header special chains are never D-Dd.
1395 if (chain->modify_xid != trans->sync_xid && /* cross boundary */
1396 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1397 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1398 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1399 hammer2_chain_delete_duplicate(trans, chainp, 0);
1405 * Data must be resolved if already assigned unless explicitly
1406 * flagged otherwise.
1408 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1409 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1410 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1411 hammer2_chain_unlock(chain);
1415 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1416 * that the chain has been modified. Set FLUSH_CREATE to flush
1417 * the new blockref (the D-D set FLUSH_DELETE on the old chain to
1418 * delete the old blockref).
1420 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1421 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1422 hammer2_chain_ref(chain);
1423 hammer2_pfs_memory_inc(chain->pmp);
1425 if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
1426 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
1427 hammer2_chain_ref(chain);
1431 * The modification or re-modification requires an allocation and
1434 * We normally always allocate new storage here. If storage exists
1435 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1437 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1438 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1439 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1440 chain->modify_xid != trans->sync_xid)
1442 hammer2_freemap_alloc(trans, chain, chain->bytes);
1443 /* XXX failed allocation */
1444 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1445 hammer2_freemap_alloc(trans, chain, chain->bytes);
1446 /* XXX failed allocation */
1448 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1452 * Update modify_xid. XXX special-case vchain/fchain because they
1453 * are always modified in-place. Otherwise the chain being modified
1454 * must not be part of a future transaction.
1456 if (chain == &hmp->vchain || chain == &hmp->fchain) {
1457 if (chain->modify_xid <= trans->sync_xid)
1458 chain->modify_xid = trans->sync_xid;
1460 KKASSERT(chain->modify_xid <= trans->sync_xid);
1461 chain->modify_xid = trans->sync_xid;
1465 * Do not COW BREF_TYPE_DATA when OPTDATA is set. This is because
1466 * data modifications are done via the logical buffer cache so COWing
1467 * it here would result in unnecessary extra copies (and possibly extra
1468 * block reallocations). The INITIAL flag remains unchanged in this
1471 * (This is a bit of a hack).
1473 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1474 (flags & HAMMER2_MODIFY_OPTDATA)) {
1479 * Clearing the INITIAL flag (for indirect blocks) indicates that
1480 * we've processed the uninitialized storage allocation.
1482 * If this flag is already clear we are likely in a copy-on-write
1483 * situation but we have to be sure NOT to bzero the storage if
1484 * no data is present.
1486 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1487 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1494 * Instantiate data buffer and possibly execute COW operation
1496 switch(chain->bref.type) {
1497 case HAMMER2_BREF_TYPE_VOLUME:
1498 case HAMMER2_BREF_TYPE_FREEMAP:
1500 * The data is embedded, no copy-on-write operation is
1503 KKASSERT(chain->dio == NULL);
1505 case HAMMER2_BREF_TYPE_INODE:
1506 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1507 case HAMMER2_BREF_TYPE_DATA:
1508 case HAMMER2_BREF_TYPE_INDIRECT:
1509 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1511 * Perform the copy-on-write operation
1513 * zero-fill or copy-on-write depending on whether
1514 * chain->data exists or not and set the dirty state for
1515 * the new buffer. hammer2_io_new() will handle the
1518 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1521 error = hammer2_io_new(hmp, chain->bref.data_off,
1522 chain->bytes, &dio);
1524 error = hammer2_io_bread(hmp, chain->bref.data_off,
1525 chain->bytes, &dio);
1527 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1528 KKASSERT(error == 0);
1530 bdata = hammer2_io_data(dio, chain->bref.data_off);
1533 KKASSERT(chain->dio != NULL);
1534 if (chain->data != (void *)bdata) {
1535 bcopy(chain->data, bdata, chain->bytes);
1537 } else if (wasinitial == 0) {
1539 * We have a problem. We were asked to COW but
1540 * we don't have any data to COW with!
1542 panic("hammer2_chain_modify: having a COW %p\n",
1547 * Retire the old buffer, replace with the new
1550 hammer2_io_brelse(&chain->dio);
1551 chain->data = (void *)bdata;
1553 hammer2_io_setdirty(dio); /* modified by bcopy above */
1556 panic("hammer2_chain_modify: illegal non-embedded type %d",
1562 hammer2_chain_setsubmod(trans, chain);
1566 * Volume header data locks
1569 hammer2_voldata_lock(hammer2_mount_t *hmp)
1571 lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1575 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1577 lockmgr(&hmp->vollk, LK_RELEASE);
1581 hammer2_voldata_modify(hammer2_mount_t *hmp)
1583 if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1584 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1585 hammer2_chain_ref(&hmp->vchain);
1590 * This function returns the chain at the nearest key within the specified
1591 * range with the highest delete_xid. The core spinlock must be held on
1592 * call and the returned chain will be referenced but not locked.
1594 * The returned chain may or may not be in a deleted state. Note that
1595 * live chains have a delete_xid = XID_MAX.
1597 * This function will recurse through chain->rbtree as necessary and will
1598 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1599 * the iteration value is less than the current value of *key_nextp.
1601 * The caller should use (*key_nextp) to calculate the actual range of
1602 * the returned element, which will be (key_beg to *key_nextp - 1), because
1603 * there might be another element which is superior to the returned element
1606 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1607 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1608 * it will wind up being (key_end + 1).
1610 struct hammer2_chain_find_info {
1611 hammer2_chain_t *best;
1612 hammer2_key_t key_beg;
1613 hammer2_key_t key_end;
1614 hammer2_key_t key_next;
1617 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1618 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1622 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1623 hammer2_key_t key_beg, hammer2_key_t key_end)
1625 struct hammer2_chain_find_info info;
1628 info.key_beg = key_beg;
1629 info.key_end = key_end;
1630 info.key_next = *key_nextp;
1632 KKASSERT(parent->core->good == 0x1234);
1633 RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1634 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1636 *key_nextp = info.key_next;
1638 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1639 parent, key_beg, key_end, *key_nextp);
1646 * Find a deleted chain covering a block table entry. Be careful to deal
1647 * with the race condition where the block table has been updated but the
1648 * chain has not yet been removed from dbtree (due to multiple parents having
1653 hammer2_chain_find_deleted(hammer2_chain_t *parent,
1654 hammer2_key_t key_beg, hammer2_key_t key_end)
1656 struct hammer2_chain_find_info info;
1657 hammer2_chain_t *child;
1660 info.key_beg = key_beg;
1661 info.key_end = key_end;
1664 KKASSERT(parent->core->good == 0x1234);
1665 RB_SCAN(hammer2_chain_tree, &parent->core->dbtree,
1666 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1668 if ((child = info.best) != NULL) {
1669 if (child->delete_xid <= parent->update_xlo)
1677 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1679 struct hammer2_chain_find_info *info = data;
1680 hammer2_key_t child_beg;
1681 hammer2_key_t child_end;
1683 child_beg = child->bref.key;
1684 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1686 if (child_end < info->key_beg)
1688 if (child_beg > info->key_end)
1695 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1697 struct hammer2_chain_find_info *info = data;
1698 hammer2_chain_t *best;
1699 hammer2_key_t child_end;
1702 * WARNING! Do not discard DUPLICATED chains, it is possible that
1703 * we are catching an insertion half-way done. If a
1704 * duplicated chain turns out to be the best choice the
1705 * caller will re-check its flags after locking it.
1707 * WARNING! Layerq is scanned forwards, exact matches should keep
1708 * the existing info->best.
1710 if ((best = info->best) == NULL) {
1712 * No previous best. Assign best
1715 } else if (best->bref.key <= info->key_beg &&
1716 child->bref.key <= info->key_beg) {
1718 * If our current best is flush with key_beg and child is
1719 * also flush with key_beg choose based on delete_xid.
1721 * key_next will automatically be limited to the smaller of
1722 * the two end-points.
1724 if (child->delete_xid > best->delete_xid)
1726 } else if (child->bref.key < best->bref.key) {
1728 * Child has a nearer key and best is not flush with key_beg.
1729 * Truncate key_next to the old best key iff it had a better
1733 if (best->delete_xid >= child->delete_xid &&
1734 (info->key_next > best->bref.key || info->key_next == 0))
1735 info->key_next = best->bref.key;
1736 } else if (child->bref.key == best->bref.key) {
1738 * If our current best is flush with the child then choose
1739 * based on delete_xid.
1741 * key_next will automatically be limited to the smaller of
1742 * the two end-points.
1744 if (child->delete_xid > best->delete_xid)
1748 * Keep the current best but truncate key_next to the child's
1749 * base iff the child has a higher delete_xid.
1751 * key_next will also automatically be limited to the smaller
1752 * of the two end-points (probably not necessary for this case
1753 * but we do it anyway).
1755 if (child->delete_xid >= best->delete_xid &&
1756 (info->key_next > child->bref.key || info->key_next == 0))
1757 info->key_next = child->bref.key;
1761 * Always truncate key_next based on child's end-of-range.
1763 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1764 if (child_end && (info->key_next > child_end || info->key_next == 0))
1765 info->key_next = child_end;
1771 * Retrieve the specified chain from a media blockref, creating the
1772 * in-memory chain structure which reflects it. modify_xid will be
1773 * set to the min value which forces any modifications to issue a
1776 * To handle insertion races pass the INSERT_RACE flag along with the
1777 * generation number of the core. NULL will be returned if the generation
1778 * number changes before we have a chance to insert the chain. Insert
1779 * races can occur because the parent might be held shared.
1781 * Caller must hold the parent locked shared or exclusive since we may
1782 * need the parent's bref array to find our block.
1784 * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1788 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1789 hammer2_blockref_t *bref)
1791 hammer2_mount_t *hmp = parent->hmp;
1792 hammer2_chain_core_t *above = parent->core;
1793 hammer2_chain_t *chain;
1797 * Allocate a chain structure representing the existing media
1798 * entry. Resulting chain has one ref and is not locked.
1800 if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1801 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1803 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1804 hammer2_chain_core_alloc(NULL, chain, NULL);
1805 /* ref'd chain returned */
1808 * Set modify_xid and update_xlo to the chain's synchronization
1809 * point from the media.
1811 chain->modify_xid = HAMMER2_XID_MIN;
1812 chain->update_xlo = HAMMER2_XID_MIN;
1813 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1816 * Link the chain into its parent. A spinlock is required to safely
1817 * access the RBTREE, and it is possible to collide with another
1818 * hammer2_chain_get() operation because the caller might only hold
1819 * a shared lock on the parent.
1821 KKASSERT(parent->refs > 0);
1822 error = hammer2_chain_insert(above, NULL, chain,
1823 HAMMER2_CHAIN_INSERT_SPIN |
1824 HAMMER2_CHAIN_INSERT_RACE,
1827 KKASSERT((chain->flags & (HAMMER2_CHAIN_ONRBTREE |
1828 HAMMER2_CHAIN_ONDBTREE |
1829 HAMMER2_CHAIN_ONDBQ)) == 0);
1830 kprintf("chain %p get race\n", chain);
1831 hammer2_chain_drop(chain);
1834 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1838 * Return our new chain referenced but not locked, or NULL if
1845 * Lookup initialization/completion API
1848 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1850 if (flags & HAMMER2_LOOKUP_SHARED) {
1851 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1852 HAMMER2_RESOLVE_SHARED);
1854 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1860 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1863 hammer2_chain_unlock(parent);
1868 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1870 hammer2_chain_t *oparent;
1871 hammer2_chain_t *bparent;
1872 hammer2_chain_t *nparent;
1873 hammer2_chain_core_t *above;
1876 above = oparent->above;
1878 spin_lock(&above->cst.spin);
1879 bparent = TAILQ_FIRST(&above->ownerq);
1880 hammer2_chain_ref(bparent);
1883 * Be careful of order, oparent must be unlocked before nparent
1884 * is locked below to avoid a deadlock. We might as well delay its
1885 * unlocking until we conveniently no longer have the spinlock (instead
1886 * of cycling the spinlock).
1888 * Theoretically our ref on bparent should prevent elements of the
1889 * following chain from going away and prevent above from going away,
1890 * but we still need the spinlock to safely scan the list.
1894 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1895 nparent = TAILQ_NEXT(nparent, core_entry);
1896 hammer2_chain_ref(nparent);
1897 spin_unlock(&above->cst.spin);
1900 hammer2_chain_unlock(oparent);
1903 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1904 hammer2_chain_drop(bparent);
1907 * We might have raced a delete-duplicate.
1909 if ((nparent->flags & HAMMER2_CHAIN_DUPLICATED) == 0)
1912 hammer2_chain_ref(bparent);
1913 hammer2_chain_unlock(nparent);
1914 spin_lock(&above->cst.spin);
1923 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1924 * (*parentp) typically points to an inode but can also point to a related
1925 * indirect block and this function will recurse upwards and find the inode
1928 * (*parentp) must be exclusively locked and referenced and can be an inode
1929 * or an existing indirect block within the inode.
1931 * On return (*parentp) will be modified to point at the deepest parent chain
1932 * element encountered during the search, as a helper for an insertion or
1933 * deletion. The new (*parentp) will be locked and referenced and the old
1934 * will be unlocked and dereferenced (no change if they are both the same).
1936 * The matching chain will be returned exclusively locked. If NOLOCK is
1937 * requested the chain will be returned only referenced.
1939 * NULL is returned if no match was found, but (*parentp) will still
1940 * potentially be adjusted.
1942 * On return (*key_nextp) will point to an iterative value for key_beg.
1943 * (If NULL is returned (*key_nextp) is set to key_end).
1945 * This function will also recurse up the chain if the key is not within the
1946 * current parent's range. (*parentp) can never be set to NULL. An iteration
1947 * can simply allow (*parentp) to float inside the loop.
1949 * NOTE! chain->data is not always resolved. By default it will not be
1950 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1951 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1952 * BREF_TYPE_DATA as the device buffer can alias the logical file
1956 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1957 hammer2_key_t key_beg, hammer2_key_t key_end,
1958 int *cache_indexp, int flags, int *ddflagp)
1960 hammer2_mount_t *hmp;
1961 hammer2_chain_t *parent;
1962 hammer2_chain_t *chain;
1963 hammer2_blockref_t *base;
1964 hammer2_blockref_t *bref;
1965 hammer2_blockref_t bcopy;
1966 hammer2_key_t scan_beg;
1967 hammer2_key_t scan_end;
1968 hammer2_chain_core_t *above;
1970 int how_always = HAMMER2_RESOLVE_ALWAYS;
1971 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1974 int maxloops = 300000;
1978 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1979 how_maybe = how_always;
1980 how = HAMMER2_RESOLVE_ALWAYS;
1981 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1982 how = HAMMER2_RESOLVE_NEVER;
1984 how = HAMMER2_RESOLVE_MAYBE;
1986 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1987 how_maybe |= HAMMER2_RESOLVE_SHARED;
1988 how_always |= HAMMER2_RESOLVE_SHARED;
1989 how |= HAMMER2_RESOLVE_SHARED;
1993 * Recurse (*parentp) upward if necessary until the parent completely
1994 * encloses the key range or we hit the inode.
1996 * This function handles races against the flusher doing a delete-
1997 * duplicate above us and re-homes the parent to the duplicate in
1998 * that case, otherwise we'd wind up recursing down a stale chain.
2003 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2004 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2005 scan_beg = parent->bref.key;
2006 scan_end = scan_beg +
2007 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2008 if (key_beg >= scan_beg && key_end <= scan_end)
2010 parent = hammer2_chain_getparent(parentp, how_maybe);
2014 if (--maxloops == 0)
2015 panic("hammer2_chain_lookup: maxloops");
2017 * Locate the blockref array. Currently we do a fully associative
2018 * search through the array.
2020 switch(parent->bref.type) {
2021 case HAMMER2_BREF_TYPE_INODE:
2023 * Special shortcut for embedded data returns the inode
2024 * itself. Callers must detect this condition and access
2025 * the embedded data (the strategy code does this for us).
2027 * This is only applicable to regular files and softlinks.
2029 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2030 if (flags & HAMMER2_LOOKUP_NOLOCK)
2031 hammer2_chain_ref(parent);
2033 hammer2_chain_lock(parent, how_always);
2034 *key_nextp = key_end + 1;
2038 base = &parent->data->ipdata.u.blockset.blockref[0];
2039 count = HAMMER2_SET_COUNT;
2041 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2042 case HAMMER2_BREF_TYPE_INDIRECT:
2044 * Handle MATCHIND on the parent
2046 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2047 scan_beg = parent->bref.key;
2048 scan_end = scan_beg +
2049 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2050 if (key_beg == scan_beg && key_end == scan_end) {
2052 hammer2_chain_lock(chain, how_maybe);
2053 *key_nextp = scan_end + 1;
2058 * Optimize indirect blocks in the INITIAL state to avoid
2061 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2064 if (parent->data == NULL)
2065 panic("parent->data is NULL");
2066 base = &parent->data->npdata[0];
2068 count = parent->bytes / sizeof(hammer2_blockref_t);
2070 case HAMMER2_BREF_TYPE_VOLUME:
2071 base = &hmp->voldata.sroot_blockset.blockref[0];
2072 count = HAMMER2_SET_COUNT;
2074 case HAMMER2_BREF_TYPE_FREEMAP:
2075 base = &hmp->voldata.freemap_blockset.blockref[0];
2076 count = HAMMER2_SET_COUNT;
2079 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2081 base = NULL; /* safety */
2082 count = 0; /* safety */
2086 * Merged scan to find next candidate.
2088 * hammer2_base_*() functions require the above->live_* fields
2089 * to be synchronized.
2091 * We need to hold the spinlock to access the block array and RB tree
2092 * and to interlock chain creation.
2094 above = parent->core;
2095 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2096 hammer2_chain_countbrefs(parent, base, count);
2101 spin_lock(&above->cst.spin);
2102 chain = hammer2_combined_find(parent, base, count,
2103 cache_indexp, key_nextp,
2106 generation = above->generation;
2109 * Exhausted parent chain, iterate.
2112 spin_unlock(&above->cst.spin);
2113 if (key_beg == key_end) /* short cut single-key case */
2117 * Stop if we reached the end of the iteration.
2119 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2120 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2125 * Calculate next key, stop if we reached the end of the
2126 * iteration, otherwise go up one level and loop.
2128 key_beg = parent->bref.key +
2129 ((hammer2_key_t)1 << parent->bref.keybits);
2130 if (key_beg == 0 || key_beg > key_end)
2132 parent = hammer2_chain_getparent(parentp, how_maybe);
2137 * Selected from blockref or in-memory chain.
2139 if (chain == NULL) {
2141 spin_unlock(&above->cst.spin);
2142 chain = hammer2_chain_get(parent, generation,
2144 if (chain == NULL) {
2145 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2146 parent, key_beg, key_end);
2149 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2150 hammer2_chain_drop(chain);
2155 hammer2_chain_ref(chain);
2156 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2157 spin_unlock(&above->cst.spin);
2161 * chain is referenced but not locked. We must lock the chain
2162 * to obtain definitive DUPLICATED/DELETED state
2164 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2165 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2166 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2168 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2172 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2174 * NOTE: Chain's key range is not relevant as there might be
2175 * one-offs within the range that are not deleted.
2177 * NOTE: Lookups can race delete-duplicate because
2178 * delete-duplicate does not lock the parent's core
2179 * (they just use the spinlock on the core). We must
2180 * check for races by comparing the DUPLICATED flag before
2181 * releasing the spinlock with the flag after locking the
2184 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2185 hammer2_chain_unlock(chain);
2186 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2187 key_beg = *key_nextp;
2188 if (key_beg == 0 || key_beg > key_end)
2195 * If the chain element is an indirect block it becomes the new
2196 * parent and we loop on it. We must maintain our top-down locks
2197 * to prevent the flusher from interfering (i.e. doing a
2198 * delete-duplicate and leaving us recursing down a deleted chain).
2200 * The parent always has to be locked with at least RESOLVE_MAYBE
2201 * so we can access its data. It might need a fixup if the caller
2202 * passed incompatible flags. Be careful not to cause a deadlock
2203 * as a data-load requires an exclusive lock.
2205 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2206 * range is within the requested key range we return the indirect
2207 * block and do NOT loop. This is usually only used to acquire
2210 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2211 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2212 hammer2_chain_unlock(parent);
2213 *parentp = parent = chain;
2218 * All done, return the chain
2224 * After having issued a lookup we can iterate all matching keys.
2226 * If chain is non-NULL we continue the iteration from just after it's index.
2228 * If chain is NULL we assume the parent was exhausted and continue the
2229 * iteration at the next parent.
2231 * parent must be locked on entry and remains locked throughout. chain's
2232 * lock status must match flags. Chain is always at least referenced.
2234 * WARNING! The MATCHIND flag does not apply to this function.
2237 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2238 hammer2_key_t *key_nextp,
2239 hammer2_key_t key_beg, hammer2_key_t key_end,
2240 int *cache_indexp, int flags)
2242 hammer2_chain_t *parent;
2247 * Calculate locking flags for upward recursion.
2249 how_maybe = HAMMER2_RESOLVE_MAYBE;
2250 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2251 how_maybe |= HAMMER2_RESOLVE_SHARED;
2256 * Calculate the next index and recalculate the parent if necessary.
2259 key_beg = chain->bref.key +
2260 ((hammer2_key_t)1 << chain->bref.keybits);
2261 if (flags & HAMMER2_LOOKUP_NOLOCK)
2262 hammer2_chain_drop(chain);
2264 hammer2_chain_unlock(chain);
2267 * Any scan where the lookup returned degenerate data embedded
2268 * in the inode has an invalid index and must terminate.
2270 if (chain == parent)
2272 if (key_beg == 0 || key_beg > key_end)
2275 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2276 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2278 * We reached the end of the iteration.
2283 * Continue iteration with next parent unless the current
2284 * parent covers the range.
2286 key_beg = parent->bref.key +
2287 ((hammer2_key_t)1 << parent->bref.keybits);
2288 if (key_beg == 0 || key_beg > key_end)
2290 parent = hammer2_chain_getparent(parentp, how_maybe);
2296 return (hammer2_chain_lookup(parentp, key_nextp,
2298 cache_indexp, flags, &ddflag));
2302 * The raw scan function is similar to lookup/next but does not seek to a key.
2303 * Blockrefs are iterated via first_chain = (parent, NULL) and
2304 * next_chain = (parent, chain).
2306 * The passed-in parent must be locked and its data resolved. The returned
2307 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
2308 * under parent and then iterate with the passed-in chain (which this
2309 * function will unlock).
2312 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2313 int *cache_indexp, int flags)
2315 hammer2_mount_t *hmp;
2316 hammer2_blockref_t *base;
2317 hammer2_blockref_t *bref;
2318 hammer2_blockref_t bcopy;
2319 hammer2_chain_core_t *above;
2321 hammer2_key_t next_key;
2323 int how_always = HAMMER2_RESOLVE_ALWAYS;
2324 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2327 int maxloops = 300000;
2333 * Scan flags borrowed from lookup
2335 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2336 how_maybe = how_always;
2337 how = HAMMER2_RESOLVE_ALWAYS;
2338 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2339 how = HAMMER2_RESOLVE_NEVER;
2341 how = HAMMER2_RESOLVE_MAYBE;
2343 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2344 how_maybe |= HAMMER2_RESOLVE_SHARED;
2345 how_always |= HAMMER2_RESOLVE_SHARED;
2346 how |= HAMMER2_RESOLVE_SHARED;
2350 * Calculate key to locate first/next element, unlocking the previous
2351 * element as we go. Be careful, the key calculation can overflow.
2354 key = chain->bref.key +
2355 ((hammer2_key_t)1 << chain->bref.keybits);
2356 hammer2_chain_unlock(chain);
2365 if (--maxloops == 0)
2366 panic("hammer2_chain_scan: maxloops");
2368 * Locate the blockref array. Currently we do a fully associative
2369 * search through the array.
2371 switch(parent->bref.type) {
2372 case HAMMER2_BREF_TYPE_INODE:
2374 * An inode with embedded data has no sub-chains.
2376 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2378 base = &parent->data->ipdata.u.blockset.blockref[0];
2379 count = HAMMER2_SET_COUNT;
2381 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2382 case HAMMER2_BREF_TYPE_INDIRECT:
2384 * Optimize indirect blocks in the INITIAL state to avoid
2387 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2390 if (parent->data == NULL)
2391 panic("parent->data is NULL");
2392 base = &parent->data->npdata[0];
2394 count = parent->bytes / sizeof(hammer2_blockref_t);
2396 case HAMMER2_BREF_TYPE_VOLUME:
2397 base = &hmp->voldata.sroot_blockset.blockref[0];
2398 count = HAMMER2_SET_COUNT;
2400 case HAMMER2_BREF_TYPE_FREEMAP:
2401 base = &hmp->voldata.freemap_blockset.blockref[0];
2402 count = HAMMER2_SET_COUNT;
2405 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2407 base = NULL; /* safety */
2408 count = 0; /* safety */
2412 * Merged scan to find next candidate.
2414 * hammer2_base_*() functions require the above->live_* fields
2415 * to be synchronized.
2417 * We need to hold the spinlock to access the block array and RB tree
2418 * and to interlock chain creation.
2420 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2421 hammer2_chain_countbrefs(parent, base, count);
2423 above = parent->core;
2425 spin_lock(&above->cst.spin);
2426 chain = hammer2_combined_find(parent, base, count,
2427 cache_indexp, &next_key,
2428 key, HAMMER2_KEY_MAX,
2430 generation = above->generation;
2433 * Exhausted parent chain, we're done.
2436 spin_unlock(&above->cst.spin);
2437 KKASSERT(chain == NULL);
2442 * Selected from blockref or in-memory chain.
2444 if (chain == NULL) {
2446 spin_unlock(&above->cst.spin);
2447 chain = hammer2_chain_get(parent, generation, &bcopy);
2448 if (chain == NULL) {
2449 kprintf("retry scan parent %p keys %016jx\n",
2453 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2454 hammer2_chain_drop(chain);
2460 hammer2_chain_ref(chain);
2461 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2462 spin_unlock(&above->cst.spin);
2466 * chain is referenced but not locked. We must lock the chain
2467 * to obtain definitive DUPLICATED/DELETED state
2469 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2472 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2474 * NOTE: chain's key range is not relevant as there might be
2475 * one-offs within the range that are not deleted.
2477 * NOTE: XXX this could create problems with scans used in
2478 * situations other than mount-time recovery.
2480 * NOTE: Lookups can race delete-duplicate because
2481 * delete-duplicate does not lock the parent's core
2482 * (they just use the spinlock on the core). We must
2483 * check for races by comparing the DUPLICATED flag before
2484 * releasing the spinlock with the flag after locking the
2487 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2488 hammer2_chain_unlock(chain);
2491 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2501 * All done, return the chain or NULL
2507 * Create and return a new hammer2 system memory structure of the specified
2508 * key, type and size and insert it under (*parentp). This is a full
2509 * insertion, based on the supplied key/keybits, and may involve creating
2510 * indirect blocks and moving other chains around via delete/duplicate.
2512 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2513 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2514 * FULL. This typically means that the caller is creating the chain after
2515 * doing a hammer2_chain_lookup().
2517 * (*parentp) must be exclusive locked and may be replaced on return
2518 * depending on how much work the function had to do.
2520 * (*chainp) usually starts out NULL and returns the newly created chain,
2521 * but if the caller desires the caller may allocate a disconnected chain
2522 * and pass it in instead. (It is also possible for the caller to use
2523 * chain_duplicate() to create a disconnected chain, manipulate it, then
2524 * pass it into this function to insert it).
2526 * This function should NOT be used to insert INDIRECT blocks. It is
2527 * typically used to create/insert inodes and data blocks.
2529 * Caller must pass-in an exclusively locked parent the new chain is to
2530 * be inserted under, and optionally pass-in a disconnected, exclusively
2531 * locked chain to insert (else we create a new chain). The function will
2532 * adjust (*parentp) as necessary, create or connect the chain, and
2533 * return an exclusively locked chain in *chainp.
2536 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2537 hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2538 hammer2_key_t key, int keybits, int type, size_t bytes)
2540 hammer2_mount_t *hmp;
2541 hammer2_chain_t *chain;
2542 hammer2_chain_t *parent = *parentp;
2543 hammer2_chain_core_t *above;
2544 hammer2_blockref_t *base;
2545 hammer2_blockref_t dummy;
2549 int maxloops = 300000;
2552 * Topology may be crossing a PFS boundary.
2554 above = parent->core;
2555 KKASSERT(ccms_thread_lock_owned(&above->cst));
2559 if (chain == NULL) {
2561 * First allocate media space and construct the dummy bref,
2562 * then allocate the in-memory chain structure. Set the
2563 * INITIAL flag for fresh chains which do not have embedded
2566 bzero(&dummy, sizeof(dummy));
2569 dummy.keybits = keybits;
2570 dummy.data_off = hammer2_getradix(bytes);
2571 dummy.methods = parent->bref.methods;
2572 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2573 hammer2_chain_core_alloc(trans, chain, NULL);
2576 * Lock the chain manually, chain_lock will load the chain
2577 * which we do NOT want to do. (note: chain->refs is set
2578 * to 1 by chain_alloc() for us, but lockcnt is not).
2581 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2585 * We do NOT set INITIAL here (yet). INITIAL is only
2586 * used for indirect blocks.
2588 * Recalculate bytes to reflect the actual media block
2591 bytes = (hammer2_off_t)1 <<
2592 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2593 chain->bytes = bytes;
2596 case HAMMER2_BREF_TYPE_VOLUME:
2597 case HAMMER2_BREF_TYPE_FREEMAP:
2598 panic("hammer2_chain_create: called with volume type");
2600 case HAMMER2_BREF_TYPE_INDIRECT:
2601 panic("hammer2_chain_create: cannot be used to"
2602 "create indirect block");
2604 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2605 panic("hammer2_chain_create: cannot be used to"
2606 "create freemap root or node");
2608 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2609 KKASSERT(bytes == sizeof(chain->data->bmdata));
2611 case HAMMER2_BREF_TYPE_INODE:
2612 case HAMMER2_BREF_TYPE_DATA:
2615 * leave chain->data NULL, set INITIAL
2617 KKASSERT(chain->data == NULL);
2618 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2623 * We are reattaching a chain that has been duplicated and
2624 * left disconnected under a DIFFERENT parent with potentially
2625 * different key/keybits.
2627 * The chain must be modified in the current transaction
2628 * (the duplication code should have done that for us),
2629 * and it's modify_xid should be greater than the parent's
2630 * bref.mirror_tid. This should cause it to be created under
2633 * If deleted in the same transaction, the create/delete TIDs
2634 * will be the same and effective the chain will not have
2635 * existed at all from the point of view of the parent.
2637 * Do NOT mess with the current state of the INITIAL flag.
2639 KKASSERT(chain->modify_xid == trans->sync_xid);
2640 chain->bref.key = key;
2641 chain->bref.keybits = keybits;
2642 KKASSERT(chain->above == NULL);
2646 * Calculate how many entries we have in the blockref array and
2647 * determine if an indirect block is required.
2650 if (--maxloops == 0)
2651 panic("hammer2_chain_create: maxloops");
2652 above = parent->core;
2654 switch(parent->bref.type) {
2655 case HAMMER2_BREF_TYPE_INODE:
2656 KKASSERT((parent->data->ipdata.op_flags &
2657 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2658 KKASSERT(parent->data != NULL);
2659 base = &parent->data->ipdata.u.blockset.blockref[0];
2660 count = HAMMER2_SET_COUNT;
2662 case HAMMER2_BREF_TYPE_INDIRECT:
2663 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2664 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2667 base = &parent->data->npdata[0];
2668 count = parent->bytes / sizeof(hammer2_blockref_t);
2670 case HAMMER2_BREF_TYPE_VOLUME:
2671 KKASSERT(parent->data != NULL);
2672 base = &hmp->voldata.sroot_blockset.blockref[0];
2673 count = HAMMER2_SET_COUNT;
2675 case HAMMER2_BREF_TYPE_FREEMAP:
2676 KKASSERT(parent->data != NULL);
2677 base = &hmp->voldata.freemap_blockset.blockref[0];
2678 count = HAMMER2_SET_COUNT;
2681 panic("hammer2_chain_create: unrecognized blockref type: %d",
2689 * Make sure we've counted the brefs
2691 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2692 hammer2_chain_countbrefs(parent, base, count);
2694 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2697 * If no free blockref could be found we must create an indirect
2698 * block and move a number of blockrefs into it. With the parent
2699 * locked we can safely lock each child in order to delete+duplicate
2700 * it without causing a deadlock.
2702 * This may return the new indirect block or the old parent depending
2703 * on where the key falls. NULL is returned on error.
2705 if (above->live_count == count) {
2706 hammer2_chain_t *nparent;
2708 nparent = hammer2_chain_create_indirect(trans, parent,
2711 if (nparent == NULL) {
2713 hammer2_chain_drop(chain);
2717 if (parent != nparent) {
2718 hammer2_chain_unlock(parent);
2719 parent = *parentp = nparent;
2725 * Link the chain into its parent.
2727 if (chain->above != NULL)
2728 panic("hammer2: hammer2_chain_create: chain already connected");
2729 KKASSERT(chain->above == NULL);
2730 hammer2_chain_insert(above, NULL, chain,
2731 HAMMER2_CHAIN_INSERT_SPIN |
2732 HAMMER2_CHAIN_INSERT_LIVE,
2737 * Mark the newly created chain modified. This will cause
2738 * FLUSH_CREATE to be set.
2740 * Device buffers are not instantiated for DATA elements
2741 * as these are handled by logical buffers.
2743 * Indirect and freemap node indirect blocks are handled
2744 * by hammer2_chain_create_indirect() and not by this
2747 * Data for all other bref types is expected to be
2748 * instantiated (INODE, LEAF).
2750 switch(chain->bref.type) {
2751 case HAMMER2_BREF_TYPE_DATA:
2752 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2753 case HAMMER2_BREF_TYPE_INODE:
2754 hammer2_chain_modify(trans, &chain,
2755 HAMMER2_MODIFY_OPTDATA |
2756 HAMMER2_MODIFY_ASSERTNOCOPY);
2760 * Remaining types are not supported by this function.
2761 * In particular, INDIRECT and LEAF_NODE types are
2762 * handled by create_indirect().
2764 panic("hammer2_chain_create: bad type: %d",
2771 * When reconnecting a chain we must set FLUSH_CREATE and
2772 * setsubmod so the flush recognizes that it must update
2773 * the bref in the parent.
2775 if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
2776 hammer2_chain_ref(chain);
2777 atomic_set_int(&chain->flags,
2778 HAMMER2_CHAIN_FLUSH_CREATE);
2781 hammer2_chain_setsubmod(trans, chain);
2790 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2791 * the same core and media state as the orignal. The original *chainp is
2792 * unlocked and the replacement will be returned locked. The duplicated
2793 * chain is inserted under (*parentp).
2795 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2796 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2797 * FULL. This typically means that the caller is creating the chain after
2798 * doing a hammer2_chain_lookup().
2800 * A non-NULL bref is typically passed when key and keybits must be overridden.
2801 * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2802 * from a passed-in bref and uses the old chain's bref for everything else.
2804 * The old chain must be in a DELETED state unless snapshot is non-zero.
2806 * The new chain will be live (i.e. not deleted), and modified.
2808 * If (parent) is non-NULL then the new duplicated chain is inserted under
2811 * If (parent) is NULL then the newly duplicated chain is not inserted
2812 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2813 * passing into hammer2_chain_create() after this function returns).
2815 * WARNING! This function cannot take snapshots all by itself. The caller
2816 * needs to do other massaging for snapshots.
2818 * WARNING! This function calls create which means it can insert indirect
2819 * blocks. Callers may have to refactor locked chains held across
2820 * the call (other than the ones passed into the call).
2823 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2824 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2825 int snapshot, int duplicate_reason)
2827 hammer2_mount_t *hmp;
2828 hammer2_chain_t *parent;
2829 hammer2_chain_t *ochain;
2830 hammer2_chain_t *nchain;
2831 hammer2_chain_core_t *above;
2835 * We want nchain to be our go-to live chain, but ochain may be in
2836 * a MODIFIED state within the current flush synchronization segment.
2837 * Force any further modifications of ochain to do another COW
2838 * operation even if modify_xid indicates that one is not needed.
2840 * We don't want to set FORCECOW on nchain simply as an optimization,
2841 * as many duplication calls simply move chains into ichains and
2842 * then delete the original.
2844 * WARNING! We should never resolve DATA to device buffers
2845 * (XXX allow it if the caller did?), and since
2846 * we currently do not have the logical buffer cache
2847 * buffer in-hand to fix its cached physical offset
2848 * we also force the modify code to not COW it. XXX
2852 KKASSERT(snapshot == 1 || (ochain->flags & HAMMER2_CHAIN_DELETED));
2855 * Now create a duplicate of the chain structure, associating
2856 * it with the same core, making it the same size, pointing it
2857 * to the same bref (the same media block).
2859 * Give nchain the same modify_xid that we previously ensured was
2860 * sufficiently advanced to trigger a block table insertion on flush.
2862 * nchain copies ochain's data and must inherit ochain->update_xlo.
2864 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2865 * hammer2_chain_alloc()
2868 bref = &ochain->bref;
2870 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2871 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2873 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2875 hammer2_chain_core_alloc(trans, nchain, ochain);
2876 bytes = (hammer2_off_t)1 <<
2877 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2878 nchain->bytes = bytes;
2879 nchain->modify_xid = ochain->modify_xid;
2880 nchain->update_xlo = ochain->update_xlo;
2881 nchain->inode_reason = ochain->inode_reason + 0x100000;
2882 atomic_set_int(&nchain->flags,
2883 ochain->flags & (HAMMER2_CHAIN_INITIAL |
2884 HAMMER2_CHAIN_FORCECOW |
2885 HAMMER2_CHAIN_UNLINKED |
2886 HAMMER2_CHAIN_PFSROOT |
2887 HAMMER2_CHAIN_PFSBOUNDARY));
2888 if (ochain->modify_xid == trans->sync_xid)
2889 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2892 * Switch from ochain to nchain
2894 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2895 HAMMER2_RESOLVE_NOREF);
2896 /* nchain has 1 ref */
2897 hammer2_chain_unlock(ochain);
2900 * Place nchain in the modified state, instantiate media data
2901 * if necessary. Because modify_xid is already completely
2902 * synchronized this should not result in a delete-duplicate.
2904 * We want nchain at the target to look like a new insertion.
2905 * Forcing the modification to be INPLACE accomplishes this
2906 * because we get the same nchain with an updated modify_xid.
2908 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2909 hammer2_chain_modify(trans, &nchain,
2910 HAMMER2_MODIFY_OPTDATA |
2911 HAMMER2_MODIFY_NOREALLOC |
2912 HAMMER2_MODIFY_INPLACE);
2913 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2914 hammer2_chain_modify(trans, &nchain,
2915 HAMMER2_MODIFY_OPTDATA |
2916 HAMMER2_MODIFY_INPLACE);
2918 hammer2_chain_modify(trans, &nchain,
2919 HAMMER2_MODIFY_INPLACE);
2923 * If parent is not NULL the duplicated chain will be entered under
2924 * the parent and the FLUSH_CREATE bit set to tell flush to update
2927 * Having both chains locked is extremely important for atomicy.
2929 if (parentp && (parent = *parentp) != NULL) {
2930 above = parent->core;
2931 KKASSERT(ccms_thread_lock_owned(&above->cst));
2932 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2933 KKASSERT(parent->refs > 0);
2935 hammer2_chain_create(trans, parentp, &nchain, nchain->pmp,
2936 nchain->bref.key, nchain->bref.keybits,
2937 nchain->bref.type, nchain->bytes);
2940 KKASSERT(nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE);
2941 hammer2_chain_setsubmod(trans, nchain);
2948 * Helper function for deleting chains.
2950 * The chain is removed from the live view (the RBTREE).
2952 * If appropriate, the chain is added to the shadow topology and FLUSH_DELETE
2953 * is set for flusher visbility. The caller is responsible for calling
2954 * setsubmod on chain, so we do not adjust update_xhi here.
2957 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2958 hammer2_chain_core_t *above,
2959 hammer2_chain_t *chain)
2961 hammer2_mount_t *hmp;
2962 hammer2_chain_t *xchain;
2964 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2965 KKASSERT(trans->sync_xid >= chain->modify_xid);
2966 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2967 HAMMER2_CHAIN_ONDBQ |
2968 HAMMER2_CHAIN_ONDBTREE |
2969 HAMMER2_CHAIN_FLUSH_DELETE)) == 0);
2972 * Flag as deleted, reduce live_count and bump the above core's
2975 chain->delete_xid = trans->sync_xid;
2976 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2977 atomic_add_int(&above->live_count, -1);
2978 ++above->generation;
2982 * Remove from live tree
2984 RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
2985 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2987 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2989 * If the chain was originally bmapped we must place on the
2990 * deleted tree and set FLUSH_DELETE (+ref) to prevent
2991 * destruction of the chain until the flush can reconcile
2992 * the parent's block table.
2994 * NOTE! DBTREE is only representitive of the live view,
2995 * the flush must check both DBTREE and DBQ.
2997 xchain = RB_INSERT(hammer2_chain_tree, &above->dbtree, chain);
2998 KKASSERT(xchain == NULL);
2999 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
3001 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
3002 hammer2_chain_ref(chain);
3005 * If the chain no longer (and never had) an actual blockmap
3006 * entry we must place it on the dbq list and set FLUSH_DELETE
3007 * (+ref) to prevent destruction of the chain until the flush
3008 * can reconcile the parent's block table.
3010 * NOTE! DBTREE is only representitive of the live view,
3011 * the flush must check both DBTREE and DBQ.
3013 TAILQ_INSERT_TAIL(&above->dbq, chain, db_entry);
3014 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
3016 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
3017 hammer2_chain_ref(chain);
3022 * Special in-place delete-duplicate sequence which does not require a
3023 * locked parent. (*chainp) is marked DELETED and atomically replaced
3024 * with a duplicate. Atomicy is at the very-fine spin-lock level in
3025 * order to ensure that lookups do not race us.
3027 * The flush code will sometimes call this function with a deleted chain.
3028 * In this situation the old chain's memory is reallocated without
3031 * The new chain will be marked modified for the current transaction.
3034 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
3037 hammer2_mount_t *hmp;
3038 hammer2_chain_t *ochain;
3039 hammer2_chain_t *nchain;
3040 hammer2_chain_core_t *above;
3044 if (hammer2_debug & 0x20000)
3048 * Note that we do not have to call setsubmod on ochain, calling it
3049 * on nchain is sufficient.
3052 oflags = ochain->flags; /* flags prior to core_alloc mods */
3055 if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
3056 KKASSERT(ochain->data);
3060 * First create a duplicate of the chain structure.
3061 * (nchain is allocated with one ref).
3063 * In the case where nchain inherits ochains core, nchain is
3064 * effectively locked due to ochain being locked (and sharing the
3065 * core), until we can give nchain its own official ock.
3067 * WARNING! Flusher concurrency can create two cases. The first is
3068 * that the flusher might be working on a chain that has
3069 * been deleted in the live view but is live in the flusher's
3070 * view. In the second case the flusher may be duplicating
3071 * a forward-transacted chain. In both situations nchain
3072 * must be marked deleted.
3074 * WARNING! hammer2_chain_core_alloc() also acts on these issues.
3076 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
3077 if ((ochain->flags & HAMMER2_CHAIN_DELETED) ||
3078 (ochain->modify_xid > trans->sync_xid)) {
3079 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
3081 if (flags & HAMMER2_DELDUP_RECORE)
3082 hammer2_chain_core_alloc(trans, nchain, NULL);
3084 hammer2_chain_core_alloc(trans, nchain, ochain);
3085 above = ochain->above;
3087 bytes = (hammer2_off_t)1 <<
3088 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3089 nchain->bytes = bytes;
3092 * nchain inherits ochain's live state including its modification
3093 * state. This function disposes of the original. Because we are
3094 * doing this in-place under the same parent the block array
3095 * inserted/deleted state does not change.
3097 * nchain copies ochain's data and must inherit ochain->update_xlo.
3099 * If ochain was previously marked FORCECOW we also flag nchain
3100 * FORCECOW (used during hardlink splits). FORCECOW forces a
3101 * reallocation of the block when we modify the chain a little later,
3102 * it does not force another delete-duplicate.
3104 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
3105 * hammer2_chain_alloc()
3107 nchain->data_count += ochain->data_count;
3108 nchain->inode_count += ochain->inode_count;
3109 atomic_set_int(&nchain->flags,
3110 ochain->flags & (HAMMER2_CHAIN_INITIAL |
3111 HAMMER2_CHAIN_FORCECOW |
3112 HAMMER2_CHAIN_UNLINKED |
3113 HAMMER2_CHAIN_PFSROOT |
3114 HAMMER2_CHAIN_PFSBOUNDARY));
3115 if (ochain->modify_xid == trans->sync_xid)
3116 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
3117 nchain->inode_reason = ochain->inode_reason + 0x1000;
3118 nchain->update_xlo = ochain->update_xlo;
3121 * Lock nchain so both chains are now locked (extremely important
3122 * for atomicy). The shared core allows us to unlock ochain without
3123 * actually unlocking ochain.
3125 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
3126 /* extra ref still present from original allocation */
3128 KKASSERT(ochain->flags & (HAMMER2_CHAIN_ONRBTREE |
3129 HAMMER2_CHAIN_ONDBTREE |
3130 HAMMER2_CHAIN_ONDBQ));
3131 spin_lock(&above->cst.spin);
3133 nchain->modify_xid = ochain->modify_xid;
3134 nchain->delete_xid = HAMMER2_XID_MAX;
3136 if ((nchain->flags & HAMMER2_CHAIN_DELETED) &&
3137 (oflags & HAMMER2_CHAIN_DUPLICATED)) {
3139 * Special case, used by the flush code when a chain which
3140 * has been delete-duplicated is visible (effectively 'live')
3141 * in the flush code.
3143 * In this situations nchain will be marked deleted and
3144 * insert before ochain. nchain must inherit certain features
3147 KKASSERT(trans->flags & HAMMER2_TRANS_ISFLUSH);
3148 KKASSERT(ochain->modify_xid < trans->sync_xid);
3149 KKASSERT(ochain->delete_xid > trans->sync_xid);
3150 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_TEMPORARY);
3151 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3153 if ((ochain->flags & HAMMER2_CHAIN_DELETED) &&
3154 ochain->modify_xid < trans->sync_xid) {
3155 nchain->delete_xid = ochain->delete_xid;
3156 ochain->delete_xid = trans->sync_xid;
3157 } else if (ochain->modify_xid > trans->sync_xid) {
3158 nchain->delete_xid = ochain->modify_xid;
3160 } else if (nchain->flags & HAMMER2_CHAIN_DELETED) {
3162 * ochain is 'live' with respect to not having been D-D'd,
3163 * but is flagged DELETED. Sometimes updates to deleted
3164 * chains must be allowed due to references which still exist
3165 * on those chains, or due to a flush trying to retire a
3166 * logical buffer cache buffer.
3168 * In this situation the D-D operates normally, except
3169 * ochain has already been deleted and nchain is also
3172 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3173 nchain->delete_xid = trans->sync_xid;
3176 * Normal case, delete-duplicate deletes ochain and nchain
3177 * is the new live chain.
3179 _hammer2_chain_delete_helper(trans, above, ochain);
3180 hammer2_chain_insert(above, ochain, nchain,
3181 HAMMER2_CHAIN_INSERT_LIVE, 0);
3183 spin_unlock(&above->cst.spin);
3186 * ochain must be unlocked because ochain and nchain might share
3187 * a buffer cache buffer, so we need to release it so nchain can
3188 * potentially obtain it.
3190 hammer2_chain_setsubmod(trans, ochain);
3191 hammer2_chain_unlock(ochain);
3194 * Finishing fixing up nchain. A new block will be allocated if
3195 * crossing a synchronization point (meta-data only).
3197 * Calling hammer2_chain_modify() will update modify_xid to
3198 * (typically) trans->sync_xid.
3200 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3201 hammer2_chain_modify(trans, &nchain,
3202 HAMMER2_MODIFY_OPTDATA |
3203 HAMMER2_MODIFY_NOREALLOC |
3204 HAMMER2_MODIFY_INPLACE);
3205 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3206 hammer2_chain_modify(trans, &nchain,
3207 HAMMER2_MODIFY_OPTDATA |
3208 HAMMER2_MODIFY_INPLACE);
3210 hammer2_chain_modify(trans, &nchain,
3211 HAMMER2_MODIFY_INPLACE);
3213 hammer2_chain_drop(nchain);
3216 * Unconditionally set FLUSH_CREATE to force the parent blockrefs to
3217 * update as the chain_modify() above won't necessarily do it.
3219 if ((nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
3220 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
3221 hammer2_chain_ref(nchain);
3225 * If nchain is in a DELETED state we must set FLUSH_DELETE
3227 if (nchain->flags & HAMMER2_CHAIN_DELETED)
3228 KKASSERT((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0);
3230 if ((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0 &&
3231 (nchain->flags & HAMMER2_CHAIN_DELETED)) {
3232 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
3233 hammer2_chain_ref(nchain);
3236 hammer2_chain_setsubmod(trans, nchain);
3241 * Create an indirect block that covers one or more of the elements in the
3242 * current parent. Either returns the existing parent with no locking or
3243 * ref changes or returns the new indirect block locked and referenced
3244 * and leaving the original parent lock/ref intact as well.
3246 * If an error occurs, NULL is returned and *errorp is set to the error.
3248 * The returned chain depends on where the specified key falls.
3250 * The key/keybits for the indirect mode only needs to follow three rules:
3252 * (1) That all elements underneath it fit within its key space and
3254 * (2) That all elements outside it are outside its key space.
3256 * (3) When creating the new indirect block any elements in the current
3257 * parent that fit within the new indirect block's keyspace must be
3258 * moved into the new indirect block.
3260 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3261 * keyspace the the current parent, but lookup/iteration rules will
3262 * ensure (and must ensure) that rule (2) for all parents leading up
3263 * to the nearest inode or the root volume header is adhered to. This
3264 * is accomplished by always recursing through matching keyspaces in
3265 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3267 * The current implementation calculates the current worst-case keyspace by
3268 * iterating the current parent and then divides it into two halves, choosing
3269 * whichever half has the most elements (not necessarily the half containing
3270 * the requested key).
3272 * We can also opt to use the half with the least number of elements. This
3273 * causes lower-numbered keys (aka logical file offsets) to recurse through
3274 * fewer indirect blocks and higher-numbered keys to recurse through more.
3275 * This also has the risk of not moving enough elements to the new indirect
3276 * block and being forced to create several indirect blocks before the element
3279 * Must be called with an exclusively locked parent.
3281 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3282 hammer2_key_t *keyp, int keybits,
3283 hammer2_blockref_t *base, int count);
3284 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3285 hammer2_key_t *keyp, int keybits,
3286 hammer2_blockref_t *base, int count);
3289 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3290 hammer2_key_t create_key, int create_bits,
3291 int for_type, int *errorp)
3293 hammer2_mount_t *hmp;
3294 hammer2_chain_core_t *above;
3295 hammer2_chain_core_t *icore;
3296 hammer2_blockref_t *base;
3297 hammer2_blockref_t *bref;
3298 hammer2_blockref_t bcopy;
3299 hammer2_chain_t *chain;
3300 hammer2_chain_t *ichain;
3301 hammer2_chain_t dummy;
3302 hammer2_key_t key = create_key;
3303 hammer2_key_t key_beg;
3304 hammer2_key_t key_end;
3305 hammer2_key_t key_next;
3306 int keybits = create_bits;
3313 int maxloops = 300000;
3318 * Calculate the base blockref pointer or NULL if the chain
3319 * is known to be empty. We need to calculate the array count
3320 * for RB lookups either way.
3324 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3325 above = parent->core;
3327 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3328 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3331 switch(parent->bref.type) {
3332 case HAMMER2_BREF_TYPE_INODE:
3333 count = HAMMER2_SET_COUNT;
3335 case HAMMER2_BREF_TYPE_INDIRECT:
3336 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3337 count = parent->bytes / sizeof(hammer2_blockref_t);
3339 case HAMMER2_BREF_TYPE_VOLUME:
3340 count = HAMMER2_SET_COUNT;
3342 case HAMMER2_BREF_TYPE_FREEMAP:
3343 count = HAMMER2_SET_COUNT;
3346 panic("hammer2_chain_create_indirect: "
3347 "unrecognized blockref type: %d",
3353 switch(parent->bref.type) {
3354 case HAMMER2_BREF_TYPE_INODE:
3355 base = &parent->data->ipdata.u.blockset.blockref[0];
3356 count = HAMMER2_SET_COUNT;
3358 case HAMMER2_BREF_TYPE_INDIRECT:
3359 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3360 base = &parent->data->npdata[0];
3361 count = parent->bytes / sizeof(hammer2_blockref_t);
3363 case HAMMER2_BREF_TYPE_VOLUME:
3364 base = &hmp->voldata.sroot_blockset.blockref[0];
3365 count = HAMMER2_SET_COUNT;
3367 case HAMMER2_BREF_TYPE_FREEMAP:
3368 base = &hmp->voldata.freemap_blockset.blockref[0];
3369 count = HAMMER2_SET_COUNT;
3372 panic("hammer2_chain_create_indirect: "
3373 "unrecognized blockref type: %d",
3381 * dummy used in later chain allocation (no longer used for lookups).
3383 bzero(&dummy, sizeof(dummy));
3384 dummy.delete_xid = HAMMER2_XID_MAX;
3387 * When creating an indirect block for a freemap node or leaf
3388 * the key/keybits must be fitted to static radix levels because
3389 * particular radix levels use particular reserved blocks in the
3392 * This routine calculates the key/radix of the indirect block
3393 * we need to create, and whether it is on the high-side or the
3396 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3397 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3398 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3401 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3406 * Normalize the key for the radix being represented, keeping the
3407 * high bits and throwing away the low bits.
3409 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3412 * How big should our new indirect block be? It has to be at least
3413 * as large as its parent.
3415 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3416 nbytes = HAMMER2_IND_BYTES_MIN;
3418 nbytes = HAMMER2_IND_BYTES_MAX;
3419 if (nbytes < count * sizeof(hammer2_blockref_t))
3420 nbytes = count * sizeof(hammer2_blockref_t);
3423 * Ok, create our new indirect block
3425 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3426 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3427 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3429 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3431 dummy.bref.key = key;
3432 dummy.bref.keybits = keybits;
3433 dummy.bref.data_off = hammer2_getradix(nbytes);
3434 dummy.bref.methods = parent->bref.methods;
3436 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3437 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3438 hammer2_chain_core_alloc(trans, ichain, NULL);
3439 icore = ichain->core;
3440 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3441 hammer2_chain_drop(ichain); /* excess ref from alloc */
3444 * We have to mark it modified to allocate its block, but use
3445 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3446 * it won't be acted upon by the flush code.
3448 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3451 * Iterate the original parent and move the matching brefs into
3452 * the new indirect block.
3454 * XXX handle flushes.
3457 key_end = HAMMER2_KEY_MAX;
3459 spin_lock(&above->cst.spin);
3465 if (++loops > 100000) {
3466 spin_unlock(&above->cst.spin);
3467 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3468 reason, parent, base, count, key_next);
3472 * NOTE: spinlock stays intact, returned chain (if not NULL)
3473 * is not referenced or locked which means that we
3474 * cannot safely check its flagged / deletion status
3477 chain = hammer2_combined_find(parent, base, count,
3478 &cache_index, &key_next,
3481 generation = above->generation;
3484 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3487 * Skip keys that are not within the key/radix of the new
3488 * indirect block. They stay in the parent.
3490 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3491 (key ^ bref->key)) != 0) {
3492 goto next_key_spinlocked;
3496 * Load the new indirect block by acquiring the related
3497 * chains (potentially from media as it might not be
3498 * in-memory). Then move it to the new parent (ichain)
3499 * via DELETE-DUPLICATE.
3501 * chain is referenced but not locked. We must lock the
3502 * chain to obtain definitive DUPLICATED/DELETED state
3506 * Use chain already present in the RBTREE
3508 hammer2_chain_ref(chain);
3509 wasdup = ((chain->flags &
3510 HAMMER2_CHAIN_DUPLICATED) != 0);
3511 spin_unlock(&above->cst.spin);
3512 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3513 HAMMER2_RESOLVE_NOREF);
3516 * Get chain for blockref element. _get returns NULL
3517 * on insertion race.
3520 spin_unlock(&above->cst.spin);
3521 chain = hammer2_chain_get(parent, generation, &bcopy);
3522 if (chain == NULL) {
3524 spin_lock(&above->cst.spin);
3527 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3529 hammer2_chain_drop(chain);
3530 spin_lock(&above->cst.spin);
3533 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3534 HAMMER2_RESOLVE_NOREF);
3539 * This is always live so if the chain has been delete-
3540 * duplicated we raced someone and we have to retry.
3542 * NOTE: Lookups can race delete-duplicate because
3543 * delete-duplicate does not lock the parent's core
3544 * (they just use the spinlock on the core). We must
3545 * check for races by comparing the DUPLICATED flag before
3546 * releasing the spinlock with the flag after locking the
3549 * (note reversed logic for this one)
3551 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3552 hammer2_chain_unlock(chain);
3553 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) &&
3561 * Shift the chain to the indirect block.
3563 * WARNING! Can cause held-over chains to require a refactor.
3564 * Fortunately we have none (our locked chains are
3565 * passed into and modified by the call).
3567 hammer2_chain_delete(trans, chain, 0);
3568 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0, 1);
3569 hammer2_chain_unlock(chain);
3570 KKASSERT(parent->refs > 0);
3573 spin_lock(&above->cst.spin);
3574 next_key_spinlocked:
3575 if (--maxloops == 0)
3576 panic("hammer2_chain_create_indirect: maxloops");
3578 if (retry_same == 0) {
3579 if (key_next == 0 || key_next > key_end)
3585 spin_unlock(&above->cst.spin);
3588 * Insert the new indirect block into the parent now that we've
3589 * cleared out some entries in the parent. We calculated a good
3590 * insertion index in the loop above (ichain->index).
3592 * We don't have to set FLUSH_CREATE here because we mark ichain
3593 * modified down below (so the normal modified -> flush -> set-moved
3594 * sequence applies).
3596 * The insertion shouldn't race as this is a completely new block
3597 * and the parent is locked.
3599 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3600 hammer2_chain_insert(above, NULL, ichain,
3601 HAMMER2_CHAIN_INSERT_SPIN |
3602 HAMMER2_CHAIN_INSERT_LIVE,
3606 * Mark the new indirect block modified after insertion, which
3607 * will propagate up through parent all the way to the root and
3608 * also allocate the physical block in ichain for our caller,
3609 * and assign ichain->data to a pre-zero'd space (because there
3610 * is not prior data to copy into it).
3612 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
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_KEY_MAX;
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,
3696 * NOTE: No need to check DUPLICATED here because we do
3697 * not release the spinlock.
3699 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3700 if (key_next == 0 || key_next > key_end)
3707 * Use the full live (not deleted) element for the scan
3708 * iteration. HAMMER2 does not allow partial replacements.
3710 * XXX should be built into hammer2_combined_find().
3712 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3714 if (keybits > bref->keybits) {
3716 keybits = bref->keybits;
3717 } else if (keybits == bref->keybits && bref->key < key) {
3724 spin_unlock(&above->cst.spin);
3727 * Return the keybits for a higher-level FREEMAP_NODE covering
3731 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3732 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3734 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3735 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3737 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3738 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3740 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3741 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3743 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3744 panic("hammer2_chain_indkey_freemap: level too high");
3747 panic("hammer2_chain_indkey_freemap: bad radix");
3756 * Calculate the keybits and highside/lowside of the indirect block the
3757 * caller is creating.
3760 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3761 int keybits, hammer2_blockref_t *base, int count)
3763 hammer2_chain_core_t *above;
3764 hammer2_blockref_t *bref;
3765 hammer2_chain_t *chain;
3766 hammer2_key_t key_beg;
3767 hammer2_key_t key_end;
3768 hammer2_key_t key_next;
3774 int maxloops = 300000;
3777 above = parent->core;
3782 * Calculate the range of keys in the array being careful to skip
3783 * slots which are overridden with a deletion. Once the scan
3784 * completes we will cut the key range in half and shift half the
3785 * range into the new indirect block.
3788 key_end = HAMMER2_KEY_MAX;
3790 spin_lock(&above->cst.spin);
3793 if (--maxloops == 0) {
3794 panic("indkey_freemap shit %p %p:%d\n",
3795 parent, base, count);
3797 chain = hammer2_combined_find(parent, base, count,
3798 &cache_index, &key_next,
3809 * NOTE: No need to check DUPLICATED here because we do
3810 * not release the spinlock.
3812 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3813 if (key_next == 0 || key_next > key_end)
3820 * Use the full live (not deleted) element for the scan
3821 * iteration. HAMMER2 does not allow partial replacements.
3823 * XXX should be built into hammer2_combined_find().
3825 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3828 * Expand our calculated key range (key, keybits) to fit
3829 * the scanned key. nkeybits represents the full range
3830 * that we will later cut in half (two halves @ nkeybits - 1).
3833 if (nkeybits < bref->keybits) {
3834 if (bref->keybits > 64) {
3835 kprintf("bad bref chain %p bref %p\n",
3839 nkeybits = bref->keybits;
3841 while (nkeybits < 64 &&
3842 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3843 (key ^ bref->key)) != 0) {
3848 * If the new key range is larger we have to determine
3849 * which side of the new key range the existing keys fall
3850 * under by checking the high bit, then collapsing the
3851 * locount into the hicount or vise-versa.
3853 if (keybits != nkeybits) {
3854 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3865 * The newly scanned key will be in the lower half or the
3866 * upper half of the (new) key range.
3868 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3877 spin_unlock(&above->cst.spin);
3878 bref = NULL; /* now invalid (safety) */
3881 * Adjust keybits to represent half of the full range calculated
3882 * above (radix 63 max)
3887 * Select whichever half contains the most elements. Theoretically
3888 * we can select either side as long as it contains at least one
3889 * element (in order to ensure that a free slot is present to hold
3890 * the indirect block).
3892 if (hammer2_indirect_optimize) {
3894 * Insert node for least number of keys, this will arrange
3895 * the first few blocks of a large file or the first few
3896 * inodes in a directory with fewer indirect blocks when
3899 if (hicount < locount && hicount != 0)
3900 key |= (hammer2_key_t)1 << keybits;
3902 key &= ~(hammer2_key_t)1 << keybits;
3905 * Insert node for most number of keys, best for heavily
3908 if (hicount > locount)
3909 key |= (hammer2_key_t)1 << keybits;
3911 key &= ~(hammer2_key_t)1 << keybits;
3919 * Sets CHAIN_DELETED and CHAIN_FLUSH_DELETE in the chain being deleted and
3920 * set chain->delete_xid. The chain is not actually marked possibly-free
3921 * in the freemap until the deletion is completely flushed out (because
3922 * a flush which doesn't cover the entire deletion is flushing the deleted
3923 * chain as if it were live).
3925 * This function does NOT generate a modification to the parent. It
3926 * would be nearly impossible to figure out which parent to modify anyway.
3927 * Such modifications are handled top-down by the flush code and are
3928 * properly merged using the flush synchronization point.
3930 * The find/get code will properly overload the RBTREE check on top of
3931 * the bref check to detect deleted entries.
3933 * This function is NOT recursive. Any entity already pushed into the
3934 * chain (such as an inode) may still need visibility into its contents,
3935 * as well as the ability to read and modify the contents. For example,
3936 * for an unlinked file which is still open.
3938 * NOTE: Deletions normally do not occur in the middle of a duplication
3939 * chain but we use a trick for hardlink migration that refactors
3940 * the originating inode without deleting it, so we make no assumptions
3944 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3946 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3949 * Nothing to do if already marked.
3951 if (chain->flags & HAMMER2_CHAIN_DELETED)
3955 * The setting of DELETED causes finds, lookups, and _next iterations
3956 * to no longer recognize the chain. RB_SCAN()s will still have
3957 * visibility (needed for flush serialization points).
3959 * We need the spinlock on the core whos RBTREE contains chain
3960 * to protect against races.
3962 spin_lock(&chain->above->cst.spin);
3963 _hammer2_chain_delete_helper(trans, chain->above, chain);
3964 spin_unlock(&chain->above->cst.spin);
3966 hammer2_chain_setsubmod(trans, chain);
3970 * Returns the index of the nearest element in the blockref array >= elm.
3971 * Returns (count) if no element could be found. If delete_filter is non-zero
3972 * the scan filters out any blockrefs which match deleted chains on dbtree.
3974 * Sets *key_nextp to the next key for loop purposes but does not modify
3975 * it if the next key would be higher than the current value of *key_nextp.
3976 * Note that *key_nexp can overflow to 0, which should be tested by the
3979 * (*cache_indexp) is a heuristic and can be any value without effecting
3982 * The spin lock on the related chain must be held.
3985 hammer2_base_find(hammer2_chain_t *parent,
3986 hammer2_blockref_t *base, int count,
3987 int *cache_indexp, hammer2_key_t *key_nextp,
3988 hammer2_key_t key_beg, hammer2_key_t key_end,
3991 hammer2_chain_core_t *core = parent->core;
3992 hammer2_blockref_t *scan;
3993 hammer2_key_t scan_end;
3998 * Require the live chain's already have their core's counted
3999 * so we can optimize operations.
4001 KKASSERT((parent->flags & HAMMER2_CHAIN_DUPLICATED) ||
4002 core->flags & HAMMER2_CORE_COUNTEDBREFS);
4007 if (count == 0 || base == NULL)
4011 * Sequential optimization using *cache_indexp. This is the most
4014 * We can avoid trailing empty entries on live chains, otherwise
4015 * we might have to check the whole block array.
4019 if (parent->flags & HAMMER2_CHAIN_DUPLICATED)
4022 limit = core->live_zero;
4027 KKASSERT(i < count);
4033 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4040 * Search forwards, stop when we find a scan element which
4041 * encloses the key or until we know that there are no further
4045 if (scan->type != 0) {
4046 scan_end = scan->key +
4047 ((hammer2_key_t)1 << scan->keybits) - 1;
4048 if (scan->key > key_beg || scan_end >= key_beg) {
4050 * Check to see if the entry is covered by
4051 * a deleted chain and ignore the entry if
4052 * it is and delete_filter != 0.
4054 if (delete_filter == 0)
4056 if (hammer2_chain_find_deleted(
4057 parent, scan->key, scan_end) == NULL) {
4072 scan_end = scan->key +
4073 ((hammer2_key_t)1 << scan->keybits);
4074 if (scan_end && (*key_nextp > scan_end ||
4076 *key_nextp = scan_end;
4084 * Do a combined search and return the next match either from the blockref
4085 * array or from the in-memory chain. Sets *bresp to the returned bref in
4086 * both cases, or sets it to NULL if the search exhausted. Only returns
4087 * a non-NULL chain if the search matched from the in-memory chain.
4089 * When no in-memory chain has been found and a non-NULL bref is returned
4092 * Must be called with above's spinlock held. Spinlock remains held
4093 * through the operation.
4095 * The returned chain is not locked or referenced. Use the returned bref
4096 * to determine if the search exhausted or not. Iterate if the base find
4097 * is chosen but matches a deleted chain.
4099 static hammer2_chain_t *
4100 hammer2_combined_find(hammer2_chain_t *parent,
4101 hammer2_blockref_t *base, int count,
4102 int *cache_indexp, hammer2_key_t *key_nextp,
4103 hammer2_key_t key_beg, hammer2_key_t key_end,
4104 hammer2_blockref_t **bresp)
4106 hammer2_blockref_t *bref;
4107 hammer2_chain_t *chain;
4111 * Lookup in block array and in rbtree.
4113 *key_nextp = key_end + 1;
4114 i = hammer2_base_find(parent, base, count, cache_indexp,
4115 key_nextp, key_beg, key_end, 1);
4116 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4121 if (i == count && chain == NULL) {
4127 * Only chain matched.
4130 bref = &chain->bref;
4135 * Only blockref matched.
4137 if (chain == NULL) {
4143 * Both in-memory and blockref matched, select the nearer element.
4145 * If both are flush with the left-hand side or both are the
4146 * same distance away, select the chain. In this situation the
4147 * chain must have been loaded from the matching blockmap.
4149 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4150 chain->bref.key == base[i].key) {
4151 KKASSERT(chain->bref.key == base[i].key);
4152 if ((chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
4153 kprintf("chain not bmapped %p.%d %08x\n",
4154 chain, chain->bref.type, chain->flags);
4155 kprintf("in chain mod/del %08x %08x\n",
4156 chain->modify_xid, chain->delete_xid);
4157 kprintf("and updlo/hi %08x %08x\n",
4158 chain->update_xlo, chain->update_xhi);
4160 KKASSERT(chain->flags & HAMMER2_CHAIN_BMAPPED);
4161 bref = &chain->bref;
4166 * Select the nearer key
4168 if (chain->bref.key < base[i].key) {
4169 bref = &chain->bref;
4176 * If the bref is out of bounds we've exhausted our search.
4179 if (bref->key > key_end) {
4189 * Locate the specified block array element and delete it. The element
4192 * The spin lock on the related chain must be held.
4194 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4195 * need to be adjusted when we commit the media change.
4198 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
4199 hammer2_blockref_t *base, int count,
4200 int *cache_indexp, hammer2_chain_t *child)
4202 hammer2_blockref_t *elm = &child->bref;
4203 hammer2_chain_core_t *core = parent->core;
4204 hammer2_key_t key_next;
4208 * Delete element. Expect the element to exist.
4210 * XXX see caller, flush code not yet sophisticated enough to prevent
4211 * re-flushed in some cases.
4213 key_next = 0; /* max range */
4214 i = hammer2_base_find(parent, base, count, cache_indexp,
4215 &key_next, elm->key, elm->key, 0);
4216 if (i == count || base[i].type == 0 ||
4217 base[i].key != elm->key || base[i].keybits != elm->keybits) {
4218 spin_unlock(&core->cst.spin);
4219 panic("delete base %p element not found at %d/%d elm %p\n"
4220 "child ino_reason=%08x\n",
4221 base, i, count, elm,
4222 child->inode_reason);
4225 bzero(&base[i], sizeof(*base));
4228 * We can only optimize core->live_zero for live chains.
4230 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4231 if (core->live_zero == i + 1) {
4232 while (--i >= 0 && base[i].type == 0)
4234 core->live_zero = i + 1;
4240 * Insert the specified element. The block array must not already have the
4241 * element and must have space available for the insertion.
4243 * The spin lock on the related chain must be held.
4245 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4246 * need to be adjusted when we commit the media change.
4249 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
4250 hammer2_blockref_t *base, int count,
4251 int *cache_indexp, hammer2_chain_t *child)
4253 hammer2_blockref_t *elm = &child->bref;
4254 hammer2_chain_core_t *core = parent->core;
4255 hammer2_key_t key_next;
4264 * Insert new element. Expect the element to not already exist
4265 * unless we are replacing it.
4267 * XXX see caller, flush code not yet sophisticated enough to prevent
4268 * re-flushed in some cases.
4270 key_next = 0; /* max range */
4271 i = hammer2_base_find(parent, base, count, cache_indexp,
4272 &key_next, elm->key, elm->key, 0);
4275 * Shortcut fill optimization, typical ordered insertion(s) may not
4278 KKASSERT(i >= 0 && i <= count);
4281 * We can only optimize core->live_zero for live chains.
4283 if (i == count && core->live_zero < count) {
4284 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4285 i = core->live_zero++;
4291 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4292 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4293 if (child->flags & HAMMER2_CHAIN_FLUSH_TEMPORARY) {
4294 kprintf("child %p special replace\n", child);
4298 spin_unlock(&core->cst.spin);
4299 panic("insert base %p overlapping "
4300 "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 * chain may have been moved around by the create.
4466 hammer2_chain_refactor(hammer2_chain_t **chainp)
4468 hammer2_chain_t *chain = *chainp;
4469 hammer2_chain_core_t *core;
4472 while (chain->flags & HAMMER2_CHAIN_DUPLICATED) {
4473 spin_lock(&core->cst.spin);
4474 chain = TAILQ_NEXT(chain, core_entry);
4475 while (chain->flags & HAMMER2_CHAIN_DUPLICATED)
4476 chain = TAILQ_NEXT(chain, core_entry);
4477 hammer2_chain_ref(chain);
4478 spin_unlock(&core->cst.spin);
4479 KKASSERT(chain->core == core);
4481 hammer2_chain_unlock(*chainp);
4482 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS |
4483 HAMMER2_RESOLVE_NOREF); /* eat ref */