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 void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
90 static hammer2_chain_t *hammer2_combined_find(
91 hammer2_chain_t *parent,
92 hammer2_blockref_t *base, int count,
93 int *cache_indexp, hammer2_key_t *key_nextp,
94 hammer2_key_t key_beg, hammer2_key_t key_end,
95 hammer2_blockref_t **bresp);
98 * Basic RBTree for chains (core->rbtree and core->dbtree). Chains cannot
99 * overlap in the RB trees. Deleted chains are moved from rbtree to either
102 * Chains in delete-duplicate sequences can always iterate through core_entry
103 * to locate the live version of the chain.
105 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
108 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
110 hammer2_key_t c1_beg;
111 hammer2_key_t c1_end;
112 hammer2_key_t c2_beg;
113 hammer2_key_t c2_end;
116 * Compare chains. Overlaps are not supposed to happen and catch
117 * any software issues early we count overlaps as a match.
119 c1_beg = chain1->bref.key;
120 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
121 c2_beg = chain2->bref.key;
122 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
124 if (c1_end < c2_beg) /* fully to the left */
126 if (c1_beg > c2_end) /* fully to the right */
128 return(0); /* overlap (must not cross edge boundary) */
133 hammer2_isclusterable(hammer2_chain_t *chain)
135 if (hammer2_cluster_enable) {
136 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
137 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
138 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
146 * Recursively set update_hi starting at chain up through to the root.
148 * This controls top-down visibility for flushes. The child has just one
149 * 'above' core, but the core itself can be multi-homed with parents iterated
150 * via core->ownerq. The last parent is the 'live' parent (all others had to
151 * have been delete-duplicated). We always propagate upward through the live
154 * This function is not used during a flush (except when the flush is
155 * allocating which requires the live tree). The flush keeps track of its
161 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
163 hammer2_chain_core_t *above;
165 if (chain->update_hi < trans->sync_tid)
166 chain->update_hi = trans->sync_tid;
168 while ((above = chain->above) != NULL) {
169 spin_lock(&above->cst.spin);
170 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
171 if (chain->update_hi < trans->sync_tid)
172 chain->update_hi = trans->sync_tid;
173 spin_unlock(&above->cst.spin);
178 * Allocate a new disconnected chain element representing the specified
179 * bref. chain->refs is set to 1 and the passed bref is copied to
180 * chain->bref. chain->bytes is derived from the bref.
182 * chain->core is NOT allocated and the media data and bp pointers are left
183 * NULL. The caller must call chain_core_alloc() to allocate or associate
184 * a core with the chain.
186 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
189 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
190 hammer2_trans_t *trans, hammer2_blockref_t *bref)
192 hammer2_chain_t *chain;
193 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
196 * Construct the appropriate system structure.
199 case HAMMER2_BREF_TYPE_INODE:
200 case HAMMER2_BREF_TYPE_INDIRECT:
201 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
202 case HAMMER2_BREF_TYPE_DATA:
203 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
205 * Chain's are really only associated with the hmp but we
206 * maintain a pmp association for per-mount memory tracking
207 * purposes. The pmp can be NULL.
209 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
213 case HAMMER2_BREF_TYPE_VOLUME:
214 case HAMMER2_BREF_TYPE_FREEMAP:
216 panic("hammer2_chain_alloc volume type illegal for op");
219 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
225 chain->bytes = bytes;
227 chain->flags = HAMMER2_CHAIN_ALLOCATED;
228 chain->delete_tid = HAMMER2_MAX_TID;
231 * Set modify_tid if a transaction is creating the inode.
232 * Enforce update_lo = 0 so nearby transactions do not think
233 * it has been flushed when it hasn't.
235 * NOTE: When loading a chain from backing store or creating a
236 * snapshot, trans will be NULL and the caller is responsible
237 * for setting these fields.
240 chain->modify_tid = trans->sync_tid;
241 chain->update_lo = 0;
248 * Associate an existing core with the chain or allocate a new core.
250 * The core is not locked. No additional refs on the chain are made.
251 * (trans) must not be NULL if (core) is not NULL.
253 * When chains are delete-duplicated during flushes we insert nchain on
254 * the ownerq after ochain instead of at the end in order to give the
255 * drop code visibility in the correct order, otherwise drops can be missed.
258 hammer2_chain_core_alloc(hammer2_trans_t *trans,
259 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
261 hammer2_chain_core_t *core;
263 KKASSERT(nchain->core == NULL);
265 if (ochain == NULL) {
267 * Fresh core under nchain (no multi-homing of ochain's
270 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
272 TAILQ_INIT(&core->ownerq);
273 TAILQ_INIT(&core->dbq);
274 RB_INIT(&core->rbtree); /* live chains */
275 RB_INIT(&core->dbtree); /* deleted original (bmapped) chains */
279 ccms_cst_init(&core->cst, nchain);
280 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
283 * Propagate the PFSROOT flag which we set on all subdirs
284 * under the super-root.
286 atomic_set_int(&nchain->flags,
287 ochain->flags & HAMMER2_CHAIN_PFSROOT);
290 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
291 * ochain if nchain is not a snapshot.
293 * It is possible for the DUPLICATED flag to already be
294 * set when called via a flush operation because flush
295 * operations may have to work on elements with delete_tid's
296 * beyond the flush sync_tid. In this situation we must
297 * ensure that nchain is placed just after ochain in the
298 * ownerq and that the DUPLICATED flag is set on nchain so
299 * 'live' operations skip past it to the correct chain.
301 * The flusher understands the blockref synchronization state
302 * for any stale chains by observing bref.mirror_tid, which
303 * delete-duplicate replicates.
305 * WARNING! However, the case is disallowed when the flusher
306 * is allocating freemap space because this entails
307 * more than just adjusting a block table.
309 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
310 KKASSERT((trans->flags &
311 (HAMMER2_TRANS_ISFLUSH |
312 HAMMER2_TRANS_ISALLOCATING)) ==
313 HAMMER2_TRANS_ISFLUSH);
314 atomic_set_int(&nchain->flags,
315 HAMMER2_CHAIN_DUPLICATED);
317 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
318 atomic_set_int(&ochain->flags,
319 HAMMER2_CHAIN_DUPLICATED);
322 atomic_add_int(&core->sharecnt, 1);
324 spin_lock(&core->cst.spin);
328 * Maintain ordering for refactor test so we don't skip over
329 * a snapshot. Also, during flushes, delete-duplications
330 * for block-table updates can occur on ochains already
331 * deleted (delete-duplicated by a later transaction), or
332 * on forward-indexed ochains. We must properly insert
333 * nchain relative to ochain.
335 if (trans && trans->sync_tid < ochain->modify_tid) {
336 TAILQ_INSERT_BEFORE(ochain, nchain, core_entry);
338 TAILQ_INSERT_AFTER(&core->ownerq, ochain,
341 spin_unlock(&core->cst.spin);
346 * Add a reference to a chain element, preventing its destruction.
349 hammer2_chain_ref(hammer2_chain_t *chain)
351 atomic_add_int(&chain->refs, 1);
355 * Insert the chain in the core rbtree.
357 * Normal insertions are placed in the live rbtree. Insertion of a deleted
358 * chain is a special case used by the flush code that is placed on the
359 * unstaged deleted list to avoid confusing the live view.
361 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
362 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
363 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
367 hammer2_chain_insert(hammer2_chain_core_t *above,
368 hammer2_chain_t *ochain, hammer2_chain_t *nchain,
369 int flags, int generation)
371 hammer2_chain_t *xchain;
374 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
375 spin_lock(&above->cst.spin);
378 * Interlocked by spinlock, check for race
380 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
381 above->generation != generation) {
389 * XXX BMAPPED might not be handled correctly for ochain/nchain
390 * ordering in both DELETED cases (flush and non-flush-term),
391 * so delete-duplicate code.
393 if (nchain->flags & HAMMER2_CHAIN_DELETED) {
394 if (ochain && (ochain->flags & HAMMER2_CHAIN_BMAPPED)) {
395 if (ochain->flags & HAMMER2_CHAIN_ONDBTREE) {
396 RB_REMOVE(hammer2_chain_tree,
397 &above->dbtree, ochain);
398 atomic_clear_int(&ochain->flags,
399 HAMMER2_CHAIN_ONDBTREE);
400 TAILQ_INSERT_TAIL(&above->dbq,
402 atomic_set_int(&ochain->flags,
403 HAMMER2_CHAIN_ONDBQ);
405 /* clear BMAPPED (DBTREE, sometimes RBTREE) */
406 atomic_clear_int(&ochain->flags, HAMMER2_CHAIN_BMAPPED);
408 xchain = RB_INSERT(hammer2_chain_tree,
409 &above->dbtree, nchain);
410 KKASSERT(xchain == NULL);
411 atomic_set_int(&nchain->flags,
412 HAMMER2_CHAIN_ONDBTREE |
413 HAMMER2_CHAIN_BMAPPED);
415 TAILQ_INSERT_TAIL(&above->dbq, nchain, db_entry);
416 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONDBQ);
419 xchain = RB_INSERT(hammer2_chain_tree, &above->rbtree, nchain);
420 KASSERT(xchain == NULL,
421 ("hammer2_chain_insert: collision %p", nchain));
422 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
425 nchain->above = above;
426 ++above->chain_count;
430 * We have to keep track of the effective live-view blockref count
431 * so the create code knows when to push an indirect block.
433 if (flags & HAMMER2_CHAIN_INSERT_LIVE)
434 atomic_add_int(&above->live_count, 1);
436 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
437 spin_unlock(&above->cst.spin);
442 * Drop the caller's reference to the chain. When the ref count drops to
443 * zero this function will try to disassociate the chain from its parent and
444 * deallocate it, then recursely drop the parent using the implied ref
445 * from the chain's chain->parent.
447 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
448 struct h2_core_list *delayq);
451 hammer2_chain_drop(hammer2_chain_t *chain)
453 struct h2_core_list delayq;
454 hammer2_chain_t *scan;
458 if (hammer2_debug & 0x200000)
461 if (chain->flags & HAMMER2_CHAIN_FLUSH_CREATE)
463 if (chain->flags & HAMMER2_CHAIN_FLUSH_DELETE)
465 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
467 KKASSERT(chain->refs > need);
477 chain = hammer2_chain_lastdrop(chain, &delayq);
479 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
481 /* retry the same chain */
485 * When we've exhausted lastdrop chaining pull off of delayq.
486 * chains on delayq are dead but are used to placehold other
487 * chains which we added a ref to for the purpose of dropping.
490 hammer2_mount_t *hmp;
492 if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
493 chain = (void *)scan->data;
494 TAILQ_REMOVE(&delayq, scan, core_entry);
495 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
498 kfree(scan, hmp->mchain);
505 * Safe handling of the 1->0 transition on chain. Returns a chain for
506 * recursive drop or NULL, possibly returning the same chain if the atomic
509 * Whem two chains need to be recursively dropped we use the chain
510 * we would otherwise free to placehold the additional chain. It's a bit
511 * convoluted but we can't just recurse without potentially blowing out
514 * The chain cannot be freed if it has a non-empty core (children) or
515 * it is not at the head of ownerq.
517 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
521 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
523 hammer2_pfsmount_t *pmp;
524 hammer2_mount_t *hmp;
525 hammer2_chain_core_t *above;
526 hammer2_chain_core_t *core;
527 hammer2_chain_t *rdrop1;
528 hammer2_chain_t *rdrop2;
531 * Spinlock the core and check to see if it is empty. If it is
532 * not empty we leave chain intact with refs == 0. The elements
533 * in core->rbtree are associated with other chains contemporary
534 * with ours but not with our chain directly.
536 if ((core = chain->core) != NULL) {
537 spin_lock(&core->cst.spin);
540 * We can't free non-stale chains with children until we are
541 * able to free the children because there might be a flush
542 * dependency. Flushes of stale children (which should also
543 * have their deleted flag set) short-cut recursive flush
544 * dependencies and can be freed here. Any flushes which run
545 * through stale children due to the flush synchronization
546 * point should have a FLUSH_* bit set in the chain and not
547 * reach lastdrop at this time.
549 * NOTE: We return (chain) on failure to retry.
551 if (core->chain_count &&
552 (chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
553 if (atomic_cmpset_int(&chain->refs, 1, 0))
554 chain = NULL; /* success */
555 spin_unlock(&core->cst.spin);
558 /* no chains left under us */
561 * Various parts of the code might be holding a ref on a
562 * stale chain as a placemarker which must be iterated to
563 * locate a later non-stale (live) chain. We must be sure
564 * NOT to free the later non-stale chain (which might have
565 * no refs). Otherwise mass confusion may result.
567 * The DUPLICATED flag tells us whether the chain is stale
568 * or not, so the rule is that any chain whos DUPLICATED flag
569 * is NOT set must also be at the head of the ownerq.
571 * Note that the DELETED flag is not involved. That is, a
572 * live chain can represent a deletion that has not yet been
573 * flushed (or still has refs).
576 if (TAILQ_NEXT(chain, core_entry) == NULL &&
577 TAILQ_FIRST(&core->ownerq) != chain) {
579 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 &&
580 TAILQ_FIRST(&core->ownerq) != chain) {
581 if (atomic_cmpset_int(&chain->refs, 1, 0))
582 chain = NULL; /* success */
583 spin_unlock(&core->cst.spin);
589 * chain->core has no children left so no accessors can get to our
590 * chain from there. Now we have to lock the above core to interlock
591 * remaining possible accessors that might bump chain's refs before
592 * we can safely drop chain's refs with intent to free the chain.
595 pmp = chain->pmp; /* can be NULL */
600 * Spinlock the parent and try to drop the last ref on chain.
601 * On success remove chain from its parent, otherwise return NULL.
603 * (normal core locks are top-down recursive but we define core
604 * spinlocks as bottom-up recursive, so this is safe).
606 if ((above = chain->above) != NULL) {
607 spin_lock(&above->cst.spin);
608 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
609 /* 1->0 transition failed */
610 spin_unlock(&above->cst.spin);
612 spin_unlock(&core->cst.spin);
613 return(chain); /* retry */
617 * 1->0 transition successful, remove chain from its
620 switch (chain->flags & (HAMMER2_CHAIN_ONRBTREE |
621 HAMMER2_CHAIN_ONDBTREE |
622 HAMMER2_CHAIN_ONDBQ)) {
623 case HAMMER2_CHAIN_ONRBTREE:
624 RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
625 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
627 case HAMMER2_CHAIN_ONDBTREE:
628 RB_REMOVE(hammer2_chain_tree, &above->dbtree, chain);
629 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
631 case HAMMER2_CHAIN_ONDBQ:
632 TAILQ_REMOVE(&above->dbq, chain, db_entry);
633 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
636 panic("hammer2_chain_lastdrop: chain %p badflags %08x",
637 chain, chain->flags);
641 --above->chain_count;
645 * If our chain was the last chain in the parent's core the
646 * core is now empty and its parents might now be droppable.
647 * Try to drop the first multi-homed parent by gaining a
648 * ref on it here and then dropping it below.
650 if (above->chain_count == 0) {
651 rdrop1 = TAILQ_FIRST(&above->ownerq);
653 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
657 spin_unlock(&above->cst.spin);
658 above = NULL; /* safety */
662 * Successful 1->0 transition and the chain can be destroyed now.
664 * We still have the core spinlock (if core is non-NULL), and core's
665 * chain_count is 0. The above spinlock is gone.
667 * Remove chain from ownerq. Once core has no more owners (and no
668 * children which is already the case) we can destroy core.
670 * If core has more owners we may be able to continue a bottom-up
671 * drop with our next sibling.
676 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
677 rdrop2 = TAILQ_FIRST(&core->ownerq);
678 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
680 spin_unlock(&core->cst.spin);
683 * We can do the final 1->0 transition with an atomic op
684 * after releasing core's spinlock.
686 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
688 * On the 1->0 transition of core we can destroy
691 KKASSERT(TAILQ_EMPTY(&core->ownerq));
692 KKASSERT(RB_EMPTY(&core->rbtree) &&
693 RB_EMPTY(&core->dbtree) &&
694 TAILQ_EMPTY(&core->dbq) &&
695 core->chain_count == 0);
696 KKASSERT(core->cst.count == 0);
697 KKASSERT(core->cst.upgrade == 0);
699 kfree(core, hmp->mchain);
701 core = NULL; /* safety */
705 * All spin locks are gone, finish freeing stuff.
707 KKASSERT((chain->flags & (HAMMER2_CHAIN_FLUSH_CREATE |
708 HAMMER2_CHAIN_FLUSH_DELETE |
709 HAMMER2_CHAIN_MODIFIED)) == 0);
710 hammer2_chain_drop_data(chain, 1);
712 KKASSERT(chain->dio == NULL);
715 * Once chain resources are gone we can use the now dead chain
716 * structure to placehold what might otherwise require a recursive
717 * drop, because we have potentially two things to drop and can only
718 * return one directly.
720 if (rdrop1 && rdrop2) {
721 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
722 chain->data = (void *)rdrop1;
723 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
725 } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
726 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
728 kfree(chain, hmp->mchain);
732 * Either or both can be NULL. We already handled the case where
733 * both might not have been NULL.
742 * On either last lock release or last drop
745 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
747 /*hammer2_mount_t *hmp = chain->hmp;*/
749 switch(chain->bref.type) {
750 case HAMMER2_BREF_TYPE_VOLUME:
751 case HAMMER2_BREF_TYPE_FREEMAP:
756 KKASSERT(chain->data == NULL);
762 * Ref and lock a chain element, acquiring its data with I/O if necessary,
763 * and specify how you would like the data to be resolved.
765 * Returns 0 on success or an error code if the data could not be acquired.
766 * The chain element is locked on return regardless of whether an error
769 * The lock is allowed to recurse, multiple locking ops will aggregate
770 * the requested resolve types. Once data is assigned it will not be
771 * removed until the last unlock.
773 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
774 * (typically used to avoid device/logical buffer
777 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
778 * the INITIAL-create state (indirect blocks only).
780 * Do not resolve data elements for DATA chains.
781 * (typically used to avoid device/logical buffer
784 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
786 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
787 * it will be locked exclusive.
789 * NOTE: Embedded elements (volume header, inodes) are always resolved
792 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
793 * element will instantiate and zero its buffer, and flush it on
796 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
797 * so as not to instantiate a device buffer, which could alias against
798 * a logical file buffer. However, if ALWAYS is specified the
799 * device buffer will be instantiated anyway.
801 * WARNING! If data must be fetched a shared lock will temporarily be
802 * upgraded to exclusive. However, a deadlock can occur if
803 * the caller owns more than one shared lock.
806 hammer2_chain_lock(hammer2_chain_t *chain, int how)
808 hammer2_mount_t *hmp;
809 hammer2_chain_core_t *core;
810 hammer2_blockref_t *bref;
816 * Ref and lock the element. Recursive locks are allowed.
818 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
819 hammer2_chain_ref(chain);
820 atomic_add_int(&chain->lockcnt, 1);
823 KKASSERT(hmp != NULL);
826 * Get the appropriate lock.
829 if (how & HAMMER2_RESOLVE_SHARED)
830 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
832 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
835 * If we already have a valid data pointer no further action is
842 * Do we have to resolve the data?
844 switch(how & HAMMER2_RESOLVE_MASK) {
845 case HAMMER2_RESOLVE_NEVER:
847 case HAMMER2_RESOLVE_MAYBE:
848 if (chain->flags & HAMMER2_CHAIN_INITIAL)
850 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
853 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
856 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
859 case HAMMER2_RESOLVE_ALWAYS:
864 * Upgrade to an exclusive lock so we can safely manipulate the
865 * buffer cache. If another thread got to it before us we
868 ostate = ccms_thread_lock_upgrade(&core->cst);
870 ccms_thread_lock_downgrade(&core->cst, ostate);
875 * We must resolve to a device buffer, either by issuing I/O or
876 * by creating a zero-fill element. We do not mark the buffer
877 * dirty when creating a zero-fill element (the hammer2_chain_modify()
878 * API must still be used to do that).
880 * The device buffer is variable-sized in powers of 2 down
881 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
882 * chunk always contains buffers of the same size. (XXX)
884 * The minimum physical IO size may be larger than the variable
890 * The getblk() optimization can only be used on newly created
891 * elements if the physical block size matches the request.
893 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
894 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
897 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
899 adjreadcounter(&chain->bref, chain->bytes);
903 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
904 (intmax_t)bref->data_off, error);
905 hammer2_io_bqrelse(&chain->dio);
906 ccms_thread_lock_downgrade(&core->cst, ostate);
912 * No need for this, always require that hammer2_chain_modify()
913 * be called before any modifying operations.
915 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
916 !hammer2_io_isdirty(chain->dio)) {
917 hammer2_io_setdirty(chain->dio);
922 * We can clear the INITIAL state now, we've resolved the buffer
923 * to zeros and marked it dirty with hammer2_io_new().
925 bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
926 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
927 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
931 * Setup the data pointer, either pointing it to an embedded data
932 * structure and copying the data from the buffer, or pointing it
935 * The buffer is not retained when copying to an embedded data
936 * structure in order to avoid potential deadlocks or recursions
937 * on the same physical buffer.
939 switch (bref->type) {
940 case HAMMER2_BREF_TYPE_VOLUME:
941 case HAMMER2_BREF_TYPE_FREEMAP:
943 * Copy data from bp to embedded buffer
945 panic("hammer2_chain_lock: called on unresolved volume header");
947 case HAMMER2_BREF_TYPE_INODE:
948 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
949 case HAMMER2_BREF_TYPE_INDIRECT:
950 case HAMMER2_BREF_TYPE_DATA:
951 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
954 * Point data at the device buffer and leave dio intact.
956 chain->data = (void *)bdata;
959 ccms_thread_lock_downgrade(&core->cst, ostate);
964 * This basically calls hammer2_io_breadcb() but does some pre-processing
965 * of the chain first to handle certain cases.
968 hammer2_chain_load_async(hammer2_chain_t *chain,
969 void (*callback)(hammer2_io_t *dio,
970 hammer2_chain_t *chain,
971 void *arg_p, off_t arg_o),
972 void *arg_p, off_t arg_o)
974 hammer2_mount_t *hmp;
975 struct hammer2_io *dio;
976 hammer2_blockref_t *bref;
980 callback(NULL, chain, arg_p, arg_o);
985 * We must resolve to a device buffer, either by issuing I/O or
986 * by creating a zero-fill element. We do not mark the buffer
987 * dirty when creating a zero-fill element (the hammer2_chain_modify()
988 * API must still be used to do that).
990 * The device buffer is variable-sized in powers of 2 down
991 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
992 * chunk always contains buffers of the same size. (XXX)
994 * The minimum physical IO size may be larger than the variable
1001 * The getblk() optimization can only be used on newly created
1002 * elements if the physical block size matches the request.
1004 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1005 chain->bytes == hammer2_devblksize(chain->bytes)) {
1006 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
1007 KKASSERT(error == 0);
1008 callback(dio, chain, arg_p, arg_o);
1013 * Otherwise issue a read
1015 adjreadcounter(&chain->bref, chain->bytes);
1016 hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
1017 callback, chain, arg_p, arg_o);
1021 * Unlock and deref a chain element.
1023 * On the last lock release any non-embedded data (chain->dio) will be
1027 hammer2_chain_unlock(hammer2_chain_t *chain)
1029 hammer2_chain_core_t *core = chain->core;
1030 ccms_state_t ostate;
1035 * The core->cst lock can be shared across several chains so we
1036 * need to track the per-chain lockcnt separately.
1038 * If multiple locks are present (or being attempted) on this
1039 * particular chain we can just unlock, drop refs, and return.
1041 * Otherwise fall-through on the 1->0 transition.
1044 lockcnt = chain->lockcnt;
1045 KKASSERT(lockcnt > 0);
1048 if (atomic_cmpset_int(&chain->lockcnt,
1049 lockcnt, lockcnt - 1)) {
1050 ccms_thread_unlock(&core->cst);
1051 hammer2_chain_drop(chain);
1055 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1062 * On the 1->0 transition we upgrade the core lock (if necessary)
1063 * to exclusive for terminal processing. If after upgrading we find
1064 * that lockcnt is non-zero, another thread is racing us and will
1065 * handle the unload for us later on, so just cleanup and return
1066 * leaving the data/io intact
1068 * Otherwise if lockcnt is still 0 it is possible for it to become
1069 * non-zero and race, but since we hold the core->cst lock
1070 * exclusively all that will happen is that the chain will be
1071 * reloaded after we unload it.
1073 ostate = ccms_thread_lock_upgrade(&core->cst);
1074 if (chain->lockcnt) {
1075 ccms_thread_unlock_upgraded(&core->cst, ostate);
1076 hammer2_chain_drop(chain);
1081 * Shortcut the case if the data is embedded or not resolved.
1083 * Do NOT NULL out chain->data (e.g. inode data), it might be
1086 if (chain->dio == NULL) {
1087 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1088 hammer2_chain_drop_data(chain, 0);
1089 ccms_thread_unlock_upgraded(&core->cst, ostate);
1090 hammer2_chain_drop(chain);
1097 if (hammer2_io_isdirty(chain->dio) == 0) {
1099 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1100 switch(chain->bref.type) {
1101 case HAMMER2_BREF_TYPE_DATA:
1102 counterp = &hammer2_ioa_file_write;
1104 case HAMMER2_BREF_TYPE_INODE:
1105 counterp = &hammer2_ioa_meta_write;
1107 case HAMMER2_BREF_TYPE_INDIRECT:
1108 counterp = &hammer2_ioa_indr_write;
1110 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1111 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1112 counterp = &hammer2_ioa_fmap_write;
1115 counterp = &hammer2_ioa_volu_write;
1118 *counterp += chain->bytes;
1120 switch(chain->bref.type) {
1121 case HAMMER2_BREF_TYPE_DATA:
1122 counterp = &hammer2_iod_file_write;
1124 case HAMMER2_BREF_TYPE_INODE:
1125 counterp = &hammer2_iod_meta_write;
1127 case HAMMER2_BREF_TYPE_INDIRECT:
1128 counterp = &hammer2_iod_indr_write;
1130 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1131 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1132 counterp = &hammer2_iod_fmap_write;
1135 counterp = &hammer2_iod_volu_write;
1138 *counterp += chain->bytes;
1142 * Clean out the dio.
1144 * If a device buffer was used for data be sure to destroy the
1145 * buffer when we are done to avoid aliases (XXX what about the
1146 * underlying VM pages?).
1148 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1151 * NOTE: The isdirty check tracks whether we have to bdwrite() the
1152 * buffer or not. The buffer might already be dirty. The
1153 * flag is re-set when chain_modify() is called, even if
1154 * MODIFIED is already set, allowing the OS to retire the
1155 * buffer independent of a hammer2 flush.
1158 if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
1159 hammer2_io_isdirty(chain->dio)) {
1160 hammer2_io_bawrite(&chain->dio);
1162 hammer2_io_bqrelse(&chain->dio);
1164 ccms_thread_unlock_upgraded(&core->cst, ostate);
1165 hammer2_chain_drop(chain);
1169 * This counts the number of live blockrefs in a block array and
1170 * also calculates the point at which all remaining blockrefs are empty.
1171 * This routine can only be called on a live chain (DUPLICATED flag not set).
1173 * NOTE: Flag is not set until after the count is complete, allowing
1174 * callers to test the flag without holding the spinlock.
1176 * NOTE: If base is NULL the related chain is still in the INITIAL
1177 * state and there are no blockrefs to count.
1179 * NOTE: live_count may already have some counts accumulated due to
1180 * creation and deletion and could even be initially negative.
1183 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1184 hammer2_blockref_t *base, int count)
1186 hammer2_chain_core_t *core = chain->core;
1188 KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
1190 spin_lock(&core->cst.spin);
1191 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1193 while (--count >= 0) {
1194 if (base[count].type)
1197 core->live_zero = count + 1;
1198 while (count >= 0) {
1199 if (base[count].type)
1200 atomic_add_int(&core->live_count, 1);
1204 core->live_zero = 0;
1206 /* else do not modify live_count */
1207 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1209 spin_unlock(&core->cst.spin);
1213 * Resize the chain's physical storage allocation in-place. This may
1214 * replace the passed-in chain with a new chain.
1216 * Chains can be resized smaller without reallocating the storage.
1217 * Resizing larger will reallocate the storage.
1219 * Must be passed an exclusively locked parent and chain, returns a new
1220 * exclusively locked chain at the same index and unlocks the old chain.
1221 * Flushes the buffer if necessary.
1223 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1224 * to avoid instantiating a device buffer that conflicts with the vnode
1225 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1226 * any chain-oriented bp would be a device buffer.
1228 * XXX return error if cannot resize.
1231 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1232 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1233 int nradix, int flags)
1235 hammer2_mount_t *hmp;
1236 hammer2_chain_t *chain;
1244 * Only data and indirect blocks can be resized for now.
1245 * (The volu root, inodes, and freemap elements use a fixed size).
1247 KKASSERT(chain != &hmp->vchain);
1248 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1249 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1252 * Nothing to do if the element is already the proper size
1254 obytes = chain->bytes;
1255 nbytes = 1U << nradix;
1256 if (obytes == nbytes)
1260 * Delete the old chain and duplicate it at the same (parent, index),
1261 * returning a new chain. This allows the old chain to still be
1262 * used by the flush code. The new chain will be returned in a
1265 * The parent does not have to be locked for the delete/duplicate call,
1266 * but is in this particular code path.
1268 * NOTE: If we are not crossing a synchronization point the
1269 * duplication code will simply reuse the existing chain
1272 hammer2_chain_delete_duplicate(trans, &chain, 0);
1275 * Relocate the block, even if making it smaller (because different
1276 * block sizes may be in different regions).
1278 * (data blocks only, we aren't copying the storage here).
1280 hammer2_freemap_alloc(trans, chain, nbytes);
1281 chain->bytes = nbytes;
1282 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1283 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1286 * For now just support it on DATA chains (and not on indirect
1289 KKASSERT(chain->dio == NULL);
1295 * Set a chain modified, making it read-write and duplicating it if necessary.
1296 * This function will assign a new physical block to the chain if necessary
1298 * Duplication of already-modified chains is possible when the modification
1299 * crosses a flush synchronization boundary.
1301 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1302 * level or the COW operation will not work.
1304 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1305 * run the data through the device buffers.
1307 * This function may return a different chain than was passed, in which case
1308 * the old chain will be unlocked and the new chain will be locked.
1310 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1312 hammer2_inode_data_t *
1313 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1314 hammer2_chain_t **chainp, int flags)
1316 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1317 hammer2_chain_modify(trans, chainp, flags);
1318 if (ip->chain != *chainp)
1319 hammer2_inode_repoint(ip, NULL, *chainp);
1321 vsetisdirty(ip->vp);
1322 return(&ip->chain->data->ipdata);
1326 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1329 hammer2_mount_t *hmp;
1330 hammer2_chain_t *chain;
1339 KKASSERT(chain->bref.mirror_tid != trans->sync_tid ||
1340 (chain->flags & HAMMER2_CHAIN_MODIFIED));
1343 * data is not optional for freemap chains (we must always be sure
1344 * to copy the data on COW storage allocations).
1346 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1347 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1348 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1349 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1353 * Determine if a delete-duplicate is needed.
1355 * (a) Modify_tid is part of a prior flush
1356 * (b) Transaction is concurrent with a flush (has higher tid)
1357 * (c) and chain is not in the initial state (freshly created)
1358 * (d) and caller didn't request an in-place modification.
1360 * The freemap and volume header special chains are never D-Dd.
1362 if (chain->modify_tid != trans->sync_tid && /* cross boundary */
1363 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1364 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1365 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1366 hammer2_chain_delete_duplicate(trans, chainp, 0);
1372 * Data must be resolved if already assigned unless explicitly
1373 * flagged otherwise.
1375 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1376 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1377 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1378 hammer2_chain_unlock(chain);
1382 * Otherwise do initial-chain handling. Set MODIFIED to indicate
1383 * that the chain has been modified. Set FLUSH_CREATE to flush
1384 * the new blockref (the D-D set FLUSH_DELETE on the old chain to
1385 * delete the old blockref).
1387 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1388 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1389 hammer2_chain_ref(chain);
1390 hammer2_chain_memory_inc(chain->pmp);
1392 if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
1393 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
1394 hammer2_chain_ref(chain);
1398 * The modification or re-modification requires an allocation and
1401 * We normally always allocate new storage here. If storage exists
1402 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1404 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1405 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1406 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1407 chain->modify_tid != trans->sync_tid)
1409 hammer2_freemap_alloc(trans, chain, chain->bytes);
1410 /* XXX failed allocation */
1411 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1412 hammer2_freemap_alloc(trans, chain, chain->bytes);
1413 /* XXX failed allocation */
1415 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1419 * Update modify_tid. XXX special-case vchain/fchain because they
1420 * are always modified in-place. Otherwise the chain being modified
1421 * must not be part of a future transaction.
1423 if (chain == &hmp->vchain || chain == &hmp->fchain) {
1424 if (chain->modify_tid <= trans->sync_tid)
1425 chain->modify_tid = trans->sync_tid;
1427 KKASSERT(chain->modify_tid <= trans->sync_tid);
1428 chain->modify_tid = trans->sync_tid;
1431 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1432 chain->bref.modify_tid = trans->sync_tid;
1435 * Do not COW BREF_TYPE_DATA when OPTDATA is set. This is because
1436 * data modifications are done via the logical buffer cache so COWing
1437 * it here would result in unnecessary extra copies (and possibly extra
1438 * block reallocations). The INITIAL flag remains unchanged in this
1441 * (This is a bit of a hack).
1443 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1444 (flags & HAMMER2_MODIFY_OPTDATA)) {
1449 * Clearing the INITIAL flag (for indirect blocks) indicates that
1450 * we've processed the uninitialized storage allocation.
1452 * If this flag is already clear we are likely in a copy-on-write
1453 * situation but we have to be sure NOT to bzero the storage if
1454 * no data is present.
1456 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1457 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1464 * Instantiate data buffer and possibly execute COW operation
1466 switch(chain->bref.type) {
1467 case HAMMER2_BREF_TYPE_VOLUME:
1468 case HAMMER2_BREF_TYPE_FREEMAP:
1470 * The data is embedded, no copy-on-write operation is
1473 KKASSERT(chain->dio == NULL);
1475 case HAMMER2_BREF_TYPE_INODE:
1476 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1477 case HAMMER2_BREF_TYPE_DATA:
1478 case HAMMER2_BREF_TYPE_INDIRECT:
1479 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1481 * Perform the copy-on-write operation
1483 * zero-fill or copy-on-write depending on whether
1484 * chain->data exists or not and set the dirty state for
1485 * the new buffer. hammer2_io_new() will handle the
1488 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1491 error = hammer2_io_new(hmp, chain->bref.data_off,
1492 chain->bytes, &dio);
1494 error = hammer2_io_bread(hmp, chain->bref.data_off,
1495 chain->bytes, &dio);
1497 adjreadcounter(&chain->bref, chain->bytes);
1498 KKASSERT(error == 0);
1500 bdata = hammer2_io_data(dio, chain->bref.data_off);
1503 KKASSERT(chain->dio != NULL);
1504 if (chain->data != (void *)bdata) {
1505 bcopy(chain->data, bdata, chain->bytes);
1507 } else if (wasinitial == 0) {
1509 * We have a problem. We were asked to COW but
1510 * we don't have any data to COW with!
1512 panic("hammer2_chain_modify: having a COW %p\n",
1517 * Retire the old buffer, replace with the new
1520 hammer2_io_brelse(&chain->dio);
1521 chain->data = (void *)bdata;
1523 hammer2_io_setdirty(dio); /* modified by bcopy above */
1526 panic("hammer2_chain_modify: illegal non-embedded type %d",
1532 hammer2_chain_setsubmod(trans, chain);
1536 * Mark the volume as having been modified. This short-cut version
1537 * does not have to lock the volume's chain, which allows the ioctl
1538 * code to make adjustments to connections without deadlocking. XXX
1540 * No ref is made on vchain when flagging it MODIFIED.
1543 hammer2_modify_volume(hammer2_mount_t *hmp)
1545 hammer2_voldata_lock(hmp);
1546 hammer2_voldata_unlock(hmp, 1);
1550 * This function returns the chain at the nearest key within the specified
1551 * range with the highest delete_tid. The core spinlock must be held on
1552 * call and the returned chain will be referenced but not locked.
1554 * The returned chain may or may not be in a deleted state. Note that
1555 * live chains have a delete_tid = MAX_TID.
1557 * This function will recurse through chain->rbtree as necessary and will
1558 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1559 * the iteration value is less than the current value of *key_nextp.
1561 * The caller should use (*key_nextp) to calculate the actual range of
1562 * the returned element, which will be (key_beg to *key_nextp - 1), because
1563 * there might be another element which is superior to the returned element
1566 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1567 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1568 * it will wind up being (key_end + 1).
1570 struct hammer2_chain_find_info {
1571 hammer2_chain_t *best;
1572 hammer2_key_t key_beg;
1573 hammer2_key_t key_end;
1574 hammer2_key_t key_next;
1577 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1578 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1582 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1583 hammer2_key_t key_beg, hammer2_key_t key_end)
1585 struct hammer2_chain_find_info info;
1588 info.key_beg = key_beg;
1589 info.key_end = key_end;
1590 info.key_next = *key_nextp;
1592 KKASSERT(parent->core->good == 0x1234);
1593 RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1594 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1596 *key_nextp = info.key_next;
1598 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1599 parent, key_beg, key_end, *key_nextp);
1606 * Find a deleted chain covering a block table entry. Be careful to deal
1607 * with the race condition where the block table has been updated but the
1608 * chain has not yet been removed from dbtree (due to multiple parents having
1613 hammer2_chain_find_deleted(hammer2_chain_t *parent,
1614 hammer2_key_t key_beg, hammer2_key_t key_end)
1616 struct hammer2_chain_find_info info;
1617 hammer2_chain_t *child;
1620 info.key_beg = key_beg;
1621 info.key_end = key_end;
1624 KKASSERT(parent->core->good == 0x1234);
1625 RB_SCAN(hammer2_chain_tree, &parent->core->dbtree,
1626 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1628 if ((child = info.best) != NULL) {
1629 if (child->delete_tid <= parent->update_lo)
1637 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1639 struct hammer2_chain_find_info *info = data;
1640 hammer2_key_t child_beg;
1641 hammer2_key_t child_end;
1643 child_beg = child->bref.key;
1644 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1646 if (child_end < info->key_beg)
1648 if (child_beg > info->key_end)
1655 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1657 struct hammer2_chain_find_info *info = data;
1658 hammer2_chain_t *best;
1659 hammer2_key_t child_end;
1662 * WARNING! Do not discard DUPLICATED chains, it is possible that
1663 * we are catching an insertion half-way done. If a
1664 * duplicated chain turns out to be the best choice the
1665 * caller will re-check its flags after locking it.
1667 * WARNING! Layerq is scanned forwards, exact matches should keep
1668 * the existing info->best.
1670 if ((best = info->best) == NULL) {
1672 * No previous best. Assign best
1675 } else if (best->bref.key <= info->key_beg &&
1676 child->bref.key <= info->key_beg) {
1678 * If our current best is flush with key_beg and child is
1679 * also flush with key_beg choose based on delete_tid.
1681 * key_next will automatically be limited to the smaller of
1682 * the two end-points.
1684 if (child->delete_tid > best->delete_tid)
1686 } else if (child->bref.key < best->bref.key) {
1688 * Child has a nearer key and best is not flush with key_beg.
1689 * Truncate key_next to the old best key iff it had a better
1693 if (best->delete_tid >= child->delete_tid &&
1694 (info->key_next > best->bref.key || info->key_next == 0))
1695 info->key_next = best->bref.key;
1696 } else if (child->bref.key == best->bref.key) {
1698 * If our current best is flush with the child then choose
1699 * based on delete_tid.
1701 * key_next will automatically be limited to the smaller of
1702 * the two end-points.
1704 if (child->delete_tid > best->delete_tid)
1708 * Keep the current best but truncate key_next to the child's
1709 * base iff the child has a higher delete_tid.
1711 * key_next will also automatically be limited to the smaller
1712 * of the two end-points (probably not necessary for this case
1713 * but we do it anyway).
1715 if (child->delete_tid >= best->delete_tid &&
1716 (info->key_next > child->bref.key || info->key_next == 0))
1717 info->key_next = child->bref.key;
1721 * Always truncate key_next based on child's end-of-range.
1723 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1724 if (child_end && (info->key_next > child_end || info->key_next == 0))
1725 info->key_next = child_end;
1731 * Retrieve the specified chain from a media blockref, creating the
1732 * in-memory chain structure which reflects it. modify_tid will be
1733 * left 0 which forces any modifications to issue a delete-duplicate.
1735 * To handle insertion races pass the INSERT_RACE flag along with the
1736 * generation number of the core. NULL will be returned if the generation
1737 * number changes before we have a chance to insert the chain. Insert
1738 * races can occur because the parent might be held shared.
1740 * Caller must hold the parent locked shared or exclusive since we may
1741 * need the parent's bref array to find our block.
1744 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1745 hammer2_blockref_t *bref)
1747 hammer2_mount_t *hmp = parent->hmp;
1748 hammer2_chain_core_t *above = parent->core;
1749 hammer2_chain_t *chain;
1753 * Allocate a chain structure representing the existing media
1754 * entry. Resulting chain has one ref and is not locked.
1756 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1757 hammer2_chain_core_alloc(NULL, chain, NULL);
1758 /* ref'd chain returned */
1761 * Set modify_tid and update_lo to the chain's synchronization
1762 * point from the media.
1764 chain->modify_tid = chain->bref.mirror_tid;
1765 chain->update_lo = chain->bref.mirror_tid;
1766 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1769 * Link the chain into its parent. A spinlock is required to safely
1770 * access the RBTREE, and it is possible to collide with another
1771 * hammer2_chain_get() operation because the caller might only hold
1772 * a shared lock on the parent.
1774 KKASSERT(parent->refs > 0);
1775 error = hammer2_chain_insert(above, NULL, chain,
1776 HAMMER2_CHAIN_INSERT_SPIN |
1777 HAMMER2_CHAIN_INSERT_RACE,
1780 KKASSERT((chain->flags & (HAMMER2_CHAIN_ONRBTREE |
1781 HAMMER2_CHAIN_ONDBTREE |
1782 HAMMER2_CHAIN_ONDBQ)) == 0);
1783 kprintf("chain %p get race\n", chain);
1784 hammer2_chain_drop(chain);
1787 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1791 * Return our new chain referenced but not locked, or NULL if
1798 * Lookup initialization/completion API
1801 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1803 if (flags & HAMMER2_LOOKUP_SHARED) {
1804 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1805 HAMMER2_RESOLVE_SHARED);
1807 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1813 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1816 hammer2_chain_unlock(parent);
1821 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1823 hammer2_chain_t *oparent;
1824 hammer2_chain_t *bparent;
1825 hammer2_chain_t *nparent;
1826 hammer2_chain_core_t *above;
1829 above = oparent->above;
1831 spin_lock(&above->cst.spin);
1832 bparent = TAILQ_FIRST(&above->ownerq);
1833 hammer2_chain_ref(bparent);
1836 * Be careful of order, oparent must be unlocked before nparent
1837 * is locked below to avoid a deadlock. We might as well delay its
1838 * unlocking until we conveniently no longer have the spinlock (instead
1839 * of cycling the spinlock).
1841 * Theoretically our ref on bparent should prevent elements of the
1842 * following chain from going away and prevent above from going away,
1843 * but we still need the spinlock to safely scan the list.
1847 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1848 nparent = TAILQ_NEXT(nparent, core_entry);
1849 hammer2_chain_ref(nparent);
1850 spin_unlock(&above->cst.spin);
1853 hammer2_chain_unlock(oparent);
1856 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1857 hammer2_chain_drop(bparent);
1860 * We might have raced a delete-duplicate.
1862 if ((nparent->flags & HAMMER2_CHAIN_DUPLICATED) == 0)
1865 hammer2_chain_ref(bparent);
1866 hammer2_chain_unlock(nparent);
1867 spin_lock(&above->cst.spin);
1876 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1877 * (*parentp) typically points to an inode but can also point to a related
1878 * indirect block and this function will recurse upwards and find the inode
1881 * (*parentp) must be exclusively locked and referenced and can be an inode
1882 * or an existing indirect block within the inode.
1884 * On return (*parentp) will be modified to point at the deepest parent chain
1885 * element encountered during the search, as a helper for an insertion or
1886 * deletion. The new (*parentp) will be locked and referenced and the old
1887 * will be unlocked and dereferenced (no change if they are both the same).
1889 * The matching chain will be returned exclusively locked. If NOLOCK is
1890 * requested the chain will be returned only referenced.
1892 * NULL is returned if no match was found, but (*parentp) will still
1893 * potentially be adjusted.
1895 * On return (*key_nextp) will point to an iterative value for key_beg.
1896 * (If NULL is returned (*key_nextp) is set to key_end).
1898 * This function will also recurse up the chain if the key is not within the
1899 * current parent's range. (*parentp) can never be set to NULL. An iteration
1900 * can simply allow (*parentp) to float inside the loop.
1902 * NOTE! chain->data is not always resolved. By default it will not be
1903 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1904 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1905 * BREF_TYPE_DATA as the device buffer can alias the logical file
1909 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1910 hammer2_key_t key_beg, hammer2_key_t key_end,
1911 int *cache_indexp, int flags)
1913 hammer2_mount_t *hmp;
1914 hammer2_chain_t *parent;
1915 hammer2_chain_t *chain;
1916 hammer2_blockref_t *base;
1917 hammer2_blockref_t *bref;
1918 hammer2_blockref_t bcopy;
1919 hammer2_key_t scan_beg;
1920 hammer2_key_t scan_end;
1921 hammer2_chain_core_t *above;
1923 int how_always = HAMMER2_RESOLVE_ALWAYS;
1924 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1927 int maxloops = 300000;
1930 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1931 how_maybe = how_always;
1932 how = HAMMER2_RESOLVE_ALWAYS;
1933 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1934 how = HAMMER2_RESOLVE_NEVER;
1936 how = HAMMER2_RESOLVE_MAYBE;
1938 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1939 how_maybe |= HAMMER2_RESOLVE_SHARED;
1940 how_always |= HAMMER2_RESOLVE_SHARED;
1941 how |= HAMMER2_RESOLVE_SHARED;
1945 * Recurse (*parentp) upward if necessary until the parent completely
1946 * encloses the key range or we hit the inode.
1948 * This function handles races against the flusher doing a delete-
1949 * duplicate above us and re-homes the parent to the duplicate in
1950 * that case, otherwise we'd wind up recursing down a stale chain.
1955 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1956 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1957 scan_beg = parent->bref.key;
1958 scan_end = scan_beg +
1959 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1960 if (key_beg >= scan_beg && key_end <= scan_end)
1962 parent = hammer2_chain_getparent(parentp, how_maybe);
1966 if (--maxloops == 0)
1967 panic("hammer2_chain_lookup: maxloops");
1969 * Locate the blockref array. Currently we do a fully associative
1970 * search through the array.
1972 switch(parent->bref.type) {
1973 case HAMMER2_BREF_TYPE_INODE:
1975 * Special shortcut for embedded data returns the inode
1976 * itself. Callers must detect this condition and access
1977 * the embedded data (the strategy code does this for us).
1979 * This is only applicable to regular files and softlinks.
1981 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1982 if (flags & HAMMER2_LOOKUP_NOLOCK)
1983 hammer2_chain_ref(parent);
1985 hammer2_chain_lock(parent, how_always);
1986 *key_nextp = key_end + 1;
1989 base = &parent->data->ipdata.u.blockset.blockref[0];
1990 count = HAMMER2_SET_COUNT;
1992 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1993 case HAMMER2_BREF_TYPE_INDIRECT:
1995 * Handle MATCHIND on the parent
1997 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1998 scan_beg = parent->bref.key;
1999 scan_end = scan_beg +
2000 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2001 if (key_beg == scan_beg && key_end == scan_end) {
2003 hammer2_chain_lock(chain, how_maybe);
2004 *key_nextp = scan_end + 1;
2009 * Optimize indirect blocks in the INITIAL state to avoid
2012 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2015 if (parent->data == NULL)
2016 panic("parent->data is NULL");
2017 base = &parent->data->npdata[0];
2019 count = parent->bytes / sizeof(hammer2_blockref_t);
2021 case HAMMER2_BREF_TYPE_VOLUME:
2022 base = &hmp->voldata.sroot_blockset.blockref[0];
2023 count = HAMMER2_SET_COUNT;
2025 case HAMMER2_BREF_TYPE_FREEMAP:
2026 base = &hmp->voldata.freemap_blockset.blockref[0];
2027 count = HAMMER2_SET_COUNT;
2030 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2032 base = NULL; /* safety */
2033 count = 0; /* safety */
2037 * Merged scan to find next candidate.
2039 * hammer2_base_*() functions require the above->live_* fields
2040 * to be synchronized.
2042 * We need to hold the spinlock to access the block array and RB tree
2043 * and to interlock chain creation.
2045 above = parent->core;
2046 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2047 hammer2_chain_countbrefs(parent, base, count);
2052 spin_lock(&above->cst.spin);
2053 chain = hammer2_combined_find(parent, base, count,
2054 cache_indexp, key_nextp,
2057 generation = above->generation;
2060 * Exhausted parent chain, iterate.
2063 spin_unlock(&above->cst.spin);
2064 if (key_beg == key_end) /* short cut single-key case */
2068 * Stop if we reached the end of the iteration.
2070 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2071 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2076 * Calculate next key, stop if we reached the end of the
2077 * iteration, otherwise go up one level and loop.
2079 key_beg = parent->bref.key +
2080 ((hammer2_key_t)1 << parent->bref.keybits);
2081 if (key_beg == 0 || key_beg > key_end)
2083 parent = hammer2_chain_getparent(parentp, how_maybe);
2088 * Selected from blockref or in-memory chain.
2090 if (chain == NULL) {
2092 spin_unlock(&above->cst.spin);
2093 chain = hammer2_chain_get(parent, generation,
2095 if (chain == NULL) {
2096 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2097 parent, key_beg, key_end);
2100 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2101 hammer2_chain_drop(chain);
2106 hammer2_chain_ref(chain);
2107 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2108 spin_unlock(&above->cst.spin);
2112 * chain is referenced but not locked. We must lock the chain
2113 * to obtain definitive DUPLICATED/DELETED state
2115 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2116 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2117 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2119 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2123 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2125 * NOTE: Chain's key range is not relevant as there might be
2126 * one-offs within the range that are not deleted.
2128 * NOTE: Lookups can race delete-duplicate because
2129 * delete-duplicate does not lock the parent's core
2130 * (they just use the spinlock on the core). We must
2131 * check for races by comparing the DUPLICATED flag before
2132 * releasing the spinlock with the flag after locking the
2135 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2136 hammer2_chain_unlock(chain);
2137 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2138 key_beg = *key_nextp;
2139 if (key_beg == 0 || key_beg > key_end)
2146 * If the chain element is an indirect block it becomes the new
2147 * parent and we loop on it. We must maintain our top-down locks
2148 * to prevent the flusher from interfering (i.e. doing a
2149 * delete-duplicate and leaving us recursing down a deleted chain).
2151 * The parent always has to be locked with at least RESOLVE_MAYBE
2152 * so we can access its data. It might need a fixup if the caller
2153 * passed incompatible flags. Be careful not to cause a deadlock
2154 * as a data-load requires an exclusive lock.
2156 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2157 * range is within the requested key range we return the indirect
2158 * block and do NOT loop. This is usually only used to acquire
2161 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2162 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2163 hammer2_chain_unlock(parent);
2164 *parentp = parent = chain;
2169 * All done, return the chain
2175 * After having issued a lookup we can iterate all matching keys.
2177 * If chain is non-NULL we continue the iteration from just after it's index.
2179 * If chain is NULL we assume the parent was exhausted and continue the
2180 * iteration at the next parent.
2182 * parent must be locked on entry and remains locked throughout. chain's
2183 * lock status must match flags. Chain is always at least referenced.
2185 * WARNING! The MATCHIND flag does not apply to this function.
2188 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2189 hammer2_key_t *key_nextp,
2190 hammer2_key_t key_beg, hammer2_key_t key_end,
2191 int *cache_indexp, int flags)
2193 hammer2_chain_t *parent;
2197 * Calculate locking flags for upward recursion.
2199 how_maybe = HAMMER2_RESOLVE_MAYBE;
2200 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2201 how_maybe |= HAMMER2_RESOLVE_SHARED;
2206 * Calculate the next index and recalculate the parent if necessary.
2209 key_beg = chain->bref.key +
2210 ((hammer2_key_t)1 << chain->bref.keybits);
2211 if (flags & HAMMER2_LOOKUP_NOLOCK)
2212 hammer2_chain_drop(chain);
2214 hammer2_chain_unlock(chain);
2217 * Any scan where the lookup returned degenerate data embedded
2218 * in the inode has an invalid index and must terminate.
2220 if (chain == parent)
2222 if (key_beg == 0 || key_beg > key_end)
2225 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2226 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2228 * We reached the end of the iteration.
2233 * Continue iteration with next parent unless the current
2234 * parent covers the range.
2236 key_beg = parent->bref.key +
2237 ((hammer2_key_t)1 << parent->bref.keybits);
2238 if (key_beg == 0 || key_beg > key_end)
2240 parent = hammer2_chain_getparent(parentp, how_maybe);
2246 return (hammer2_chain_lookup(parentp, key_nextp,
2248 cache_indexp, flags));
2252 * The raw scan function is similar to lookup/next but does not seek to a key.
2253 * Blockrefs are iterated via first_chain = (parent, NULL) and
2254 * next_chain = (parent, chain).
2256 * The passed-in parent must be locked and its data resolved. The returned
2257 * chain will be locked. Pass chain == NULL to acquire the first sub-chain
2258 * under parent and then iterate with the passed-in chain (which this
2259 * function will unlock).
2262 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2263 int *cache_indexp, int flags)
2265 hammer2_mount_t *hmp;
2266 hammer2_blockref_t *base;
2267 hammer2_blockref_t *bref;
2268 hammer2_blockref_t bcopy;
2269 hammer2_chain_core_t *above;
2271 hammer2_key_t next_key;
2273 int how_always = HAMMER2_RESOLVE_ALWAYS;
2274 int how_maybe = HAMMER2_RESOLVE_MAYBE;
2277 int maxloops = 300000;
2283 * Scan flags borrowed from lookup
2285 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2286 how_maybe = how_always;
2287 how = HAMMER2_RESOLVE_ALWAYS;
2288 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2289 how = HAMMER2_RESOLVE_NEVER;
2291 how = HAMMER2_RESOLVE_MAYBE;
2293 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2294 how_maybe |= HAMMER2_RESOLVE_SHARED;
2295 how_always |= HAMMER2_RESOLVE_SHARED;
2296 how |= HAMMER2_RESOLVE_SHARED;
2300 * Calculate key to locate first/next element, unlocking the previous
2301 * element as we go. Be careful, the key calculation can overflow.
2304 key = chain->bref.key +
2305 ((hammer2_key_t)1 << chain->bref.keybits);
2306 hammer2_chain_unlock(chain);
2315 if (--maxloops == 0)
2316 panic("hammer2_chain_scan: maxloops");
2318 * Locate the blockref array. Currently we do a fully associative
2319 * search through the array.
2321 switch(parent->bref.type) {
2322 case HAMMER2_BREF_TYPE_INODE:
2324 * An inode with embedded data has no sub-chains.
2326 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2328 base = &parent->data->ipdata.u.blockset.blockref[0];
2329 count = HAMMER2_SET_COUNT;
2331 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2332 case HAMMER2_BREF_TYPE_INDIRECT:
2334 * Optimize indirect blocks in the INITIAL state to avoid
2337 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2340 if (parent->data == NULL)
2341 panic("parent->data is NULL");
2342 base = &parent->data->npdata[0];
2344 count = parent->bytes / sizeof(hammer2_blockref_t);
2346 case HAMMER2_BREF_TYPE_VOLUME:
2347 base = &hmp->voldata.sroot_blockset.blockref[0];
2348 count = HAMMER2_SET_COUNT;
2350 case HAMMER2_BREF_TYPE_FREEMAP:
2351 base = &hmp->voldata.freemap_blockset.blockref[0];
2352 count = HAMMER2_SET_COUNT;
2355 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2357 base = NULL; /* safety */
2358 count = 0; /* safety */
2362 * Merged scan to find next candidate.
2364 * hammer2_base_*() functions require the above->live_* fields
2365 * to be synchronized.
2367 * We need to hold the spinlock to access the block array and RB tree
2368 * and to interlock chain creation.
2370 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2371 hammer2_chain_countbrefs(parent, base, count);
2373 above = parent->core;
2375 spin_lock(&above->cst.spin);
2376 chain = hammer2_combined_find(parent, base, count,
2377 cache_indexp, &next_key,
2378 key, HAMMER2_MAX_KEY,
2380 generation = above->generation;
2383 * Exhausted parent chain, we're done.
2386 spin_unlock(&above->cst.spin);
2387 KKASSERT(chain == NULL);
2392 * Selected from blockref or in-memory chain.
2394 if (chain == NULL) {
2396 spin_unlock(&above->cst.spin);
2397 chain = hammer2_chain_get(parent, generation, &bcopy);
2398 if (chain == NULL) {
2399 kprintf("retry scan parent %p keys %016jx\n",
2403 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2404 hammer2_chain_drop(chain);
2410 hammer2_chain_ref(chain);
2411 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2412 spin_unlock(&above->cst.spin);
2416 * chain is referenced but not locked. We must lock the chain
2417 * to obtain definitive DUPLICATED/DELETED state
2419 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2422 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2424 * NOTE: chain's key range is not relevant as there might be
2425 * one-offs within the range that are not deleted.
2427 * NOTE: XXX this could create problems with scans used in
2428 * situations other than mount-time recovery.
2430 * NOTE: Lookups can race delete-duplicate because
2431 * delete-duplicate does not lock the parent's core
2432 * (they just use the spinlock on the core). We must
2433 * check for races by comparing the DUPLICATED flag before
2434 * releasing the spinlock with the flag after locking the
2437 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2438 hammer2_chain_unlock(chain);
2441 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2451 * All done, return the chain or NULL
2457 * Create and return a new hammer2 system memory structure of the specified
2458 * key, type and size and insert it under (*parentp). This is a full
2459 * insertion, based on the supplied key/keybits, and may involve creating
2460 * indirect blocks and moving other chains around via delete/duplicate.
2462 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2463 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2464 * FULL. This typically means that the caller is creating the chain after
2465 * doing a hammer2_chain_lookup().
2467 * (*parentp) must be exclusive locked and may be replaced on return
2468 * depending on how much work the function had to do.
2470 * (*chainp) usually starts out NULL and returns the newly created chain,
2471 * but if the caller desires the caller may allocate a disconnected chain
2472 * and pass it in instead. (It is also possible for the caller to use
2473 * chain_duplicate() to create a disconnected chain, manipulate it, then
2474 * pass it into this function to insert it).
2476 * This function should NOT be used to insert INDIRECT blocks. It is
2477 * typically used to create/insert inodes and data blocks.
2479 * Caller must pass-in an exclusively locked parent the new chain is to
2480 * be inserted under, and optionally pass-in a disconnected, exclusively
2481 * locked chain to insert (else we create a new chain). The function will
2482 * adjust (*parentp) as necessary, create or connect the chain, and
2483 * return an exclusively locked chain in *chainp.
2486 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2487 hammer2_chain_t **chainp,
2488 hammer2_key_t key, int keybits, int type, size_t bytes)
2490 hammer2_mount_t *hmp;
2491 hammer2_chain_t *chain;
2492 hammer2_chain_t *parent = *parentp;
2493 hammer2_chain_core_t *above;
2494 hammer2_blockref_t *base;
2495 hammer2_blockref_t dummy;
2499 int maxloops = 300000;
2501 above = parent->core;
2502 KKASSERT(ccms_thread_lock_owned(&above->cst));
2506 if (chain == NULL) {
2508 * First allocate media space and construct the dummy bref,
2509 * then allocate the in-memory chain structure. Set the
2510 * INITIAL flag for fresh chains which do not have embedded
2513 bzero(&dummy, sizeof(dummy));
2516 dummy.keybits = keybits;
2517 dummy.data_off = hammer2_getradix(bytes);
2518 dummy.methods = parent->bref.methods;
2519 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2520 hammer2_chain_core_alloc(trans, chain, NULL);
2523 * Lock the chain manually, chain_lock will load the chain
2524 * which we do NOT want to do. (note: chain->refs is set
2525 * to 1 by chain_alloc() for us, but lockcnt is not).
2528 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2532 * We do NOT set INITIAL here (yet). INITIAL is only
2533 * used for indirect blocks.
2535 * Recalculate bytes to reflect the actual media block
2538 bytes = (hammer2_off_t)1 <<
2539 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2540 chain->bytes = bytes;
2543 case HAMMER2_BREF_TYPE_VOLUME:
2544 case HAMMER2_BREF_TYPE_FREEMAP:
2545 panic("hammer2_chain_create: called with volume type");
2547 case HAMMER2_BREF_TYPE_INDIRECT:
2548 panic("hammer2_chain_create: cannot be used to"
2549 "create indirect block");
2551 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2552 panic("hammer2_chain_create: cannot be used to"
2553 "create freemap root or node");
2555 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2556 KKASSERT(bytes == sizeof(chain->data->bmdata));
2558 case HAMMER2_BREF_TYPE_INODE:
2559 case HAMMER2_BREF_TYPE_DATA:
2562 * leave chain->data NULL, set INITIAL
2564 KKASSERT(chain->data == NULL);
2565 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2570 * We are reattaching a chain that has been duplicated and
2571 * left disconnected under a DIFFERENT parent with potentially
2572 * different key/keybits.
2574 * The chain must be modified in the current transaction
2575 * (the duplication code should have done that for us),
2576 * and it's modify_tid should be greater than the parent's
2577 * bref.mirror_tid. This should cause it to be created under
2580 * If deleted in the same transaction, the create/delete TIDs
2581 * will be the same and effective the chain will not have
2582 * existed at all from the point of view of the parent.
2584 * Do NOT mess with the current state of the INITIAL flag.
2586 KKASSERT(chain->modify_tid == trans->sync_tid);
2587 chain->bref.key = key;
2588 chain->bref.keybits = keybits;
2589 KKASSERT(chain->above == NULL);
2593 * Calculate how many entries we have in the blockref array and
2594 * determine if an indirect block is required.
2597 if (--maxloops == 0)
2598 panic("hammer2_chain_create: maxloops");
2599 above = parent->core;
2601 switch(parent->bref.type) {
2602 case HAMMER2_BREF_TYPE_INODE:
2603 KKASSERT((parent->data->ipdata.op_flags &
2604 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2605 KKASSERT(parent->data != NULL);
2606 base = &parent->data->ipdata.u.blockset.blockref[0];
2607 count = HAMMER2_SET_COUNT;
2609 case HAMMER2_BREF_TYPE_INDIRECT:
2610 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2611 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2614 base = &parent->data->npdata[0];
2615 count = parent->bytes / sizeof(hammer2_blockref_t);
2617 case HAMMER2_BREF_TYPE_VOLUME:
2618 KKASSERT(parent->data != NULL);
2619 base = &hmp->voldata.sroot_blockset.blockref[0];
2620 count = HAMMER2_SET_COUNT;
2622 case HAMMER2_BREF_TYPE_FREEMAP:
2623 KKASSERT(parent->data != NULL);
2624 base = &hmp->voldata.freemap_blockset.blockref[0];
2625 count = HAMMER2_SET_COUNT;
2628 panic("hammer2_chain_create: unrecognized blockref type: %d",
2636 * Make sure we've counted the brefs
2638 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2639 hammer2_chain_countbrefs(parent, base, count);
2641 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2644 * If no free blockref could be found we must create an indirect
2645 * block and move a number of blockrefs into it. With the parent
2646 * locked we can safely lock each child in order to delete+duplicate
2647 * it without causing a deadlock.
2649 * This may return the new indirect block or the old parent depending
2650 * on where the key falls. NULL is returned on error.
2652 if (above->live_count == count) {
2653 hammer2_chain_t *nparent;
2655 nparent = hammer2_chain_create_indirect(trans, parent,
2658 if (nparent == NULL) {
2660 hammer2_chain_drop(chain);
2664 if (parent != nparent) {
2665 hammer2_chain_unlock(parent);
2666 parent = *parentp = nparent;
2672 * Link the chain into its parent.
2674 if (chain->above != NULL)
2675 panic("hammer2: hammer2_chain_create: chain already connected");
2676 KKASSERT(chain->above == NULL);
2677 hammer2_chain_insert(above, NULL, chain,
2678 HAMMER2_CHAIN_INSERT_SPIN |
2679 HAMMER2_CHAIN_INSERT_LIVE,
2684 * Mark the newly created chain modified. This will cause
2685 * FLUSH_CREATE to be set.
2687 * Device buffers are not instantiated for DATA elements
2688 * as these are handled by logical buffers.
2690 * Indirect and freemap node indirect blocks are handled
2691 * by hammer2_chain_create_indirect() and not by this
2694 * Data for all other bref types is expected to be
2695 * instantiated (INODE, LEAF).
2697 switch(chain->bref.type) {
2698 case HAMMER2_BREF_TYPE_DATA:
2699 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2700 case HAMMER2_BREF_TYPE_INODE:
2701 hammer2_chain_modify(trans, &chain,
2702 HAMMER2_MODIFY_OPTDATA |
2703 HAMMER2_MODIFY_ASSERTNOCOPY);
2707 * Remaining types are not supported by this function.
2708 * In particular, INDIRECT and LEAF_NODE types are
2709 * handled by create_indirect().
2711 panic("hammer2_chain_create: bad type: %d",
2718 * When reconnecting a chain we must set FLUSH_CREATE and
2719 * setsubmod so the flush recognizes that it must update
2720 * the bref in the parent.
2722 if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
2723 hammer2_chain_ref(chain);
2724 atomic_set_int(&chain->flags,
2725 HAMMER2_CHAIN_FLUSH_CREATE);
2728 hammer2_chain_setsubmod(trans, chain);
2737 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2738 * the same core and media state as the orignal. The original *chainp is
2739 * unlocked and the replacement will be returned locked. The duplicated
2740 * chain is inserted under (*parentp).
2742 * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2743 * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2744 * FULL. This typically means that the caller is creating the chain after
2745 * doing a hammer2_chain_lookup().
2747 * The old chain must be in a DELETED state unless snapshot is non-zero.
2749 * The new chain will be live (i.e. not deleted), and modified.
2751 * If (parent) is non-NULL then the new duplicated chain is inserted under
2754 * If (parent) is NULL then the newly duplicated chain is not inserted
2755 * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2756 * passing into hammer2_chain_create() after this function returns).
2758 * WARNING! This function cannot take snapshots all by itself. The caller
2759 * needs to do other massaging for snapshots.
2761 * WARNING! This function calls create which means it can insert indirect
2762 * blocks. Callers may have to refactor locked chains held across
2763 * the call (other than the ones passed into the call).
2766 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2767 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2768 int snapshot, int duplicate_reason)
2770 hammer2_mount_t *hmp;
2771 hammer2_chain_t *parent;
2772 hammer2_chain_t *ochain;
2773 hammer2_chain_t *nchain;
2774 hammer2_chain_core_t *above;
2778 * We want nchain to be our go-to live chain, but ochain may be in
2779 * a MODIFIED state within the current flush synchronization segment.
2780 * Force any further modifications of ochain to do another COW
2781 * operation even if modify_tid indicates that one is not needed.
2783 * We don't want to set FORCECOW on nchain simply as an optimization,
2784 * as many duplication calls simply move chains into ichains and
2785 * then delete the original.
2787 * WARNING! We should never resolve DATA to device buffers
2788 * (XXX allow it if the caller did?), and since
2789 * we currently do not have the logical buffer cache
2790 * buffer in-hand to fix its cached physical offset
2791 * we also force the modify code to not COW it. XXX
2795 KKASSERT(snapshot == 1 || (ochain->flags & HAMMER2_CHAIN_DELETED));
2798 * Now create a duplicate of the chain structure, associating
2799 * it with the same core, making it the same size, pointing it
2800 * to the same bref (the same media block).
2802 * Give nchain the same modify_tid that we previously ensured was
2803 * sufficiently advanced to trigger a block table insertion on flush.
2805 * nchain copies ochain's data and must inherit ochain->update_lo.
2807 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2808 * hammer2_chain_alloc()
2811 bref = &ochain->bref;
2813 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2814 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2816 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2818 hammer2_chain_core_alloc(trans, nchain, ochain);
2819 bytes = (hammer2_off_t)1 <<
2820 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2821 nchain->bytes = bytes;
2822 nchain->modify_tid = ochain->modify_tid;
2823 nchain->update_lo = ochain->update_lo;
2824 nchain->inode_reason = ochain->inode_reason + 0x100000;
2825 atomic_set_int(&nchain->flags,
2826 ochain->flags & (HAMMER2_CHAIN_INITIAL |
2827 HAMMER2_CHAIN_FORCECOW |
2828 HAMMER2_CHAIN_UNLINKED));
2829 if (ochain->modify_tid == trans->sync_tid)
2830 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2833 * Switch from ochain to nchain
2835 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2836 HAMMER2_RESOLVE_NOREF);
2837 /* nchain has 1 ref */
2838 hammer2_chain_unlock(ochain);
2841 * Place nchain in the modified state, instantiate media data
2842 * if necessary. Because modify_tid is already completely
2843 * synchronized this should not result in a delete-duplicate.
2845 * We want nchain at the target to look like a new insertion.
2846 * Forcing the modification to be INPLACE accomplishes this
2847 * because we get the same nchain with an updated modify_tid.
2849 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2850 hammer2_chain_modify(trans, &nchain,
2851 HAMMER2_MODIFY_OPTDATA |
2852 HAMMER2_MODIFY_NOREALLOC |
2853 HAMMER2_MODIFY_INPLACE);
2854 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2855 hammer2_chain_modify(trans, &nchain,
2856 HAMMER2_MODIFY_OPTDATA |
2857 HAMMER2_MODIFY_INPLACE);
2859 hammer2_chain_modify(trans, &nchain,
2860 HAMMER2_MODIFY_INPLACE);
2864 * If parent is not NULL the duplicated chain will be entered under
2865 * the parent and the FLUSH_CREATE bit set to tell flush to update
2868 * Having both chains locked is extremely important for atomicy.
2870 if (parentp && (parent = *parentp) != NULL) {
2871 above = parent->core;
2872 KKASSERT(ccms_thread_lock_owned(&above->cst));
2873 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2874 KKASSERT(parent->refs > 0);
2876 hammer2_chain_create(trans, parentp, &nchain,
2877 nchain->bref.key, nchain->bref.keybits,
2878 nchain->bref.type, nchain->bytes);
2881 KKASSERT(nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE);
2882 hammer2_chain_setsubmod(trans, nchain);
2889 * Helper function for deleting chains.
2891 * The chain is removed from the live view (the RBTREE).
2893 * If appropriate, the chain is added to the shadow topology and FLUSH_DELETE
2894 * is set for flusher visbility. The caller is responsible for calling
2895 * setsubmod on chain, so we do not adjust update_hi here.
2898 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2899 hammer2_chain_core_t *above,
2900 hammer2_chain_t *chain)
2902 hammer2_mount_t *hmp;
2903 hammer2_chain_t *xchain;
2905 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2906 KKASSERT(trans->sync_tid >= chain->modify_tid);
2907 KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2908 HAMMER2_CHAIN_ONDBQ |
2909 HAMMER2_CHAIN_ONDBTREE |
2910 HAMMER2_CHAIN_FLUSH_DELETE)) == 0);
2913 * Flag as deleted, reduce live_count and bump the above core's
2916 chain->delete_tid = trans->sync_tid;
2917 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2918 atomic_add_int(&above->live_count, -1);
2919 ++above->generation;
2923 * Remove from live tree
2925 RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
2926 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2928 if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2930 * If the chain was originally bmapped we must place on the
2931 * deleted tree and set FLUSH_DELETE (+ref) to prevent
2932 * destruction of the chain until the flush can reconcile
2933 * the parent's block table.
2935 * NOTE! DBTREE is only representitive of the live view,
2936 * the flush must check both DBTREE and DBQ.
2938 xchain = RB_INSERT(hammer2_chain_tree, &above->dbtree, chain);
2939 KKASSERT(xchain == NULL);
2940 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
2942 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
2943 hammer2_chain_ref(chain);
2946 * If the chain no longer (and never had) an actual blockmap
2947 * entry we must place it on the dbq list and set FLUSH_DELETE
2948 * (+ref) to prevent destruction of the chain until the flush
2949 * can reconcile the parent's block table.
2951 * NOTE! DBTREE is only representitive of the live view,
2952 * the flush must check both DBTREE and DBQ.
2954 TAILQ_INSERT_TAIL(&above->dbq, chain, db_entry);
2955 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
2957 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
2958 hammer2_chain_ref(chain);
2963 * Special in-place delete-duplicate sequence which does not require a
2964 * locked parent. (*chainp) is marked DELETED and atomically replaced
2965 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2966 * order to ensure that lookups do not race us.
2968 * The flush code will sometimes call this function with a deleted chain.
2969 * In this situation the old chain's memory is reallocated without
2972 * The new chain will be marked modified for the current transaction.
2975 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2978 hammer2_mount_t *hmp;
2979 hammer2_chain_t *ochain;
2980 hammer2_chain_t *nchain;
2981 hammer2_chain_core_t *above;
2985 if (hammer2_debug & 0x20000)
2989 * Note that we do not have to call setsubmod on ochain, calling it
2990 * on nchain is sufficient.
2993 oflags = ochain->flags; /* flags prior to core_alloc mods */
2996 if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2997 KKASSERT(ochain->data);
3001 * First create a duplicate of the chain structure.
3002 * (nchain is allocated with one ref).
3004 * In the case where nchain inherits ochains core, nchain is
3005 * effectively locked due to ochain being locked (and sharing the
3006 * core), until we can give nchain its own official ock.
3008 * WARNING! Flusher concurrency can create two cases. The first is
3009 * that the flusher might be working on a chain that has
3010 * been deleted in the live view but is live in the flusher's
3011 * view. In the second case the flusher may be duplicating
3012 * a forward-transacted chain. In both situations nchain
3013 * must be marked deleted.
3015 * WARNING! hammer2_chain_core_alloc() also acts on these issues.
3017 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
3018 if ((ochain->flags & HAMMER2_CHAIN_DELETED) ||
3019 (ochain->modify_tid > trans->sync_tid)) {
3020 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
3022 if (flags & HAMMER2_DELDUP_RECORE)
3023 hammer2_chain_core_alloc(trans, nchain, NULL);
3025 hammer2_chain_core_alloc(trans, nchain, ochain);
3026 above = ochain->above;
3028 bytes = (hammer2_off_t)1 <<
3029 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3030 nchain->bytes = bytes;
3033 * nchain inherits ochain's live state including its modification
3034 * state. This function disposes of the original. Because we are
3035 * doing this in-place under the same parent the block array
3036 * inserted/deleted state does not change.
3038 * nchain copies ochain's data and must inherit ochain->update_lo.
3040 * If ochain was previously marked FORCECOW we also flag nchain
3041 * FORCECOW (used during hardlink splits). FORCECOW forces a
3042 * reallocation of the block when we modify the chain a little later,
3043 * it does not force another delete-duplicate.
3045 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
3046 * hammer2_chain_alloc()
3048 nchain->data_count += ochain->data_count;
3049 nchain->inode_count += ochain->inode_count;
3050 atomic_set_int(&nchain->flags,
3051 ochain->flags & (HAMMER2_CHAIN_INITIAL |
3052 HAMMER2_CHAIN_FORCECOW |
3053 HAMMER2_CHAIN_UNLINKED));
3054 if (ochain->modify_tid == trans->sync_tid)
3055 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
3056 nchain->inode_reason = ochain->inode_reason + 0x1000;
3057 nchain->update_lo = ochain->update_lo;
3058 nchain->dsrc = ochain->bref; /* DEBUG */
3059 nchain->dsrc_dupfromat = trans->sync_tid; /* DEBUG */
3060 nchain->dsrc_dupfromflags = trans->flags; /* DEBUG */
3061 nchain->dsrc_reason = ochain->inode_reason; /* DEBUG */
3062 nchain->dsrc_ninserts = ochain->ninserts; /* DEBUG */
3063 nchain->dsrc_flags = ochain->flags; /* DEBUG */
3064 nchain->dsrc_modify = ochain->modify_tid; /* DEBUG */
3065 nchain->dsrc_delete = ochain->delete_tid; /* DEBUG */
3066 nchain->dsrc_update_lo = ochain->update_lo; /* DEBUG */
3067 nchain->dsrc_original = ochain; /* DEBUG */
3070 * Lock nchain so both chains are now locked (extremely important
3071 * for atomicy). The shared core allows us to unlock ochain without
3072 * actually unlocking ochain.
3074 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
3075 /* extra ref still present from original allocation */
3077 KKASSERT(ochain->flags & (HAMMER2_CHAIN_ONRBTREE |
3078 HAMMER2_CHAIN_ONDBTREE |
3079 HAMMER2_CHAIN_ONDBQ));
3080 spin_lock(&above->cst.spin);
3082 nchain->modify_tid = ochain->modify_tid;
3083 nchain->delete_tid = HAMMER2_MAX_TID;
3085 if ((nchain->flags & HAMMER2_CHAIN_DELETED) &&
3086 (oflags & HAMMER2_CHAIN_DUPLICATED)) {
3088 * Special case, used by the flush code when a chain which
3089 * has been delete-duplicated is visible (effectively 'live')
3090 * in the flush code.
3092 * In this situations nchain will be marked deleted and
3093 * insert before ochain. nchain must inherit certain features
3096 KKASSERT(trans->flags & HAMMER2_TRANS_ISFLUSH);
3097 KKASSERT(ochain->modify_tid < trans->sync_tid);
3098 KKASSERT(ochain->delete_tid > trans->sync_tid);
3099 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_TEMPORARY);
3100 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3102 if ((ochain->flags & HAMMER2_CHAIN_DELETED) &&
3103 ochain->modify_tid < trans->sync_tid) {
3104 nchain->delete_tid = ochain->delete_tid;
3105 ochain->delete_tid = trans->sync_tid;
3106 } else if (ochain->modify_tid > trans->sync_tid) {
3107 nchain->delete_tid = ochain->modify_tid;
3109 } else if (nchain->flags & HAMMER2_CHAIN_DELETED) {
3111 * ochain is 'live' with respect to not having been D-D'd,
3112 * but is flagged DELETED. Sometimes updates to deleted
3113 * chains must be allowed due to references which still exist
3114 * on those chains, or due to a flush trying to retire a
3115 * logical buffer cache buffer.
3117 * In this situation the D-D operates normally, except
3118 * ochain has already been deleted and nchain is also
3121 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3122 nchain->delete_tid = trans->sync_tid;
3125 * Normal case, delete-duplicate deletes ochain and nchain
3126 * is the new live chain.
3128 _hammer2_chain_delete_helper(trans, above, ochain);
3129 hammer2_chain_insert(above, ochain, nchain,
3130 HAMMER2_CHAIN_INSERT_LIVE, 0);
3132 spin_unlock(&above->cst.spin);
3135 * ochain must be unlocked because ochain and nchain might share
3136 * a buffer cache buffer, so we need to release it so nchain can
3137 * potentially obtain it.
3139 hammer2_chain_setsubmod(trans, ochain);
3140 hammer2_chain_unlock(ochain);
3143 * Finishing fixing up nchain. A new block will be allocated if
3144 * crossing a synchronization point (meta-data only).
3146 * Calling hammer2_chain_modify() will update modify_tid to
3147 * (typically) trans->sync_tid.
3149 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3150 hammer2_chain_modify(trans, &nchain,
3151 HAMMER2_MODIFY_OPTDATA |
3152 HAMMER2_MODIFY_NOREALLOC |
3153 HAMMER2_MODIFY_INPLACE);
3154 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3155 hammer2_chain_modify(trans, &nchain,
3156 HAMMER2_MODIFY_OPTDATA |
3157 HAMMER2_MODIFY_INPLACE);
3159 hammer2_chain_modify(trans, &nchain,
3160 HAMMER2_MODIFY_INPLACE);
3162 hammer2_chain_drop(nchain);
3165 * Unconditionally set FLUSH_CREATE to force the parent blockrefs to
3166 * update as the chain_modify() above won't necessarily do it.
3168 if ((nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
3169 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
3170 hammer2_chain_ref(nchain);
3174 * If nchain is in a DELETED state we must set FLUSH_DELETE
3176 if (nchain->flags & HAMMER2_CHAIN_DELETED)
3177 KKASSERT((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0);
3179 if ((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0 &&
3180 (nchain->flags & HAMMER2_CHAIN_DELETED)) {
3181 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
3182 hammer2_chain_ref(nchain);
3185 hammer2_chain_setsubmod(trans, nchain);
3190 * Create a snapshot of the specified {parent, ochain} with the specified
3191 * label. The originating hammer2_inode must be exclusively locked for
3194 * The ioctl code has already synced the filesystem.
3197 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
3198 hammer2_ioc_pfs_t *pfs)
3200 hammer2_mount_t *hmp;
3201 hammer2_chain_t *ochain = *ochainp;
3202 hammer2_chain_t *nchain;
3203 hammer2_inode_data_t *ipdata;
3204 hammer2_inode_t *nip;
3211 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
3212 pfs->name, ochain->refs, ochain->flags);
3214 name_len = strlen(pfs->name);
3215 lhc = hammer2_dirhash(pfs->name, name_len);
3218 opfs_clid = ochain->data->ipdata.pfs_clid;
3223 * Create the snapshot directory under the super-root
3225 * Set PFS type, generate a unique filesystem id, and generate
3226 * a cluster id. Use the same clid when snapshotting a PFS root,
3227 * which theoretically allows the snapshot to be used as part of
3228 * the same cluster (perhaps as a cache).
3230 * Copy the (flushed) ochain's blockref array. Theoretically we
3231 * could use chain_duplicate() but it becomes difficult to disentangle
3232 * the shared core so for now just brute-force it.
3238 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
3239 pfs->name, name_len, &nchain, &error);
3242 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
3243 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
3244 kern_uuidgen(&ipdata->pfs_fsid, 1);
3245 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
3246 ipdata->pfs_clid = opfs_clid;
3248 kern_uuidgen(&ipdata->pfs_clid, 1);
3249 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
3250 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
3252 hammer2_inode_unlock_ex(nip, nchain);
3258 * Create an indirect block that covers one or more of the elements in the
3259 * current parent. Either returns the existing parent with no locking or
3260 * ref changes or returns the new indirect block locked and referenced
3261 * and leaving the original parent lock/ref intact as well.
3263 * If an error occurs, NULL is returned and *errorp is set to the error.
3265 * The returned chain depends on where the specified key falls.
3267 * The key/keybits for the indirect mode only needs to follow three rules:
3269 * (1) That all elements underneath it fit within its key space and
3271 * (2) That all elements outside it are outside its key space.
3273 * (3) When creating the new indirect block any elements in the current
3274 * parent that fit within the new indirect block's keyspace must be
3275 * moved into the new indirect block.
3277 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3278 * keyspace the the current parent, but lookup/iteration rules will
3279 * ensure (and must ensure) that rule (2) for all parents leading up
3280 * to the nearest inode or the root volume header is adhered to. This
3281 * is accomplished by always recursing through matching keyspaces in
3282 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3284 * The current implementation calculates the current worst-case keyspace by
3285 * iterating the current parent and then divides it into two halves, choosing
3286 * whichever half has the most elements (not necessarily the half containing
3287 * the requested key).
3289 * We can also opt to use the half with the least number of elements. This
3290 * causes lower-numbered keys (aka logical file offsets) to recurse through
3291 * fewer indirect blocks and higher-numbered keys to recurse through more.
3292 * This also has the risk of not moving enough elements to the new indirect
3293 * block and being forced to create several indirect blocks before the element
3296 * Must be called with an exclusively locked parent.
3298 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3299 hammer2_key_t *keyp, int keybits,
3300 hammer2_blockref_t *base, int count);
3301 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3302 hammer2_key_t *keyp, int keybits,
3303 hammer2_blockref_t *base, int count);
3306 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3307 hammer2_key_t create_key, int create_bits,
3308 int for_type, int *errorp)
3310 hammer2_mount_t *hmp;
3311 hammer2_chain_core_t *above;
3312 hammer2_chain_core_t *icore;
3313 hammer2_blockref_t *base;
3314 hammer2_blockref_t *bref;
3315 hammer2_blockref_t bcopy;
3316 hammer2_chain_t *chain;
3317 hammer2_chain_t *ichain;
3318 hammer2_chain_t dummy;
3319 hammer2_key_t key = create_key;
3320 hammer2_key_t key_beg;
3321 hammer2_key_t key_end;
3322 hammer2_key_t key_next;
3323 int keybits = create_bits;
3330 int maxloops = 300000;
3335 * Calculate the base blockref pointer or NULL if the chain
3336 * is known to be empty. We need to calculate the array count
3337 * for RB lookups either way.
3341 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3342 above = parent->core;
3344 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3345 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3348 switch(parent->bref.type) {
3349 case HAMMER2_BREF_TYPE_INODE:
3350 count = HAMMER2_SET_COUNT;
3352 case HAMMER2_BREF_TYPE_INDIRECT:
3353 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3354 count = parent->bytes / sizeof(hammer2_blockref_t);
3356 case HAMMER2_BREF_TYPE_VOLUME:
3357 count = HAMMER2_SET_COUNT;
3359 case HAMMER2_BREF_TYPE_FREEMAP:
3360 count = HAMMER2_SET_COUNT;
3363 panic("hammer2_chain_create_indirect: "
3364 "unrecognized blockref type: %d",
3370 switch(parent->bref.type) {
3371 case HAMMER2_BREF_TYPE_INODE:
3372 base = &parent->data->ipdata.u.blockset.blockref[0];
3373 count = HAMMER2_SET_COUNT;
3375 case HAMMER2_BREF_TYPE_INDIRECT:
3376 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3377 base = &parent->data->npdata[0];
3378 count = parent->bytes / sizeof(hammer2_blockref_t);
3380 case HAMMER2_BREF_TYPE_VOLUME:
3381 base = &hmp->voldata.sroot_blockset.blockref[0];
3382 count = HAMMER2_SET_COUNT;
3384 case HAMMER2_BREF_TYPE_FREEMAP:
3385 base = &hmp->voldata.freemap_blockset.blockref[0];
3386 count = HAMMER2_SET_COUNT;
3389 panic("hammer2_chain_create_indirect: "
3390 "unrecognized blockref type: %d",
3398 * dummy used in later chain allocation (no longer used for lookups).
3400 bzero(&dummy, sizeof(dummy));
3401 dummy.delete_tid = HAMMER2_MAX_TID;
3404 * When creating an indirect block for a freemap node or leaf
3405 * the key/keybits must be fitted to static radix levels because
3406 * particular radix levels use particular reserved blocks in the
3409 * This routine calculates the key/radix of the indirect block
3410 * we need to create, and whether it is on the high-side or the
3413 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3414 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3415 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3418 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3423 * Normalize the key for the radix being represented, keeping the
3424 * high bits and throwing away the low bits.
3426 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3429 * How big should our new indirect block be? It has to be at least
3430 * as large as its parent.
3432 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3433 nbytes = HAMMER2_IND_BYTES_MIN;
3435 nbytes = HAMMER2_IND_BYTES_MAX;
3436 if (nbytes < count * sizeof(hammer2_blockref_t))
3437 nbytes = count * sizeof(hammer2_blockref_t);
3440 * Ok, create our new indirect block
3442 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3443 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3444 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3446 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3448 dummy.bref.key = key;
3449 dummy.bref.keybits = keybits;
3450 dummy.bref.data_off = hammer2_getradix(nbytes);
3451 dummy.bref.methods = parent->bref.methods;
3453 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3454 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3455 hammer2_chain_core_alloc(trans, ichain, NULL);
3456 icore = ichain->core;
3457 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3458 hammer2_chain_drop(ichain); /* excess ref from alloc */
3461 * We have to mark it modified to allocate its block, but use
3462 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3463 * it won't be acted upon by the flush code.
3465 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3468 * Iterate the original parent and move the matching brefs into
3469 * the new indirect block.
3471 * XXX handle flushes.
3474 key_end = HAMMER2_MAX_KEY;
3476 spin_lock(&above->cst.spin);
3482 if (++loops > 100000) {
3483 spin_unlock(&above->cst.spin);
3484 panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3485 reason, parent, base, count, key_next);
3489 * NOTE: spinlock stays intact, returned chain (if not NULL)
3490 * is not referenced or locked which means that we
3491 * cannot safely check its flagged / deletion status
3494 chain = hammer2_combined_find(parent, base, count,
3495 &cache_index, &key_next,
3498 generation = above->generation;
3501 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3504 * Skip keys that are not within the key/radix of the new
3505 * indirect block. They stay in the parent.
3507 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3508 (key ^ bref->key)) != 0) {
3509 goto next_key_spinlocked;
3513 * Load the new indirect block by acquiring the related
3514 * chains (potentially from media as it might not be
3515 * in-memory). Then move it to the new parent (ichain)
3516 * via DELETE-DUPLICATE.
3518 * chain is referenced but not locked. We must lock the
3519 * chain to obtain definitive DUPLICATED/DELETED state
3523 * Use chain already present in the RBTREE
3525 hammer2_chain_ref(chain);
3526 wasdup = ((chain->flags &
3527 HAMMER2_CHAIN_DUPLICATED) != 0);
3528 spin_unlock(&above->cst.spin);
3529 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3530 HAMMER2_RESOLVE_NOREF);
3533 * Get chain for blockref element. _get returns NULL
3534 * on insertion race.
3537 spin_unlock(&above->cst.spin);
3538 chain = hammer2_chain_get(parent, generation, &bcopy);
3539 if (chain == NULL) {
3541 spin_lock(&above->cst.spin);
3544 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3546 hammer2_chain_drop(chain);
3547 spin_lock(&above->cst.spin);
3550 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3551 HAMMER2_RESOLVE_NOREF);
3556 * This is always live so if the chain has been delete-
3557 * duplicated we raced someone and we have to retry.
3559 * NOTE: Lookups can race delete-duplicate because
3560 * delete-duplicate does not lock the parent's core
3561 * (they just use the spinlock on the core). We must
3562 * check for races by comparing the DUPLICATED flag before
3563 * releasing the spinlock with the flag after locking the
3566 * (note reversed logic for this one)
3568 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3569 hammer2_chain_unlock(chain);
3570 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) &&
3578 * Shift the chain to the indirect block.
3580 * WARNING! Can cause held-over chains to require a refactor.
3581 * Fortunately we have none (our locked chains are
3582 * passed into and modified by the call).
3584 hammer2_chain_delete(trans, chain, 0);
3585 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0, 1);
3586 hammer2_chain_unlock(chain);
3587 KKASSERT(parent->refs > 0);
3590 spin_lock(&above->cst.spin);
3591 next_key_spinlocked:
3592 if (--maxloops == 0)
3593 panic("hammer2_chain_create_indirect: maxloops");
3595 if (retry_same == 0) {
3596 if (key_next == 0 || key_next > key_end)
3602 spin_unlock(&above->cst.spin);
3605 * Insert the new indirect block into the parent now that we've
3606 * cleared out some entries in the parent. We calculated a good
3607 * insertion index in the loop above (ichain->index).
3609 * We don't have to set FLUSH_CREATE here because we mark ichain
3610 * modified down below (so the normal modified -> flush -> set-moved
3611 * sequence applies).
3613 * The insertion shouldn't race as this is a completely new block
3614 * and the parent is locked.
3616 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3617 hammer2_chain_insert(above, NULL, ichain,
3618 HAMMER2_CHAIN_INSERT_SPIN |
3619 HAMMER2_CHAIN_INSERT_LIVE,
3623 * Mark the new indirect block modified after insertion, which
3624 * will propagate up through parent all the way to the root and
3625 * also allocate the physical block in ichain for our caller,
3626 * and assign ichain->data to a pre-zero'd space (because there
3627 * is not prior data to copy into it).
3629 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3630 hammer2_chain_setsubmod(trans, ichain);
3633 * Figure out what to return.
3635 if (~(((hammer2_key_t)1 << keybits) - 1) &
3636 (create_key ^ key)) {
3638 * Key being created is outside the key range,
3639 * return the original parent.
3641 hammer2_chain_unlock(ichain);
3644 * Otherwise its in the range, return the new parent.
3645 * (leave both the new and old parent locked).
3654 * Calculate the keybits and highside/lowside of the freemap node the
3655 * caller is creating.
3657 * This routine will specify the next higher-level freemap key/radix
3658 * representing the lowest-ordered set. By doing so, eventually all
3659 * low-ordered sets will be moved one level down.
3661 * We have to be careful here because the freemap reserves a limited
3662 * number of blocks for a limited number of levels. So we can't just
3663 * push indiscriminately.
3666 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3667 int keybits, hammer2_blockref_t *base, int count)
3669 hammer2_chain_core_t *above;
3670 hammer2_chain_t *chain;
3671 hammer2_blockref_t *bref;
3673 hammer2_key_t key_beg;
3674 hammer2_key_t key_end;
3675 hammer2_key_t key_next;
3679 int maxloops = 300000;
3682 above = parent->core;
3688 * Calculate the range of keys in the array being careful to skip
3689 * slots which are overridden with a deletion.
3692 key_end = HAMMER2_MAX_KEY;
3694 spin_lock(&above->cst.spin);
3697 if (--maxloops == 0) {
3698 panic("indkey_freemap shit %p %p:%d\n",
3699 parent, base, count);
3701 chain = hammer2_combined_find(parent, base, count,
3702 &cache_index, &key_next,
3713 * NOTE: No need to check DUPLICATED here because we do
3714 * not release the spinlock.
3716 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3717 if (key_next == 0 || key_next > key_end)
3724 * Use the full live (not deleted) element for the scan
3725 * iteration. HAMMER2 does not allow partial replacements.
3727 * XXX should be built into hammer2_combined_find().
3729 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3731 if (keybits > bref->keybits) {
3733 keybits = bref->keybits;
3734 } else if (keybits == bref->keybits && bref->key < key) {
3741 spin_unlock(&above->cst.spin);
3744 * Return the keybits for a higher-level FREEMAP_NODE covering
3748 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3749 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3751 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3752 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3754 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3755 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3757 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3758 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3760 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3761 panic("hammer2_chain_indkey_freemap: level too high");
3764 panic("hammer2_chain_indkey_freemap: bad radix");
3773 * Calculate the keybits and highside/lowside of the indirect block the
3774 * caller is creating.
3777 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3778 int keybits, hammer2_blockref_t *base, int count)
3780 hammer2_chain_core_t *above;
3781 hammer2_blockref_t *bref;
3782 hammer2_chain_t *chain;
3783 hammer2_key_t key_beg;
3784 hammer2_key_t key_end;
3785 hammer2_key_t key_next;
3791 int maxloops = 300000;
3794 above = parent->core;
3799 * Calculate the range of keys in the array being careful to skip
3800 * slots which are overridden with a deletion. Once the scan
3801 * completes we will cut the key range in half and shift half the
3802 * range into the new indirect block.
3805 key_end = HAMMER2_MAX_KEY;
3807 spin_lock(&above->cst.spin);
3810 if (--maxloops == 0) {
3811 panic("indkey_freemap shit %p %p:%d\n",
3812 parent, base, count);
3814 chain = hammer2_combined_find(parent, base, count,
3815 &cache_index, &key_next,
3826 * NOTE: No need to check DUPLICATED here because we do
3827 * not release the spinlock.
3829 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3830 if (key_next == 0 || key_next > key_end)
3837 * Use the full live (not deleted) element for the scan
3838 * iteration. HAMMER2 does not allow partial replacements.
3840 * XXX should be built into hammer2_combined_find().
3842 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3845 * Expand our calculated key range (key, keybits) to fit
3846 * the scanned key. nkeybits represents the full range
3847 * that we will later cut in half (two halves @ nkeybits - 1).
3850 if (nkeybits < bref->keybits) {
3851 if (bref->keybits > 64) {
3852 kprintf("bad bref chain %p bref %p\n",
3856 nkeybits = bref->keybits;
3858 while (nkeybits < 64 &&
3859 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3860 (key ^ bref->key)) != 0) {
3865 * If the new key range is larger we have to determine
3866 * which side of the new key range the existing keys fall
3867 * under by checking the high bit, then collapsing the
3868 * locount into the hicount or vise-versa.
3870 if (keybits != nkeybits) {
3871 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3882 * The newly scanned key will be in the lower half or the
3883 * upper half of the (new) key range.
3885 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3894 spin_unlock(&above->cst.spin);
3895 bref = NULL; /* now invalid (safety) */
3898 * Adjust keybits to represent half of the full range calculated
3899 * above (radix 63 max)
3904 * Select whichever half contains the most elements. Theoretically
3905 * we can select either side as long as it contains at least one
3906 * element (in order to ensure that a free slot is present to hold
3907 * the indirect block).
3909 if (hammer2_indirect_optimize) {
3911 * Insert node for least number of keys, this will arrange
3912 * the first few blocks of a large file or the first few
3913 * inodes in a directory with fewer indirect blocks when
3916 if (hicount < locount && hicount != 0)
3917 key |= (hammer2_key_t)1 << keybits;
3919 key &= ~(hammer2_key_t)1 << keybits;
3922 * Insert node for most number of keys, best for heavily
3925 if (hicount > locount)
3926 key |= (hammer2_key_t)1 << keybits;
3928 key &= ~(hammer2_key_t)1 << keybits;
3936 * Sets CHAIN_DELETED and CHAIN_FLUSH_DELETE in the chain being deleted and
3937 * set chain->delete_tid. The chain is not actually marked possibly-free
3938 * in the freemap until the deletion is completely flushed out (because
3939 * a flush which doesn't cover the entire deletion is flushing the deleted
3940 * chain as if it were live).
3942 * This function does NOT generate a modification to the parent. It
3943 * would be nearly impossible to figure out which parent to modify anyway.
3944 * Such modifications are handled top-down by the flush code and are
3945 * properly merged using the flush synchronization point.
3947 * The find/get code will properly overload the RBTREE check on top of
3948 * the bref check to detect deleted entries.
3950 * This function is NOT recursive. Any entity already pushed into the
3951 * chain (such as an inode) may still need visibility into its contents,
3952 * as well as the ability to read and modify the contents. For example,
3953 * for an unlinked file which is still open.
3955 * NOTE: This function does NOT set chain->modify_tid, allowing future
3956 * code to distinguish between live and deleted chains by testing
3957 * trans->sync_tid vs chain->modify_tid and chain->delete_tid.
3959 * NOTE: Deletions normally do not occur in the middle of a duplication
3960 * chain but we use a trick for hardlink migration that refactors
3961 * the originating inode without deleting it, so we make no assumptions
3965 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3967 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3970 * Nothing to do if already marked.
3972 if (chain->flags & HAMMER2_CHAIN_DELETED)
3976 * The setting of DELETED causes finds, lookups, and _next iterations
3977 * to no longer recognize the chain. RB_SCAN()s will still have
3978 * visibility (needed for flush serialization points).
3980 * We need the spinlock on the core whos RBTREE contains chain
3981 * to protect against races.
3983 spin_lock(&chain->above->cst.spin);
3984 _hammer2_chain_delete_helper(trans, chain->above, chain);
3985 spin_unlock(&chain->above->cst.spin);
3987 hammer2_chain_setsubmod(trans, chain);
3991 * Returns the index of the nearest element in the blockref array >= elm.
3992 * Returns (count) if no element could be found. If delete_filter is non-zero
3993 * the scan filters out any blockrefs which match deleted chains on dbtree.
3995 * Sets *key_nextp to the next key for loop purposes but does not modify
3996 * it if the next key would be higher than the current value of *key_nextp.
3997 * Note that *key_nexp can overflow to 0, which should be tested by the
4000 * (*cache_indexp) is a heuristic and can be any value without effecting
4003 * The spin lock on the related chain must be held.
4006 hammer2_base_find(hammer2_chain_t *parent,
4007 hammer2_blockref_t *base, int count,
4008 int *cache_indexp, hammer2_key_t *key_nextp,
4009 hammer2_key_t key_beg, hammer2_key_t key_end,
4012 hammer2_chain_core_t *core = parent->core;
4013 hammer2_blockref_t *scan;
4014 hammer2_key_t scan_end;
4019 * Require the live chain's already have their core's counted
4020 * so we can optimize operations.
4022 KKASSERT((parent->flags & HAMMER2_CHAIN_DUPLICATED) ||
4023 core->flags & HAMMER2_CORE_COUNTEDBREFS);
4028 if (count == 0 || base == NULL)
4032 * Sequential optimization using *cache_indexp. This is the most
4035 * We can avoid trailing empty entries on live chains, otherwise
4036 * we might have to check the whole block array.
4040 if (parent->flags & HAMMER2_CHAIN_DUPLICATED)
4043 limit = core->live_zero;
4048 KKASSERT(i < count);
4054 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4061 * Search forwards, stop when we find a scan element which
4062 * encloses the key or until we know that there are no further
4066 if (scan->type != 0) {
4067 scan_end = scan->key +
4068 ((hammer2_key_t)1 << scan->keybits) - 1;
4069 if (scan->key > key_beg || scan_end >= key_beg) {
4071 * Check to see if the entry is covered by
4072 * a deleted chain and ignore the entry if
4073 * it is and delete_filter != 0.
4075 if (delete_filter == 0)
4077 if (hammer2_chain_find_deleted(
4078 parent, scan->key, scan_end) == NULL) {
4093 scan_end = scan->key +
4094 ((hammer2_key_t)1 << scan->keybits);
4095 if (scan_end && (*key_nextp > scan_end ||
4097 *key_nextp = scan_end;
4105 * Do a combined search and return the next match either from the blockref
4106 * array or from the in-memory chain. Sets *bresp to the returned bref in
4107 * both cases, or sets it to NULL if the search exhausted. Only returns
4108 * a non-NULL chain if the search matched from the in-memory chain.
4110 * When no in-memory chain has been found and a non-NULL bref is returned
4113 * Must be called with above's spinlock held. Spinlock remains held
4114 * through the operation.
4116 * The returned chain is not locked or referenced. Use the returned bref
4117 * to determine if the search exhausted or not. Iterate if the base find
4118 * is chosen but matches a deleted chain.
4120 static hammer2_chain_t *
4121 hammer2_combined_find(hammer2_chain_t *parent,
4122 hammer2_blockref_t *base, int count,
4123 int *cache_indexp, hammer2_key_t *key_nextp,
4124 hammer2_key_t key_beg, hammer2_key_t key_end,
4125 hammer2_blockref_t **bresp)
4127 hammer2_blockref_t *bref;
4128 hammer2_chain_t *chain;
4132 * Lookup in block array and in rbtree.
4134 *key_nextp = key_end + 1;
4135 i = hammer2_base_find(parent, base, count, cache_indexp,
4136 key_nextp, key_beg, key_end, 1);
4137 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4142 if (i == count && chain == NULL) {
4148 * Only chain matched.
4151 bref = &chain->bref;
4156 * Only blockref matched.
4158 if (chain == NULL) {
4164 * Both in-memory and blockref matched, select the nearer element.
4166 * If both are flush with the left-hand side or both are the
4167 * same distance away, select the chain. In this situation the
4168 * chain must have been loaded from the matching blockmap.
4170 if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4171 chain->bref.key == base[i].key) {
4172 KKASSERT(chain->bref.key == base[i].key);
4173 if ((chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
4174 kprintf("chain not bmapped %p.%d %08x\n", chain, chain->bref.type, chain->flags);
4175 kprintf("in chain mod/del %016jx %016jx\n", chain->modify_tid, chain->delete_tid);
4176 kprintf("and updlo/hi %016jx %016jx\n", chain->update_lo, chain->update_hi);
4178 KKASSERT(chain->flags & HAMMER2_CHAIN_BMAPPED);
4179 bref = &chain->bref;
4184 * Select the nearer key
4186 if (chain->bref.key < base[i].key) {
4187 bref = &chain->bref;
4194 * If the bref is out of bounds we've exhausted our search.
4197 if (bref->key > key_end) {
4207 * Locate the specified block array element and delete it. The element
4210 * The spin lock on the related chain must be held.
4212 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4213 * need to be adjusted when we commit the media change.
4216 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
4217 hammer2_blockref_t *base, int count,
4218 int *cache_indexp, hammer2_chain_t *child)
4220 hammer2_blockref_t *elm = &child->bref;
4221 hammer2_chain_core_t *core = parent->core;
4222 hammer2_key_t key_next;
4226 * Delete element. Expect the element to exist.
4228 * XXX see caller, flush code not yet sophisticated enough to prevent
4229 * re-flushed in some cases.
4231 key_next = 0; /* max range */
4232 i = hammer2_base_find(parent, base, count, cache_indexp,
4233 &key_next, elm->key, elm->key, 0);
4234 if (i == count || base[i].type == 0 ||
4235 base[i].key != elm->key || base[i].keybits != elm->keybits) {
4236 spin_unlock(&core->cst.spin);
4237 panic("delete base %p element not found at %d/%d elm %p\n"
4238 "child ino_reason=%08x\n",
4239 base, i, count, elm,
4240 child->inode_reason);
4243 bzero(&base[i], sizeof(*base));
4244 base[i].mirror_tid = (intptr_t)parent; /* MEDIA DEBUG */
4245 base[i].modify_tid = (intptr_t)child; /* MEDIA DEBUG */
4246 base[i].check.debug.sync_tid = trans->sync_tid; /* MEDIA DEBUG */
4247 ++parent->nremoves; /* DEBUG */
4250 * We can only optimize core->live_zero for live chains.
4252 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4253 if (core->live_zero == i + 1) {
4254 while (--i >= 0 && base[i].type == 0)
4256 core->live_zero = i + 1;
4262 * Insert the specified element. The block array must not already have the
4263 * element and must have space available for the insertion.
4265 * The spin lock on the related chain must be held.
4267 * NOTE: live_count was adjusted when the chain was deleted, so it does not
4268 * need to be adjusted when we commit the media change.
4271 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
4272 hammer2_blockref_t *base, int count,
4273 int *cache_indexp, hammer2_chain_t *child)
4275 hammer2_blockref_t *elm = &child->bref;
4276 hammer2_chain_core_t *core = parent->core;
4277 hammer2_key_t key_next;
4286 * Insert new element. Expect the element to not already exist
4287 * unless we are replacing it.
4289 * XXX see caller, flush code not yet sophisticated enough to prevent
4290 * re-flushed in some cases.
4292 key_next = 0; /* max range */
4293 i = hammer2_base_find(parent, base, count, cache_indexp,
4294 &key_next, elm->key, elm->key, 0);
4297 * Shortcut fill optimization, typical ordered insertion(s) may not
4300 KKASSERT(i >= 0 && i <= count);
4303 * We can only optimize core->live_zero for live chains.
4305 if (i == count && core->live_zero < count) {
4306 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4307 i = core->live_zero++;
4309 ++parent->ninserts; /* DEBUG */
4314 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4315 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4316 if (child->flags & HAMMER2_CHAIN_FLUSH_TEMPORARY) {
4317 kprintf("child %p special replace\n", child);
4321 spin_unlock(&core->cst.spin);
4322 panic("insert base %p overlapping "
4323 "elements at %d elm %p\n",
4329 * Try to find an empty slot before or after.
4333 while (j > 0 || k < count) {
4335 if (j >= 0 && base[j].type == 0) {
4339 bcopy(&base[j+1], &base[j],
4340 (i - j - 1) * sizeof(*base));
4343 ++parent->ninserts; /* DEBUG */
4347 if (k < count && base[k].type == 0) {
4348 bcopy(&base[i], &base[i+1],
4349 (k - i) * sizeof(hammer2_blockref_t));
4353 * We can only update core->live_zero for live
4356 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4357 if (core->live_zero <= k)
4358 core->live_zero = k + 1;
4361 ++parent->ninserts; /* DEBUG */
4365 panic("hammer2_base_insert: no room!");
4372 for (l = 0; l < count; ++l) {
4374 key_next = base[l].key +
4375 ((hammer2_key_t)1 << base[l].keybits) - 1;
4379 while (++l < count) {
4381 if (base[l].key <= key_next)
4382 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4383 key_next = base[l].key +
4384 ((hammer2_key_t)1 << base[l].keybits) - 1;
4394 * Sort the blockref array for the chain. Used by the flush code to
4395 * sort the blockref[] array.
4397 * The chain must be exclusively locked AND spin-locked.
4399 typedef hammer2_blockref_t *hammer2_blockref_p;
4403 hammer2_base_sort_callback(const void *v1, const void *v2)
4405 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4406 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4409 * Make sure empty elements are placed at the end of the array
4411 if (bref1->type == 0) {
4412 if (bref2->type == 0)
4415 } else if (bref2->type == 0) {
4422 if (bref1->key < bref2->key)
4424 if (bref1->key > bref2->key)
4430 hammer2_base_sort(hammer2_chain_t *chain)
4432 hammer2_blockref_t *base;
4435 switch(chain->bref.type) {
4436 case HAMMER2_BREF_TYPE_INODE:
4438 * Special shortcut for embedded data returns the inode
4439 * itself. Callers must detect this condition and access
4440 * the embedded data (the strategy code does this for us).
4442 * This is only applicable to regular files and softlinks.
4444 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4446 base = &chain->data->ipdata.u.blockset.blockref[0];
4447 count = HAMMER2_SET_COUNT;
4449 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4450 case HAMMER2_BREF_TYPE_INDIRECT:
4452 * Optimize indirect blocks in the INITIAL state to avoid
4455 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4456 base = &chain->data->npdata[0];
4457 count = chain->bytes / sizeof(hammer2_blockref_t);
4459 case HAMMER2_BREF_TYPE_VOLUME:
4460 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4461 count = HAMMER2_SET_COUNT;
4463 case HAMMER2_BREF_TYPE_FREEMAP:
4464 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4465 count = HAMMER2_SET_COUNT;
4468 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4470 base = NULL; /* safety */
4471 count = 0; /* safety */
4473 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4479 * Chain memory management
4482 hammer2_chain_wait(hammer2_chain_t *chain)
4484 tsleep(chain, 0, "chnflw", 1);
4488 * Manage excessive memory resource use for chain and related
4492 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4502 * Atomic check condition and wait. Also do an early speedup of
4503 * the syncer to try to avoid hitting the wait.
4506 waiting = pmp->inmem_dirty_chains;
4508 count = waiting & HAMMER2_DIRTYCHAIN_MASK;
4510 limit = pmp->mp->mnt_nvnodelistsize / 10;
4511 if (limit < hammer2_limit_dirty_chains)
4512 limit = hammer2_limit_dirty_chains;
4517 if ((int)(ticks - zzticks) > hz) {
4519 kprintf("count %ld %ld\n", count, limit);
4524 * Block if there are too many dirty chains present, wait
4525 * for the flush to clean some out.
4527 if (count > limit) {
4528 tsleep_interlock(&pmp->inmem_dirty_chains, 0);
4529 if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4531 waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
4532 speedup_syncer(pmp->mp);
4533 tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
4536 continue; /* loop on success or fail */
4540 * Try to start an early flush before we are forced to block.
4542 if (count > limit * 7 / 10)
4543 speedup_syncer(pmp->mp);
4549 hammer2_chain_memory_inc(hammer2_pfsmount_t *pmp)
4552 atomic_add_long(&pmp->inmem_dirty_chains, 1);
4556 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4564 waiting = pmp->inmem_dirty_chains;
4566 if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4569 ~HAMMER2_DIRTYCHAIN_WAITING)) {
4574 if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
4575 wakeup(&pmp->inmem_dirty_chains);
4580 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4584 switch(bref->type) {
4585 case HAMMER2_BREF_TYPE_DATA:
4586 counterp = &hammer2_iod_file_read;
4588 case HAMMER2_BREF_TYPE_INODE:
4589 counterp = &hammer2_iod_meta_read;
4591 case HAMMER2_BREF_TYPE_INDIRECT:
4592 counterp = &hammer2_iod_indr_read;
4594 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4595 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4596 counterp = &hammer2_iod_fmap_read;
4599 counterp = &hammer2_iod_volu_read;