2 * Copyright (c) 2011-2013 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@dragonflybsd.org>
6 * by Venkatesh Srinivas <vsrinivas@dragonflybsd.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
18 * 3. Neither the name of The DragonFly Project nor the names of its
19 * contributors may be used to endorse or promote products derived
20 * from this software without specific, prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
30 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
32 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * This subsystem implements most of the core support functions for
37 * the hammer2_chain structure.
39 * Chains are the in-memory version on media objects (volume header, inodes,
40 * indirect blocks, data blocks, etc). Chains represent a portion of the
43 * A chain is topologically stable once it has been inserted into the
44 * in-memory topology. Modifications which copy, move, or resize the chain
45 * are handled via the DELETE-DUPLICATE mechanic where the original chain
46 * stays intact but is marked deleted and a new chain is allocated which
47 * shares the old chain's children.
49 * This sharing is handled via the hammer2_chain_core structure.
51 * The DELETE-DUPLICATE mechanism allows the same topological level to contain
52 * many overloadings. However, our RBTREE mechanics require that there be
53 * no overlaps so we accomplish the overloading by moving conflicting chains
54 * with smaller or equal radii into a sub-RBTREE under the chain being
57 * DELETE-DUPLICATE is also used when a modification to a chain crosses a
58 * flush synchronization boundary, allowing the flush code to continue flushing
59 * the older version of the topology and not be disrupted by new frontend
64 * All lookup and iterate operations and most modifications are done on the
65 * live view. During flushes lookups are not normally done and modifications
66 * may be run on the flush view. However, flushes often needs to allocate
67 * blocks and the freemap_alloc/free code issues lookups. This code is
68 * special cased to use the live view when called from a flush.
70 * General chain lookup/iteration functions are NOT aware of the flush view,
71 * they only know about live views.
73 #include <sys/cdefs.h>
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/types.h>
78 #include <sys/kern_syscall.h>
83 static int hammer2_indirect_optimize; /* XXX SYSCTL */
85 static hammer2_chain_t *hammer2_chain_create_indirect(
86 hammer2_trans_t *trans, hammer2_chain_t *parent,
87 hammer2_key_t key, int keybits, int for_type, int *errorp);
88 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
89 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
90 static hammer2_chain_t *hammer2_combined_find(
91 hammer2_chain_t *parent,
92 hammer2_blockref_t *base, int count,
93 int *cache_indexp, hammer2_key_t *key_nextp,
94 hammer2_key_t key_beg, hammer2_key_t key_end,
95 hammer2_blockref_t **bresp);
98 * Basic RBTree for chains. Chains cannot overlap within any given
99 * core->rbtree without recursing through chain->rbtree. We effectively
100 * guarantee this by checking the full range rather than just the first
101 * key element. By matching on the full range callers can detect when
102 * recursrion through chain->rbtree is needed.
104 * NOTE: This also means the a delete-duplicate on the same key will
105 * overload by placing the deleted element in the new element's
106 * chain->rbtree (when doing a direct replacement).
108 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
111 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
113 hammer2_key_t c1_beg;
114 hammer2_key_t c1_end;
115 hammer2_key_t c2_beg;
116 hammer2_key_t c2_end;
118 c1_beg = chain1->bref.key;
119 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
120 c2_beg = chain2->bref.key;
121 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
123 if (c1_end < c2_beg) /* fully to the left */
125 if (c1_beg > c2_end) /* fully to the right */
127 return(0); /* overlap (must not cross edge boundary) */
132 hammer2_isclusterable(hammer2_chain_t *chain)
134 if (hammer2_cluster_enable) {
135 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
136 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
137 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
145 * Recursively set the update_tid flag up to the root starting at chain's
146 * parent->core. update_tid is not set in chain's core.
148 * This controls top-down visibility for flushes. The child has just one
149 * 'above' core, but the core itself can be multi-homed with parents iterated
152 * This function is not used during a flush (except when the flush is
153 * allocating which requires the live tree). The flush keeps track of its
156 * XXX needs to be optimized to use roll-up TIDs. update_tid is only really
157 * compared against bref.mirror_tid which itself is only updated by a flush.
160 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
162 hammer2_chain_core_t *above;
166 (HAMMER2_TRANS_ISFLUSH | HAMMER2_TRANS_ISALLOCATING)) ==
167 HAMMER2_TRANS_ISFLUSH) {
172 while ((above = chain->above) != NULL) {
173 spin_lock(&above->cst.spin);
175 if (above->update_tid < trans->sync_tid)
176 above->update_tid = trans->sync_tid;
177 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
179 TAILQ_FOREACH_REVERSE(chain, &above->ownerq,
180 h2_core_list, core_entry) {
181 if (trans->sync_tid >= chain->modify_tid &&
182 trans->sync_tid <= chain->delete_tid) {
187 spin_unlock(&above->cst.spin);
192 * Allocate a new disconnected chain element representing the specified
193 * bref. chain->refs is set to 1 and the passed bref is copied to
194 * chain->bref. chain->bytes is derived from the bref.
196 * chain->core is NOT allocated and the media data and bp pointers are left
197 * NULL. The caller must call chain_core_alloc() to allocate or associate
198 * a core with the chain.
200 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
203 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
204 hammer2_trans_t *trans, hammer2_blockref_t *bref)
206 hammer2_chain_t *chain;
207 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
210 * Construct the appropriate system structure.
213 case HAMMER2_BREF_TYPE_INODE:
214 case HAMMER2_BREF_TYPE_INDIRECT:
215 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
216 case HAMMER2_BREF_TYPE_DATA:
217 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
219 * Chain's are really only associated with the hmp but we
220 * maintain a pmp association for per-mount memory tracking
221 * purposes. The pmp can be NULL.
223 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
226 atomic_add_long(&pmp->inmem_chains, 1);
229 case HAMMER2_BREF_TYPE_VOLUME:
230 case HAMMER2_BREF_TYPE_FREEMAP:
232 panic("hammer2_chain_alloc volume type illegal for op");
235 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
241 chain->bytes = bytes;
243 chain->flags = HAMMER2_CHAIN_ALLOCATED;
244 chain->delete_tid = HAMMER2_MAX_TID;
247 * Set modify_tid if a transaction is creating the chain. When
248 * loading a chain from backing store trans is passed as NULL and
249 * modify_tid is left set to 0.
252 chain->modify_tid = trans->sync_tid;
258 * Associate an existing core with the chain or allocate a new core.
260 * The core is not locked. No additional refs on the chain are made.
261 * (trans) must not be NULL if (core) is not NULL.
263 * When chains are delete-duplicated during flushes we insert nchain on
264 * the ownerq after ochain instead of at the end in order to give the
265 * drop code visibility in the correct order, otherwise drops can be missed.
268 hammer2_chain_core_alloc(hammer2_trans_t *trans,
269 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
271 hammer2_chain_core_t *core;
273 KKASSERT(nchain->core == NULL);
275 if (ochain == NULL) {
277 * Fresh core under nchain (no multi-homing of ochain's
280 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
282 TAILQ_INIT(&core->layerq);
283 TAILQ_INIT(&core->ownerq);
287 core->update_tid = trans->sync_tid;
289 core->update_tid = nchain->bref.mirror_tid;
291 ccms_cst_init(&core->cst, nchain);
292 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
295 * Propagate the PFSROOT flag which we set on all subdirs
296 * under the super-root.
298 atomic_set_int(&nchain->flags,
299 ochain->flags & HAMMER2_CHAIN_PFSROOT);
302 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
303 * ochain if nchain is not a snapshot.
305 * It is possible for the DUPLICATED flag to already be
306 * set when called via a flush operation because flush
307 * operations may have to work on elements with delete_tid's
308 * beyond the flush sync_tid. In this situation we must
309 * ensure that nchain is placed just after ochain in the
310 * ownerq and that the DUPLICATED flag is set on nchain so
311 * 'live' operations skip past it to the correct chain.
313 * The flusher understands the blockref synchronization state
314 * for any stale chains by observing bref.mirror_tid, which
315 * delete-duplicate replicates.
317 * WARNING! However, the case is disallowed when the flusher
318 * is allocating freemap space because this entails
319 * more than just adjusting a block table.
321 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
322 KKASSERT((trans->flags &
323 (HAMMER2_TRANS_ISFLUSH |
324 HAMMER2_TRANS_ISALLOCATING)) ==
325 HAMMER2_TRANS_ISFLUSH);
326 atomic_set_int(&nchain->flags,
327 HAMMER2_CHAIN_DUPLICATED);
329 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
330 atomic_set_int(&ochain->flags,
331 HAMMER2_CHAIN_DUPLICATED);
334 atomic_add_int(&core->sharecnt, 1);
336 spin_lock(&core->cst.spin);
338 if (core->update_tid < trans->sync_tid)
339 core->update_tid = trans->sync_tid;
342 * Maintain ordering for refactor test so we don't skip over
343 * a snapshot. Also, during flushes, delete-duplications
344 * for block-table updates can occur on blocks already
345 * deleted (delete-duplicated by a later transaction). We
346 * must insert nchain after ochain but before the later
347 * transaction's copy.
349 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
351 spin_unlock(&core->cst.spin);
356 * Add a reference to a chain element, preventing its destruction.
359 hammer2_chain_ref(hammer2_chain_t *chain)
361 atomic_add_int(&chain->refs, 1);
365 * Insert the chain in the core rbtree at the first layer
366 * which accepts it (for now we don't sort layers by the transaction tid)
368 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
369 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
370 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
374 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_t *chain,
377 hammer2_chain_layer_t *layer;
378 hammer2_chain_t *xchain;
380 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
381 spin_lock(&above->cst.spin);
382 chain->above = above;
383 layer = TAILQ_FIRST(&above->layerq);
390 (xchain = RB_INSERT(hammer2_chain_tree,
391 &layer->rbtree, chain)) != NULL) {
393 * Either no layers have been allocated or the insertion
394 * failed. This is fatal if the conflicted xchain is not
395 * flagged as deleted. Caller may or may allow the failure.
397 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
398 xchain && (xchain->flags & HAMMER2_CHAIN_DELETED) == 0) {
400 chain->inlayer = NULL;
401 kprintf("insertion race against %p\n", xchain);
406 * Allocate a new layer to resolve the issue.
408 spin_unlock(&above->cst.spin);
409 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
411 RB_INIT(&layer->rbtree);
412 layer->good = 0xABCD;
413 spin_lock(&above->cst.spin);
414 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
415 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
417 chain->inlayer = layer;
418 ++above->chain_count;
421 if ((flags & HAMMER2_CHAIN_INSERT_LIVE) &&
422 (chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
423 atomic_add_int(&above->live_count, 1);
425 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
427 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
428 spin_unlock(&above->cst.spin);
432 * Drop the caller's reference to the chain. When the ref count drops to
433 * zero this function will disassociate the chain from its parent and
434 * deallocate it, then recursely drop the parent using the implied ref
435 * from the chain's chain->parent.
437 * WARNING! Just because we are able to deallocate a chain doesn't mean
438 * that chain->core->rbtree is empty. There can still be a sharecnt
439 * on chain->core and RBTREE entries that refer to different parents.
441 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
444 hammer2_chain_drop(hammer2_chain_t *chain)
449 if (chain->flags & HAMMER2_CHAIN_MOVED)
451 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
453 KKASSERT(chain->refs > need);
461 chain = hammer2_chain_lastdrop(chain);
463 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
465 /* retry the same chain */
471 * Safe handling of the 1->0 transition on chain. Returns a chain for
472 * recursive drop or NULL, possibly returning the same chain if the atomic
475 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
479 hammer2_chain_lastdrop(hammer2_chain_t *chain)
481 hammer2_pfsmount_t *pmp;
482 hammer2_mount_t *hmp;
483 hammer2_chain_core_t *above;
484 hammer2_chain_core_t *core;
485 hammer2_chain_layer_t *layer;
486 hammer2_chain_t *rdrop1;
487 hammer2_chain_t *rdrop2;
490 * Spinlock the core and check to see if it is empty. If it is
491 * not empty we leave chain intact with refs == 0. The elements
492 * in core->rbtree are associated with other chains contemporary
493 * with ours but not with our chain directly.
495 if ((core = chain->core) != NULL) {
496 spin_lock(&core->cst.spin);
499 * We can't drop any chains if they have children because
500 * there might be a flush dependency.
502 * NOTE: We return (chain) on failure to retry.
504 if (core->chain_count) {
505 if (atomic_cmpset_int(&chain->refs, 1, 0))
506 chain = NULL; /* success */
507 spin_unlock(&core->cst.spin);
510 /* no chains left under us */
513 * We can't drop a live chain unless it is a the head
514 * of its ownerq. If we were to then the go-to chain
515 * would revert to the prior deleted chain.
517 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
518 (chain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0 &&
519 TAILQ_FIRST(&core->ownerq) != chain) {
520 if (atomic_cmpset_int(&chain->refs, 1, 0))
521 chain = NULL; /* success */
522 spin_unlock(&core->cst.spin);
529 pmp = chain->pmp; /* can be NULL */
535 * Spinlock the parent and try to drop the last ref. On success
536 * remove chain from its parent, otherwise return NULL.
538 * (multiple spinlocks on core's are allowed in a bottom-up fashion).
540 if ((above = chain->above) != NULL) {
541 spin_lock(&above->cst.spin);
542 if (!atomic_cmpset_int(&chain->refs, 1, 0)) {
543 /* 1->0 transition failed */
544 spin_unlock(&above->cst.spin);
546 spin_unlock(&core->cst.spin);
547 return(chain); /* retry */
551 * 1->0 transition successful, remove chain from its
552 * above core. Track layer for removal/freeing.
554 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
555 layer = chain->inlayer;
556 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
557 --above->chain_count;
558 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
560 chain->inlayer = NULL;
562 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
563 TAILQ_REMOVE(&above->layerq, layer, entry);
570 * If our chain was the last chain in the parent's core the
571 * core is now empty. Try to drop the first multi-homed
574 if (above->chain_count == 0) {
575 rdrop1 = TAILQ_FIRST(&above->ownerq);
577 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
582 spin_unlock(&above->cst.spin);
583 above = NULL; /* safety */
587 * We still have the core spinlock (if core is non-NULL). The
588 * above spinlock is gone.
590 * Remove chain from ownerq. This may change the first element of
591 * ownerq to something we can remove.
596 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
597 rdrop2 = TAILQ_FIRST(&core->ownerq);
599 atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0) {
602 spin_unlock(&core->cst.spin);
605 * We can do the final 1->0 transition with an atomic op
606 * after releasing core's spinlock.
608 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
610 * On the 1->0 transition of core we can destroy
611 * it. Any remaining layers should no longer be
612 * referenced or visibile to other threads.
614 KKASSERT(TAILQ_EMPTY(&core->ownerq));
616 layer->good = 0xEF00;
617 kfree(layer, hmp->mchain);
619 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
620 KKASSERT(layer->refs == 0 &&
621 RB_EMPTY(&layer->rbtree));
622 TAILQ_REMOVE(&core->layerq, layer, entry);
623 layer->good = 0xEF01;
624 kfree(layer, hmp->mchain);
627 KKASSERT(core->cst.count == 0);
628 KKASSERT(core->cst.upgrade == 0);
630 kfree(core, hmp->mchain);
632 core = NULL; /* safety */
636 * All spin locks are gone, finish freeing stuff.
638 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
639 HAMMER2_CHAIN_MODIFIED)) == 0);
640 hammer2_chain_drop_data(chain, 1);
642 KKASSERT(chain->bp == NULL);
645 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
646 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
647 kfree(chain, hmp->mchain);
649 atomic_add_long(&pmp->inmem_chains, -1);
650 hammer2_chain_memory_wakeup(pmp);
655 * Free saved empty layer and return chained drop.
658 layer->good = 0xEF02;
659 kfree(layer, hmp->mchain);
662 hammer2_chain_drop(rdrop2);
667 * On either last lock release or last drop
670 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
672 hammer2_mount_t *hmp = chain->hmp;
674 switch(chain->bref.type) {
675 case HAMMER2_BREF_TYPE_VOLUME:
676 case HAMMER2_BREF_TYPE_FREEMAP:
680 case HAMMER2_BREF_TYPE_INODE:
682 kfree(chain->data, hmp->mchain);
686 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
688 kfree(chain->data, hmp->mchain);
693 KKASSERT(chain->data == NULL);
699 * Ref and lock a chain element, acquiring its data with I/O if necessary,
700 * and specify how you would like the data to be resolved.
702 * Returns 0 on success or an error code if the data could not be acquired.
703 * The chain element is locked on return regardless of whether an error
706 * The lock is allowed to recurse, multiple locking ops will aggregate
707 * the requested resolve types. Once data is assigned it will not be
708 * removed until the last unlock.
710 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
711 * (typically used to avoid device/logical buffer
714 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
715 * the INITIAL-create state (indirect blocks only).
717 * Do not resolve data elements for DATA chains.
718 * (typically used to avoid device/logical buffer
721 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
723 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
724 * it will be locked exclusive.
726 * NOTE: Embedded elements (volume header, inodes) are always resolved
729 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
730 * element will instantiate and zero its buffer, and flush it on
733 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
734 * so as not to instantiate a device buffer, which could alias against
735 * a logical file buffer. However, if ALWAYS is specified the
736 * device buffer will be instantiated anyway.
738 * WARNING! If data must be fetched a shared lock will temporarily be
739 * upgraded to exclusive. However, a deadlock can occur if
740 * the caller owns more than one shared lock.
743 hammer2_chain_lock(hammer2_chain_t *chain, int how)
745 hammer2_mount_t *hmp;
746 hammer2_chain_core_t *core;
747 hammer2_blockref_t *bref;
758 * Ref and lock the element. Recursive locks are allowed.
760 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
761 hammer2_chain_ref(chain);
762 atomic_add_int(&chain->lockcnt, 1);
765 KKASSERT(hmp != NULL);
768 * Get the appropriate lock.
771 if (how & HAMMER2_RESOLVE_SHARED)
772 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
774 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
777 * If we already have a valid data pointer no further action is
784 * Do we have to resolve the data?
786 switch(how & HAMMER2_RESOLVE_MASK) {
787 case HAMMER2_RESOLVE_NEVER:
789 case HAMMER2_RESOLVE_MAYBE:
790 if (chain->flags & HAMMER2_CHAIN_INITIAL)
792 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
795 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
798 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
801 case HAMMER2_RESOLVE_ALWAYS:
806 * Upgrade to an exclusive lock so we can safely manipulate the
807 * buffer cache. If another thread got to it before us we
810 ostate = ccms_thread_lock_upgrade(&core->cst);
812 ccms_thread_lock_downgrade(&core->cst, ostate);
817 * We must resolve to a device buffer, either by issuing I/O or
818 * by creating a zero-fill element. We do not mark the buffer
819 * dirty when creating a zero-fill element (the hammer2_chain_modify()
820 * API must still be used to do that).
822 * The device buffer is variable-sized in powers of 2 down
823 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
824 * chunk always contains buffers of the same size. (XXX)
826 * The minimum physical IO size may be larger than the variable
831 psize = hammer2_devblksize(chain->bytes);
832 pmask = (hammer2_off_t)psize - 1;
833 pbase = bref->data_off & ~pmask;
834 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
835 KKASSERT(pbase != 0);
836 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
839 * The getblk() optimization can only be used on newly created
840 * elements if the physical block size matches the request.
842 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
843 chain->bytes == psize) {
844 chain->bp = getblk(hmp->devvp, pbase, psize, 0, 0);
846 } else if (hammer2_isclusterable(chain)) {
847 error = cluster_read(hmp->devvp, peof, pbase, psize,
848 psize, HAMMER2_PBUFSIZE*4,
850 adjreadcounter(&chain->bref, chain->bytes);
852 error = bread(hmp->devvp, pbase, psize, &chain->bp);
853 adjreadcounter(&chain->bref, chain->bytes);
857 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
858 (intmax_t)pbase, error);
861 ccms_thread_lock_downgrade(&core->cst, ostate);
866 * Zero the data area if the chain is in the INITIAL-create state.
867 * Mark the buffer for bdwrite(). This clears the INITIAL state
868 * but does not mark the chain modified.
870 bdata = (char *)chain->bp->b_data + boff;
871 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
872 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
873 bzero(bdata, chain->bytes);
874 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
878 * Setup the data pointer, either pointing it to an embedded data
879 * structure and copying the data from the buffer, or pointing it
882 * The buffer is not retained when copying to an embedded data
883 * structure in order to avoid potential deadlocks or recursions
884 * on the same physical buffer.
886 switch (bref->type) {
887 case HAMMER2_BREF_TYPE_VOLUME:
888 case HAMMER2_BREF_TYPE_FREEMAP:
890 * Copy data from bp to embedded buffer
892 panic("hammer2_chain_lock: called on unresolved volume header");
895 KKASSERT(pbase == 0);
896 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
897 bcopy(bdata, &hmp->voldata, chain->bytes);
898 chain->data = (void *)&hmp->voldata;
903 case HAMMER2_BREF_TYPE_INODE:
905 * Copy data from bp to embedded buffer, do not retain the
908 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
909 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
910 chain->data = kmalloc(sizeof(chain->data->ipdata),
911 hmp->mchain, M_WAITOK | M_ZERO);
912 bcopy(bdata, &chain->data->ipdata, chain->bytes);
916 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
917 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
918 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
919 chain->data = kmalloc(sizeof(chain->data->bmdata),
920 hmp->mchain, M_WAITOK | M_ZERO);
921 bcopy(bdata, &chain->data->bmdata, chain->bytes);
925 case HAMMER2_BREF_TYPE_INDIRECT:
926 case HAMMER2_BREF_TYPE_DATA:
927 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
930 * Point data at the device buffer and leave bp intact.
932 chain->data = (void *)bdata;
937 * Make sure the bp is not specifically owned by this thread before
938 * restoring to a possibly shared lock, so another hammer2 thread
942 BUF_KERNPROC(chain->bp);
943 ccms_thread_lock_downgrade(&core->cst, ostate);
948 * Asynchronously read the device buffer (dbp) and execute the specified
949 * callback. The caller should pass-in a locked chain (shared lock is ok).
950 * The function is responsible for unlocking the chain and for disposing
953 * NOTE! A NULL dbp (but non-NULL data) will be passed to the function
954 * if the dbp is integrated into the chain, because we do not want
955 * the caller to dispose of dbp in that situation.
957 static void hammer2_chain_load_async_callback(struct bio *bio);
960 hammer2_chain_load_async(hammer2_chain_t *chain,
961 void (*func)(hammer2_chain_t *, struct buf *, char *, void *),
964 hammer2_cbinfo_t *cbinfo;
965 hammer2_mount_t *hmp;
966 hammer2_blockref_t *bref;
976 func(chain, NULL, (char *)chain->data, arg);
981 * We must resolve to a device buffer, either by issuing I/O or
982 * by creating a zero-fill element. We do not mark the buffer
983 * dirty when creating a zero-fill element (the hammer2_chain_modify()
984 * API must still be used to do that).
986 * The device buffer is variable-sized in powers of 2 down
987 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
988 * chunk always contains buffers of the same size. (XXX)
990 * The minimum physical IO size may be larger than the variable
995 psize = hammer2_devblksize(chain->bytes);
996 pmask = (hammer2_off_t)psize - 1;
997 pbase = bref->data_off & ~pmask;
998 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
999 KKASSERT(pbase != 0);
1000 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1005 * The getblk() optimization can only be used on newly created
1006 * elements if the physical block size matches the request.
1008 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1009 chain->bytes == psize) {
1010 dbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1011 /*atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);*/
1012 bdata = (char *)dbp->b_data + boff;
1013 bzero(bdata, chain->bytes);
1014 /*atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);*/
1015 func(chain, dbp, bdata, arg);
1020 adjreadcounter(&chain->bref, chain->bytes);
1021 cbinfo = kmalloc(sizeof(*cbinfo), hmp->mchain, M_INTWAIT | M_ZERO);
1022 cbinfo->chain = chain;
1023 cbinfo->func = func;
1025 cbinfo->boff = boff;
1027 cluster_readcb(hmp->devvp, peof, pbase, psize,
1028 HAMMER2_PBUFSIZE*4, HAMMER2_PBUFSIZE*4,
1029 hammer2_chain_load_async_callback, cbinfo);
1033 hammer2_chain_load_async_callback(struct bio *bio)
1035 hammer2_cbinfo_t *cbinfo;
1036 hammer2_mount_t *hmp;
1041 * Nobody is waiting for bio/dbp to complete, we are
1042 * responsible for handling the biowait() equivalent
1043 * on dbp which means clearing BIO_DONE and BIO_SYNC
1044 * and calling bpdone() if it hasn't already been called
1045 * to restore any covered holes in the buffer's backing
1049 if ((bio->bio_flags & BIO_DONE) == 0)
1051 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
1054 * Extract the auxillary info and issue the callback.
1055 * Finish up with the dbp after it returns.
1057 cbinfo = bio->bio_caller_info1.ptr;
1058 /*ccms_thread_lock_setown(cbinfo->chain->core);*/
1059 data = dbp->b_data + cbinfo->boff;
1060 hmp = cbinfo->chain->hmp;
1062 cbinfo = bio->bio_caller_info1.ptr;
1063 if (cbinfo->chain->flags & HAMMER2_CHAIN_INITIAL)
1064 bzero(data, cbinfo->chain->bytes);
1065 cbinfo->func(cbinfo->chain, dbp, data, cbinfo->arg);
1066 /* cbinfo->chain is stale now */
1068 kfree(cbinfo, hmp->mchain);
1072 * Unlock and deref a chain element.
1074 * On the last lock release any non-embedded data (chain->bp) will be
1078 hammer2_chain_unlock(hammer2_chain_t *chain)
1080 hammer2_chain_core_t *core = chain->core;
1081 ccms_state_t ostate;
1086 * The core->cst lock can be shared across several chains so we
1087 * need to track the per-chain lockcnt separately.
1089 * If multiple locks are present (or being attempted) on this
1090 * particular chain we can just unlock, drop refs, and return.
1092 * Otherwise fall-through on the 1->0 transition.
1095 lockcnt = chain->lockcnt;
1096 KKASSERT(lockcnt > 0);
1099 if (atomic_cmpset_int(&chain->lockcnt,
1100 lockcnt, lockcnt - 1)) {
1101 ccms_thread_unlock(&core->cst);
1102 hammer2_chain_drop(chain);
1106 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1113 * On the 1->0 transition we upgrade the core lock (if necessary)
1114 * to exclusive for terminal processing. If after upgrading we find
1115 * that lockcnt is non-zero, another thread is racing us and will
1116 * handle the unload for us later on, so just cleanup and return
1117 * leaving the data/bp intact
1119 * Otherwise if lockcnt is still 0 it is possible for it to become
1120 * non-zero and race, but since we hold the core->cst lock
1121 * exclusively all that will happen is that the chain will be
1122 * reloaded after we unload it.
1124 ostate = ccms_thread_lock_upgrade(&core->cst);
1125 if (chain->lockcnt) {
1126 ccms_thread_unlock_upgraded(&core->cst, ostate);
1127 hammer2_chain_drop(chain);
1132 * Shortcut the case if the data is embedded or not resolved.
1134 * Do NOT NULL out chain->data (e.g. inode data), it might be
1137 * The DIRTYBP flag is non-applicable in this situation and can
1138 * be cleared to keep the flags state clean.
1140 if (chain->bp == NULL) {
1141 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1142 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1143 hammer2_chain_drop_data(chain, 0);
1144 ccms_thread_unlock_upgraded(&core->cst, ostate);
1145 hammer2_chain_drop(chain);
1152 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
1154 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1155 switch(chain->bref.type) {
1156 case HAMMER2_BREF_TYPE_DATA:
1157 counterp = &hammer2_ioa_file_write;
1159 case HAMMER2_BREF_TYPE_INODE:
1160 counterp = &hammer2_ioa_meta_write;
1162 case HAMMER2_BREF_TYPE_INDIRECT:
1163 counterp = &hammer2_ioa_indr_write;
1165 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1166 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1167 counterp = &hammer2_ioa_fmap_write;
1170 counterp = &hammer2_ioa_volu_write;
1173 *counterp += chain->bytes;
1175 switch(chain->bref.type) {
1176 case HAMMER2_BREF_TYPE_DATA:
1177 counterp = &hammer2_iod_file_write;
1179 case HAMMER2_BREF_TYPE_INODE:
1180 counterp = &hammer2_iod_meta_write;
1182 case HAMMER2_BREF_TYPE_INDIRECT:
1183 counterp = &hammer2_iod_indr_write;
1185 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1186 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1187 counterp = &hammer2_iod_fmap_write;
1190 counterp = &hammer2_iod_volu_write;
1193 *counterp += chain->bytes;
1199 * If a device buffer was used for data be sure to destroy the
1200 * buffer when we are done to avoid aliases (XXX what about the
1201 * underlying VM pages?).
1203 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1208 * XXX our primary cache is now the block device, not
1209 * the logical file. don't release the buffer.
1211 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1212 chain->bp->b_flags |= B_RELBUF;
1216 * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
1217 * or not. The flag will get re-set when chain_modify() is called,
1218 * even if MODIFIED is already set, allowing the OS to retire the
1219 * buffer independent of a hammer2 flus.
1222 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1223 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1224 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1225 atomic_clear_int(&chain->flags,
1226 HAMMER2_CHAIN_IOFLUSH);
1227 chain->bp->b_flags |= B_RELBUF;
1228 cluster_awrite(chain->bp);
1230 chain->bp->b_flags |= B_CLUSTEROK;
1234 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1235 atomic_clear_int(&chain->flags,
1236 HAMMER2_CHAIN_IOFLUSH);
1237 chain->bp->b_flags |= B_RELBUF;
1240 /* bp might still be dirty */
1245 ccms_thread_unlock_upgraded(&core->cst, ostate);
1246 hammer2_chain_drop(chain);
1250 * This counts the number of live blockrefs in a block array and
1251 * also calculates the point at which all remaining blockrefs are empty.
1253 * NOTE: Flag is not set until after the count is complete, allowing
1254 * callers to test the flag without holding the spinlock.
1256 * NOTE: If base is NULL the related chain is still in the INITIAL
1257 * state and there are no blockrefs to count.
1259 * NOTE: live_count may already have some counts accumulated due to
1260 * creation and deletion and could even be initially negative.
1263 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1264 hammer2_blockref_t *base, int count)
1266 hammer2_chain_core_t *core = chain->core;
1268 spin_lock(&core->cst.spin);
1269 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1271 while (--count >= 0) {
1272 if (base[count].type)
1275 core->live_zero = count + 1;
1276 while (count >= 0) {
1277 if (base[count].type)
1278 atomic_add_int(&core->live_count, 1);
1282 core->live_zero = 0;
1284 /* else do not modify live_count */
1285 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1287 spin_unlock(&core->cst.spin);
1291 * Resize the chain's physical storage allocation in-place. This may
1292 * replace the passed-in chain with a new chain.
1294 * Chains can be resized smaller without reallocating the storage.
1295 * Resizing larger will reallocate the storage.
1297 * Must be passed an exclusively locked parent and chain, returns a new
1298 * exclusively locked chain at the same index and unlocks the old chain.
1299 * Flushes the buffer if necessary.
1301 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1302 * to avoid instantiating a device buffer that conflicts with the vnode
1303 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1304 * any chain-oriented bp would be a device buffer.
1306 * XXX flags currently ignored, uses chain->bp to detect data/no-data.
1307 * XXX return error if cannot resize.
1310 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1311 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1312 int nradix, int flags)
1314 hammer2_mount_t *hmp;
1315 hammer2_chain_t *chain;
1316 hammer2_off_t pbase;
1326 * Only data and indirect blocks can be resized for now.
1327 * (The volu root, inodes, and freemap elements use a fixed size).
1329 KKASSERT(chain != &hmp->vchain);
1330 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1331 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1334 * Nothing to do if the element is already the proper size
1336 obytes = chain->bytes;
1337 nbytes = 1U << nradix;
1338 if (obytes == nbytes)
1342 * Delete the old chain and duplicate it at the same (parent, index),
1343 * returning a new chain. This allows the old chain to still be
1344 * used by the flush code. The new chain will be returned in a
1347 * The parent does not have to be locked for the delete/duplicate call,
1348 * but is in this particular code path.
1350 * NOTE: If we are not crossing a synchronization point the
1351 * duplication code will simply reuse the existing chain
1354 hammer2_chain_delete_duplicate(trans, &chain, 0);
1357 * Relocate the block, even if making it smaller (because different
1358 * block sizes may be in different regions).
1360 hammer2_freemap_alloc(trans, chain->hmp, &chain->bref, nbytes);
1361 chain->bytes = nbytes;
1362 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1363 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1366 * The device buffer may be larger than the allocation size.
1368 bbytes = hammer2_devblksize(chain->bytes);
1369 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1370 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1373 * For now just support it on DATA chains (and not on indirect
1376 KKASSERT(chain->bp == NULL);
1380 * Make sure the chain is marked MOVED and propagate the update
1381 * to the root for flush.
1383 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1384 hammer2_chain_ref(chain);
1385 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1387 hammer2_chain_setsubmod(trans, chain);
1393 * Set a chain modified, making it read-write and duplicating it if necessary.
1394 * This function will assign a new physical block to the chain if necessary
1396 * Duplication of already-modified chains is possible when the modification
1397 * crosses a flush synchronization boundary.
1399 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1400 * level or the COW operation will not work.
1402 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1403 * run the data through the device buffers.
1405 * This function may return a different chain than was passed, in which case
1406 * the old chain will be unlocked and the new chain will be locked.
1408 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1410 hammer2_inode_data_t *
1411 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1412 hammer2_chain_t **chainp, int flags)
1414 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1415 hammer2_chain_modify(trans, chainp, flags);
1416 if (ip->chain != *chainp)
1417 hammer2_inode_repoint(ip, NULL, *chainp);
1419 vsetisdirty(ip->vp);
1420 return(&ip->chain->data->ipdata);
1424 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1427 hammer2_mount_t *hmp;
1428 hammer2_chain_t *chain;
1429 hammer2_off_t pbase;
1430 hammer2_off_t pmask;
1443 kprintf("MODIFY %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1446 * Data must be resolved if already assigned unless explicitly
1447 * flagged otherwise.
1449 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1450 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1451 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1452 hammer2_chain_unlock(chain);
1456 * data is not optional for freemap chains (we must always be sure
1457 * to copy the data on COW storage allocations).
1459 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1460 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1461 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1462 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1466 * Determine if a delete-duplicate is needed.
1468 * (a) Modify_tid is part of a prior flush
1469 * (b) Transaction is concurrent with a flush (has higher tid)
1470 * (c) and chain is not in the initial state (freshly created)
1471 * (d) and caller didn't request an in-place modification.
1473 * The freemap and volume header special chains are never D-Dd.
1475 if (chain->modify_tid != trans->sync_tid && /* cross boundary */
1476 (flags & HAMMER2_MODIFY_INPLACE) == 0) { /* from d-d */
1477 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1478 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1479 hammer2_chain_delete_duplicate(trans, chainp, 0);
1481 kprintf("RET1A %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1485 kprintf("RET1B %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1489 /* fall through if fchain or vchain */
1493 * Otherwise do initial-chain handling
1495 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1496 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1497 hammer2_chain_ref(chain);
1501 * The modification or re-modification requires an allocation and
1504 * We normally always allocate new storage here. If storage exists
1505 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1507 if (chain != &hmp->vchain && chain != &hmp->fchain) {
1508 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1509 ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1510 chain->modify_tid != trans->sync_tid)
1512 hammer2_freemap_alloc(trans, chain->hmp,
1513 &chain->bref, chain->bytes);
1514 /* XXX failed allocation */
1515 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1516 hammer2_freemap_alloc(trans, chain->hmp,
1517 &chain->bref, chain->bytes);
1518 /* XXX failed allocation */
1520 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1523 chain->modify_tid = trans->sync_tid;
1524 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1525 chain->bref.modify_tid = trans->sync_tid;
1528 * Do not COW if OPTDATA is set. INITIAL flag remains unchanged.
1529 * (OPTDATA does not prevent [re]allocation of storage, only the
1530 * related copy-on-write op).
1532 if (flags & HAMMER2_MODIFY_OPTDATA)
1536 * Clearing the INITIAL flag (for indirect blocks) indicates that
1537 * we've processed the uninitialized storage allocation.
1539 * If this flag is already clear we are likely in a copy-on-write
1540 * situation but we have to be sure NOT to bzero the storage if
1541 * no data is present.
1543 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1544 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1551 * Instantiate data buffer and possibly execute COW operation
1553 switch(chain->bref.type) {
1554 case HAMMER2_BREF_TYPE_VOLUME:
1555 case HAMMER2_BREF_TYPE_FREEMAP:
1556 case HAMMER2_BREF_TYPE_INODE:
1557 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1559 * The data is embedded, no copy-on-write operation is
1562 KKASSERT(chain->bp == NULL);
1564 case HAMMER2_BREF_TYPE_DATA:
1565 case HAMMER2_BREF_TYPE_INDIRECT:
1566 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1568 * Perform the copy-on-write operation
1570 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1572 psize = hammer2_devblksize(chain->bytes);
1573 pmask = (hammer2_off_t)psize - 1;
1574 pbase = chain->bref.data_off & ~pmask;
1575 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1576 KKASSERT(pbase != 0);
1577 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1580 * The getblk() optimization can only be used if the
1581 * chain element size matches the physical block size.
1583 if (chain->bp && chain->bp->b_loffset == pbase) {
1586 } else if (chain->bytes == psize) {
1587 nbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1589 } else if (hammer2_isclusterable(chain)) {
1590 error = cluster_read(hmp->devvp, peof, pbase, psize,
1591 psize, HAMMER2_PBUFSIZE*4,
1593 adjreadcounter(&chain->bref, chain->bytes);
1595 error = bread(hmp->devvp, pbase, psize, &nbp);
1596 adjreadcounter(&chain->bref, chain->bytes);
1598 KKASSERT(error == 0);
1599 bdata = (char *)nbp->b_data + boff;
1602 * Copy or zero-fill on write depending on whether
1603 * chain->data exists or not. Retire the existing bp
1604 * based on the DIRTYBP flag. Set the DIRTYBP flag to
1605 * indicate that retirement of nbp should use bdwrite().
1608 KKASSERT(chain->bp != NULL);
1609 if (chain->data != bdata) {
1610 bcopy(chain->data, bdata, chain->bytes);
1612 } else if (wasinitial) {
1613 bzero(bdata, chain->bytes);
1616 * We have a problem. We were asked to COW but
1617 * we don't have any data to COW with!
1619 panic("hammer2_chain_modify: having a COW %p\n",
1622 if (chain->bp != nbp) {
1624 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1625 chain->bp->b_flags |= B_CLUSTEROK;
1628 chain->bp->b_flags |= B_RELBUF;
1633 BUF_KERNPROC(chain->bp);
1635 chain->data = bdata;
1636 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1639 panic("hammer2_chain_modify: illegal non-embedded type %d",
1646 kprintf("RET2 %p.%d flags %08x mod=%016jx del=%016jx\n", chain, chain->bref.type, chain->flags, chain->modify_tid, chain->delete_tid);
1648 hammer2_chain_setsubmod(trans, chain);
1652 * Mark the volume as having been modified. This short-cut version
1653 * does not have to lock the volume's chain, which allows the ioctl
1654 * code to make adjustments to connections without deadlocking. XXX
1656 * No ref is made on vchain when flagging it MODIFIED.
1659 hammer2_modify_volume(hammer2_mount_t *hmp)
1661 hammer2_voldata_lock(hmp);
1662 hammer2_voldata_unlock(hmp, 1);
1666 * This function returns the chain at the nearest key within the specified
1667 * range with the highest delete_tid. The core spinlock must be held on
1668 * call and the returned chain will be referenced but not locked.
1670 * The returned chain may or may not be in a deleted state. Note that
1671 * live chains have a delete_tid = MAX_TID.
1673 * This function will recurse through chain->rbtree as necessary and will
1674 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1675 * the iteration value is less than the current value of *key_nextp.
1677 * The caller should use (*key_nextp) to calculate the actual range of
1678 * the returned element, which will be (key_beg to *key_nextp - 1), because
1679 * there might be another element which is superior to the returned element
1682 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1683 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1684 * it will wind up being (key_end + 1).
1686 struct hammer2_chain_find_info {
1687 hammer2_chain_t *best;
1688 hammer2_key_t key_beg;
1689 hammer2_key_t key_end;
1690 hammer2_key_t key_next;
1693 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1694 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1698 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1699 hammer2_key_t key_beg, hammer2_key_t key_end)
1701 struct hammer2_chain_find_info info;
1702 hammer2_chain_layer_t *layer;
1705 info.key_beg = key_beg;
1706 info.key_end = key_end;
1707 info.key_next = *key_nextp;
1709 KKASSERT(parent->core->good == 0x1234);
1710 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1711 KKASSERT(layer->good == 0xABCD);
1712 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1713 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1716 *key_nextp = info.key_next;
1718 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1719 parent, key_beg, key_end, *key_nextp);
1727 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1729 struct hammer2_chain_find_info *info = data;
1730 hammer2_key_t child_beg;
1731 hammer2_key_t child_end;
1733 child_beg = child->bref.key;
1734 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1736 if (child_end < info->key_beg)
1738 if (child_beg > info->key_end)
1745 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1747 struct hammer2_chain_find_info *info = data;
1748 hammer2_chain_t *best;
1749 hammer2_key_t child_end;
1753 * Skip deleted chains which have been flushed (MOVED no longer set),
1754 * causes caller to check blockref array.
1756 if ((child->flags & (HAMMER2_CHAIN_DELETED | HAMMER2_CHAIN_MOVED)) ==
1757 HAMMER2_CHAIN_DELETED) {
1766 if ((best = info->best) == NULL) {
1768 * No previous best. Assign best
1771 } else if (best->bref.key <= info->key_beg &&
1772 child->bref.key <= info->key_beg) {
1774 * If our current best is flush with key_beg and child is
1775 * also flush with key_beg choose based on delete_tid.
1777 * key_next will automatically be limited to the smaller of
1778 * the two end-points.
1780 if (child->delete_tid > best->delete_tid)
1782 } else if (child->bref.key < best->bref.key) {
1784 * Child has a nearer key and best is not flush with key_beg.
1785 * Truncate key_next to the old best key iff it had a better
1789 if (best->delete_tid >= child->delete_tid &&
1790 (info->key_next > best->bref.key || info->key_next == 0))
1791 info->key_next = best->bref.key;
1792 } else if (child->bref.key == best->bref.key) {
1794 * If our current best is flush with the child then choose
1795 * based on delete_tid.
1797 * key_next will automatically be limited to the smaller of
1798 * the two end-points.
1800 if (child->delete_tid > best->delete_tid)
1804 * Keep the current best but truncate key_next to the child's
1805 * base iff the child has a higher delete_tid.
1807 * key_next will also automatically be limited to the smaller
1808 * of the two end-points (probably not necessary for this case
1809 * but we do it anyway).
1811 if (child->delete_tid >= best->delete_tid &&
1812 (info->key_next > child->bref.key || info->key_next == 0))
1813 info->key_next = child->bref.key;
1817 * Always truncate key_next based on child's end-of-range.
1819 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1820 if (child_end && (info->key_next > child_end || info->key_next == 0))
1821 info->key_next = child_end;
1827 * Retrieve the specified chain from a media blockref, creating the
1828 * in-memory chain structure which reflects it. modify_tid will be
1829 * left 0 which forces any modifications to issue a delete-duplicate.
1831 * NULL is returned if the insertion races.
1833 * Caller must hold the parent locked shared or exclusive since we may
1834 * need the parent's bref array to find our block.
1837 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref)
1839 hammer2_mount_t *hmp = parent->hmp;
1840 hammer2_chain_core_t *above = parent->core;
1841 hammer2_chain_t *chain;
1844 * Allocate a chain structure representing the existing media
1845 * entry. Resulting chain has one ref and is not locked.
1847 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1848 hammer2_chain_core_alloc(NULL, chain, NULL);
1849 /* ref'd chain returned */
1850 chain->modify_tid = chain->bref.mirror_tid;
1853 * Link the chain into its parent. A spinlock is required to safely
1854 * access the RBTREE, and it is possible to collide with another
1855 * hammer2_chain_get() operation because the caller might only hold
1856 * a shared lock on the parent.
1858 KKASSERT(parent->refs > 0);
1859 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
1860 HAMMER2_CHAIN_INSERT_RACE);
1861 if ((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0) {
1862 kprintf("chain %p not on RBTREE\n", chain);
1863 hammer2_chain_drop(chain);
1868 * Return our new chain referenced but not locked.
1874 * Lookup initialization/completion API
1877 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1879 if (flags & HAMMER2_LOOKUP_SHARED) {
1880 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1881 HAMMER2_RESOLVE_SHARED);
1883 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1889 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1892 hammer2_chain_unlock(parent);
1897 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1899 hammer2_chain_t *oparent;
1900 hammer2_chain_t *bparent;
1901 hammer2_chain_t *nparent;
1902 hammer2_chain_core_t *above;
1905 above = oparent->above;
1907 spin_lock(&above->cst.spin);
1908 bparent = TAILQ_FIRST(&above->ownerq);
1909 hammer2_chain_ref(bparent);
1913 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1914 nparent = TAILQ_NEXT(nparent, core_entry);
1915 hammer2_chain_ref(nparent);
1916 spin_unlock(&above->cst.spin);
1919 * Be careful of order
1921 hammer2_chain_unlock(oparent);
1922 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1923 hammer2_chain_drop(bparent);
1926 * We might have raced a delete-duplicate.
1928 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1929 spin_lock(&above->cst.spin);
1930 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1931 spin_unlock(&above->cst.spin);
1932 hammer2_chain_ref(nparent);
1933 hammer2_chain_unlock(nparent);
1935 spin_lock(&above->cst.spin);
1936 continue; /* retry */
1938 spin_unlock(&above->cst.spin);
1948 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1949 * (*parentp) typically points to an inode but can also point to a related
1950 * indirect block and this function will recurse upwards and find the inode
1953 * (*parentp) must be exclusively locked and referenced and can be an inode
1954 * or an existing indirect block within the inode.
1956 * On return (*parentp) will be modified to point at the deepest parent chain
1957 * element encountered during the search, as a helper for an insertion or
1958 * deletion. The new (*parentp) will be locked and referenced and the old
1959 * will be unlocked and dereferenced (no change if they are both the same).
1961 * The matching chain will be returned exclusively locked. If NOLOCK is
1962 * requested the chain will be returned only referenced.
1964 * NULL is returned if no match was found, but (*parentp) will still
1965 * potentially be adjusted.
1967 * On return (*key_nextp) will point to an iterative value for key_beg.
1968 * (If NULL is returned (*key_nextp) is set to key_end).
1970 * This function will also recurse up the chain if the key is not within the
1971 * current parent's range. (*parentp) can never be set to NULL. An iteration
1972 * can simply allow (*parentp) to float inside the loop.
1974 * NOTE! chain->data is not always resolved. By default it will not be
1975 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1976 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1977 * BREF_TYPE_DATA as the device buffer can alias the logical file
1981 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1982 hammer2_key_t key_beg, hammer2_key_t key_end,
1983 int *cache_indexp, int flags)
1985 hammer2_mount_t *hmp;
1986 hammer2_chain_t *parent;
1987 hammer2_chain_t *chain;
1988 hammer2_blockref_t *base;
1989 hammer2_blockref_t *bref;
1990 hammer2_blockref_t bcopy;
1991 hammer2_key_t scan_beg;
1992 hammer2_key_t scan_end;
1993 hammer2_chain_core_t *above;
1995 int how_always = HAMMER2_RESOLVE_ALWAYS;
1996 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1999 if (flags & HAMMER2_LOOKUP_ALWAYS) {
2000 how_maybe = how_always;
2001 how = HAMMER2_RESOLVE_ALWAYS;
2002 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2003 how = HAMMER2_RESOLVE_NEVER;
2005 how = HAMMER2_RESOLVE_MAYBE;
2007 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2008 how_maybe |= HAMMER2_RESOLVE_SHARED;
2009 how_always |= HAMMER2_RESOLVE_SHARED;
2010 how |= HAMMER2_RESOLVE_SHARED;
2014 * Recurse (*parentp) upward if necessary until the parent completely
2015 * encloses the key range or we hit the inode.
2017 * This function handles races against the flusher doing a delete-
2018 * duplicate above us and re-homes the parent to the duplicate in
2019 * that case, otherwise we'd wind up recursing down a stale chain.
2024 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2025 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2026 scan_beg = parent->bref.key;
2027 scan_end = scan_beg +
2028 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2029 if (key_beg >= scan_beg && key_end <= scan_end)
2031 parent = hammer2_chain_getparent(parentp, how_maybe);
2036 * Locate the blockref array. Currently we do a fully associative
2037 * search through the array.
2039 switch(parent->bref.type) {
2040 case HAMMER2_BREF_TYPE_INODE:
2042 * Special shortcut for embedded data returns the inode
2043 * itself. Callers must detect this condition and access
2044 * the embedded data (the strategy code does this for us).
2046 * This is only applicable to regular files and softlinks.
2048 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
2049 if (flags & HAMMER2_LOOKUP_NOLOCK)
2050 hammer2_chain_ref(parent);
2052 hammer2_chain_lock(parent, how_always);
2053 *key_nextp = key_end + 1;
2056 base = &parent->data->ipdata.u.blockset.blockref[0];
2057 count = HAMMER2_SET_COUNT;
2059 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2060 case HAMMER2_BREF_TYPE_INDIRECT:
2062 * Handle MATCHIND on the parent
2064 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2065 scan_beg = parent->bref.key;
2066 scan_end = scan_beg +
2067 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2068 if (key_beg == scan_beg && key_end == scan_end) {
2070 hammer2_chain_lock(chain, how_maybe);
2071 *key_nextp = scan_end + 1;
2076 * Optimize indirect blocks in the INITIAL state to avoid
2079 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2082 if (parent->data == NULL)
2083 panic("parent->data is NULL");
2084 base = &parent->data->npdata[0];
2086 count = parent->bytes / sizeof(hammer2_blockref_t);
2088 case HAMMER2_BREF_TYPE_VOLUME:
2089 base = &hmp->voldata.sroot_blockset.blockref[0];
2090 count = HAMMER2_SET_COUNT;
2092 case HAMMER2_BREF_TYPE_FREEMAP:
2093 base = &hmp->voldata.freemap_blockset.blockref[0];
2094 count = HAMMER2_SET_COUNT;
2097 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2099 base = NULL; /* safety */
2100 count = 0; /* safety */
2104 * Merged scan to find next candidate.
2106 * hammer2_base_*() functions require the above->live_* fields
2107 * to be synchronized.
2109 * We need to hold the spinlock to access the block array and RB tree
2110 * and to interlock chain creation.
2112 above = parent->core;
2113 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2114 hammer2_chain_countbrefs(parent, base, count);
2119 spin_lock(&above->cst.spin);
2120 chain = hammer2_combined_find(parent, base, count,
2121 cache_indexp, key_nextp,
2122 key_beg, key_end, &bref);
2125 * Exhausted parent chain, iterate.
2128 spin_unlock(&above->cst.spin);
2129 if (key_beg == key_end) /* short cut single-key case */
2131 return (hammer2_chain_next(parentp, NULL, key_nextp,
2133 cache_indexp, flags));
2137 * Selected from blockref or in-memory chain.
2139 if (chain == NULL) {
2141 spin_unlock(&above->cst.spin);
2142 chain = hammer2_chain_get(parent, &bcopy);
2143 if (chain == NULL) {
2144 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2145 parent, key_beg, key_end);
2148 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2149 hammer2_chain_drop(chain);
2153 hammer2_chain_ref(chain);
2154 spin_unlock(&above->cst.spin);
2156 /* chain is referenced but not locked */
2159 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2161 * NOTE: chain's key range is not relevant as there might be
2162 * one-offs within the range that are not deleted.
2164 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2165 hammer2_chain_drop(chain);
2166 key_beg = *key_nextp;
2167 if (key_beg == 0 || key_beg > key_end)
2173 * If the chain element is an indirect block it becomes the new
2174 * parent and we loop on it. We must maintain our top-down locks
2175 * to prevent the flusher from interfering (i.e. doing a
2176 * delete-duplicate and leaving us recursing down a deleted chain).
2178 * The parent always has to be locked with at least RESOLVE_MAYBE
2179 * so we can access its data. It might need a fixup if the caller
2180 * passed incompatible flags. Be careful not to cause a deadlock
2181 * as a data-load requires an exclusive lock.
2183 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2184 * range is within the requested key range we return the indirect
2185 * block and do NOT loop. This is usually only used to acquire
2188 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2189 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2190 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2191 hammer2_chain_unlock(parent);
2192 *parentp = parent = chain;
2196 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2199 * All done, return the chain
2205 * After having issued a lookup we can iterate all matching keys.
2207 * If chain is non-NULL we continue the iteration from just after it's index.
2209 * If chain is NULL we assume the parent was exhausted and continue the
2210 * iteration at the next parent.
2212 * parent must be locked on entry and remains locked throughout. chain's
2213 * lock status must match flags. Chain is always at least referenced.
2215 * WARNING! The MATCHIND flag does not apply to this function.
2218 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2219 hammer2_key_t *key_nextp,
2220 hammer2_key_t key_beg, hammer2_key_t key_end,
2221 int *cache_indexp, int flags)
2223 hammer2_chain_t *parent;
2227 * Calculate locking flags for upward recursion.
2229 how_maybe = HAMMER2_RESOLVE_MAYBE;
2230 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2231 how_maybe |= HAMMER2_RESOLVE_SHARED;
2236 * Calculate the next index and recalculate the parent if necessary.
2239 key_beg = chain->bref.key +
2240 ((hammer2_key_t)1 << chain->bref.keybits);
2241 if (flags & HAMMER2_LOOKUP_NOLOCK)
2242 hammer2_chain_drop(chain);
2244 hammer2_chain_unlock(chain);
2247 * Any scan where the lookup returned degenerate data embedded
2248 * in the inode has an invalid index and must terminate.
2250 if (chain == parent)
2252 if (key_beg == 0 || key_beg > key_end)
2255 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2256 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2258 * We reached the end of the iteration.
2263 * Continue iteration with next parent unless the current
2264 * parent covers the range.
2266 key_beg = parent->bref.key +
2267 ((hammer2_key_t)1 << parent->bref.keybits);
2268 if (key_beg == 0 || key_beg > key_end)
2270 parent = hammer2_chain_getparent(parentp, how_maybe);
2276 return (hammer2_chain_lookup(parentp, key_nextp,
2278 cache_indexp, flags));
2282 * Create and return a new hammer2 system memory structure of the specified
2283 * key, type and size and insert it under (*parentp). This is a full
2284 * insertion, based on the supplied key/keybits, and may involve creating
2285 * indirect blocks and moving other chains around via delete/duplicate.
2287 * (*parentp) must be exclusive locked and may be replaced on return
2288 * depending on how much work the function had to do.
2290 * (*chainp) usually starts out NULL and returns the newly created chain,
2291 * but if the caller desires the caller may allocate a disconnected chain
2292 * and pass it in instead. (It is also possible for the caller to use
2293 * chain_duplicate() to create a disconnected chain, manipulate it, then
2294 * pass it into this function to insert it).
2296 * This function should NOT be used to insert INDIRECT blocks. It is
2297 * typically used to create/insert inodes and data blocks.
2299 * Caller must pass-in an exclusively locked parent the new chain is to
2300 * be inserted under, and optionally pass-in a disconnected, exclusively
2301 * locked chain to insert (else we create a new chain). The function will
2302 * adjust (*parentp) as necessary, create or connect the chain, and
2303 * return an exclusively locked chain in *chainp.
2306 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2307 hammer2_chain_t **chainp,
2308 hammer2_key_t key, int keybits, int type, size_t bytes)
2310 hammer2_mount_t *hmp;
2311 hammer2_chain_t *chain;
2312 hammer2_chain_t *parent = *parentp;
2313 hammer2_chain_core_t *above;
2314 hammer2_blockref_t *base;
2315 hammer2_blockref_t dummy;
2320 above = parent->core;
2321 KKASSERT(ccms_thread_lock_owned(&above->cst));
2325 if (chain == NULL) {
2327 * First allocate media space and construct the dummy bref,
2328 * then allocate the in-memory chain structure. Set the
2329 * INITIAL flag for fresh chains.
2331 bzero(&dummy, sizeof(dummy));
2334 dummy.keybits = keybits;
2335 dummy.data_off = hammer2_getradix(bytes);
2336 dummy.methods = parent->bref.methods;
2337 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2338 hammer2_chain_core_alloc(trans, chain, NULL);
2340 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2343 * Lock the chain manually, chain_lock will load the chain
2344 * which we do NOT want to do. (note: chain->refs is set
2345 * to 1 by chain_alloc() for us, but lockcnt is not).
2348 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2352 * We do NOT set INITIAL here (yet). INITIAL is only
2353 * used for indirect blocks.
2355 * Recalculate bytes to reflect the actual media block
2358 bytes = (hammer2_off_t)1 <<
2359 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2360 chain->bytes = bytes;
2363 case HAMMER2_BREF_TYPE_VOLUME:
2364 case HAMMER2_BREF_TYPE_FREEMAP:
2365 panic("hammer2_chain_create: called with volume type");
2367 case HAMMER2_BREF_TYPE_INODE:
2368 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2369 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2370 chain->data = kmalloc(sizeof(chain->data->ipdata),
2371 hmp->mchain, M_WAITOK | M_ZERO);
2373 case HAMMER2_BREF_TYPE_INDIRECT:
2374 panic("hammer2_chain_create: cannot be used to"
2375 "create indirect block");
2377 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2378 panic("hammer2_chain_create: cannot be used to"
2379 "create freemap root or node");
2381 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2382 KKASSERT(bytes == sizeof(chain->data->bmdata));
2383 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2384 chain->data = kmalloc(sizeof(chain->data->bmdata),
2385 hmp->mchain, M_WAITOK | M_ZERO);
2387 case HAMMER2_BREF_TYPE_DATA:
2389 /* leave chain->data NULL */
2390 KKASSERT(chain->data == NULL);
2395 * Potentially update the existing chain's key/keybits.
2397 * Do NOT mess with the current state of the INITIAL flag.
2399 chain->bref.key = key;
2400 chain->bref.keybits = keybits;
2401 KKASSERT(chain->above == NULL);
2405 * Calculate how many entries we have in the blockref array and
2406 * determine if an indirect block is required.
2409 above = parent->core;
2411 switch(parent->bref.type) {
2412 case HAMMER2_BREF_TYPE_INODE:
2413 KKASSERT((parent->data->ipdata.op_flags &
2414 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2415 KKASSERT(parent->data != NULL);
2416 base = &parent->data->ipdata.u.blockset.blockref[0];
2417 count = HAMMER2_SET_COUNT;
2419 case HAMMER2_BREF_TYPE_INDIRECT:
2420 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2421 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2424 base = &parent->data->npdata[0];
2425 count = parent->bytes / sizeof(hammer2_blockref_t);
2427 case HAMMER2_BREF_TYPE_VOLUME:
2428 KKASSERT(parent->data != NULL);
2429 base = &hmp->voldata.sroot_blockset.blockref[0];
2430 count = HAMMER2_SET_COUNT;
2432 case HAMMER2_BREF_TYPE_FREEMAP:
2433 KKASSERT(parent->data != NULL);
2434 base = &hmp->voldata.freemap_blockset.blockref[0];
2435 count = HAMMER2_SET_COUNT;
2438 panic("hammer2_chain_create: unrecognized blockref type: %d",
2446 * Make sure we've counted the brefs
2448 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2449 hammer2_chain_countbrefs(parent, base, count);
2451 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2454 * If no free blockref could be found we must create an indirect
2455 * block and move a number of blockrefs into it. With the parent
2456 * locked we can safely lock each child in order to delete+duplicate
2457 * it without causing a deadlock.
2459 * This may return the new indirect block or the old parent depending
2460 * on where the key falls. NULL is returned on error.
2462 if (above->live_count == count) {
2463 hammer2_chain_t *nparent;
2465 nparent = hammer2_chain_create_indirect(trans, parent,
2468 if (nparent == NULL) {
2470 hammer2_chain_drop(chain);
2474 if (parent != nparent) {
2475 hammer2_chain_unlock(parent);
2476 parent = *parentp = nparent;
2482 * Link the chain into its parent. Later on we will have to set
2483 * the MOVED bit in situations where we don't mark the new chain
2484 * as being modified.
2486 if (chain->above != NULL)
2487 panic("hammer2: hammer2_chain_create: chain already connected");
2488 KKASSERT(chain->above == NULL);
2489 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2490 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
2491 HAMMER2_CHAIN_INSERT_LIVE);
2495 * Mark the newly created chain modified.
2497 * Device buffers are not instantiated for DATA elements
2498 * as these are handled by logical buffers.
2500 * Indirect and freemap node indirect blocks are handled
2501 * by hammer2_chain_create_indirect() and not by this
2504 * Data for all other bref types is expected to be
2505 * instantiated (INODE, LEAF).
2507 switch(chain->bref.type) {
2508 case HAMMER2_BREF_TYPE_DATA:
2509 hammer2_chain_modify(trans, &chain,
2510 HAMMER2_MODIFY_OPTDATA |
2511 HAMMER2_MODIFY_ASSERTNOCOPY);
2513 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2514 case HAMMER2_BREF_TYPE_INODE:
2515 hammer2_chain_modify(trans, &chain,
2516 HAMMER2_MODIFY_ASSERTNOCOPY);
2520 * Remaining types are not supported by this function.
2521 * In particular, INDIRECT and LEAF_NODE types are
2522 * handled by create_indirect().
2524 panic("hammer2_chain_create: bad type: %d",
2531 * When reconnecting a chain we must set MOVED and setsubmod
2532 * so the flush recognizes that it must update the bref in
2535 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2536 hammer2_chain_ref(chain);
2537 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2540 hammer2_chain_setsubmod(trans, chain);
2549 * Replace (*chainp) with a duplicate in-memory chain structure which shares
2550 * the same core and media state as the orignal. The original *chainp is
2551 * unlocked and the replacement will be returned locked.
2553 * The old chain may or may not be in a DELETED state. This new chain will
2554 * be live (not deleted).
2556 * The new chain will be marked modified for the current transaction.
2558 * If (parent) is non-NULL then the new duplicated chain is inserted under
2561 * If (parent) is NULL then the new duplicated chain is not inserted anywhere,
2562 * similar to if it had just been chain_alloc()'d (suitable for passing into
2563 * hammer2_chain_create() after this function returns).
2565 * WARNING! This is not a snapshot. Changes made underneath either the old
2566 * or new chain will affect both.
2568 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2569 hammer2_chain_t *nchain);
2572 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2573 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2576 hammer2_mount_t *hmp;
2577 hammer2_chain_t *parent;
2578 hammer2_chain_t *ochain;
2579 hammer2_chain_t *nchain;
2580 hammer2_chain_core_t *above;
2584 * We want nchain to be our go-to live chain, but ochain may be in
2585 * a MODIFIED state within the current flush synchronization segment.
2586 * Force any further modifications of ochain to do another COW
2587 * operation even if modify_tid indicates that one is not needed.
2589 * WARNING! We should never resolve DATA to device buffers
2590 * (XXX allow it if the caller did?), and since
2591 * we currently do not have the logical buffer cache
2592 * buffer in-hand to fix its cached physical offset
2593 * we also force the modify code to not COW it. XXX
2598 ochain->debug_reason += 0x10000;
2600 ochain->debug_reason += 0x100000;
2603 if (ochain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2604 hammer2_chain_modify(trans, &ochain,
2605 HAMMER2_MODIFY_OPTDATA |
2606 HAMMER2_MODIFY_NOREALLOC);
2607 } else if (ochain->flags & HAMMER2_CHAIN_INITIAL) {
2608 hammer2_chain_modify(trans, &ochain,
2609 HAMMER2_MODIFY_OPTDATA);
2611 hammer2_chain_modify(trans, &ochain, 0);
2614 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2617 * Now create a duplicate of the chain structure, associating
2618 * it with the same core, making it the same size, pointing it
2619 * to the same bref (the same media block).
2621 * Give the duplicate the same modify_tid that we previously
2622 * ensured was sufficiently advanced to trigger a block table
2623 * insertion on flush.
2625 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2626 * hammer2_chain_alloc()
2629 bref = &ochain->bref;
2631 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2632 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2634 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2636 hammer2_chain_core_alloc(trans, nchain, ochain);
2637 bytes = (hammer2_off_t)1 <<
2638 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2639 nchain->bytes = bytes;
2640 nchain->modify_tid = ochain->modify_tid;
2641 if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2642 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2645 * Fixup (copy) any embedded data. Non-embedded data relies on the
2646 * media block. We must unlock ochain before we can access nchain's
2647 * media block because they might share the same bp and deadlock if
2650 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2651 HAMMER2_RESOLVE_NOREF);
2652 hammer2_chain_dup_fixup(ochain, nchain);
2653 /* nchain has 1 ref */
2654 hammer2_chain_unlock(ochain);
2655 KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2656 ochain->data == NULL);
2659 * Place nchain in the modified state, instantiate media data
2660 * if necessary. Because modify_tid is already completely
2661 * synchronized this should not result in a delete-duplicate.
2663 * We want nchain at the target to look like a new insertion.
2664 * Forcing the modification to be INPLACE accomplishes this
2665 * because we get the same nchain with an updated modify_tid.
2667 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2668 hammer2_chain_modify(trans, &nchain,
2669 HAMMER2_MODIFY_OPTDATA |
2670 HAMMER2_MODIFY_NOREALLOC |
2671 HAMMER2_MODIFY_INPLACE);
2672 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2673 hammer2_chain_modify(trans, &nchain,
2674 HAMMER2_MODIFY_OPTDATA |
2675 HAMMER2_MODIFY_INPLACE);
2677 hammer2_chain_modify(trans, &nchain,
2678 HAMMER2_MODIFY_INPLACE);
2682 * If parent is not NULL the duplicated chain will be entered under
2683 * the parent and the MOVED bit set.
2685 * Having both chains locked is extremely important for atomicy.
2687 if (parentp && (parent = *parentp) != NULL) {
2688 above = parent->core;
2689 KKASSERT(ccms_thread_lock_owned(&above->cst));
2690 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2691 KKASSERT(parent->refs > 0);
2693 hammer2_chain_create(trans, parentp, &nchain,
2694 nchain->bref.key, nchain->bref.keybits,
2695 nchain->bref.type, nchain->bytes);
2698 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2699 hammer2_chain_ref(nchain);
2700 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2702 hammer2_chain_setsubmod(trans, nchain);
2706 * Unconditionally set MOVED to force the parent blockrefs to
2707 * update, and adjust update_tid below nchain so nchain's
2708 * blockrefs are updated with the new attachment.
2710 if (nchain->core->update_tid < trans->sync_tid) {
2711 spin_lock(&nchain->core->cst.spin);
2712 if (nchain->core->update_tid < trans->sync_tid)
2713 nchain->core->update_tid = trans->sync_tid;
2714 spin_unlock(&nchain->core->cst.spin);
2721 * Special in-place delete-duplicate sequence which does not require a
2722 * locked parent. (*chainp) is marked DELETED and atomically replaced
2723 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2724 * order to ensure that lookups do not race us.
2726 * If the old chain is already marked deleted the new chain will also be
2727 * marked deleted. This case can occur when an inode is removed from the
2728 * filesystem but programs still have an open descriptor to it, and during
2729 * flushes when the flush needs to operate on a chain that is deleted in
2730 * the live view but still alive in the flush view.
2732 * The new chain will be marked modified for the current transaction.
2735 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2738 hammer2_mount_t *hmp;
2739 hammer2_chain_t *ochain;
2740 hammer2_chain_t *nchain;
2741 hammer2_chain_core_t *above;
2745 * Note that we do not have to call setsubmod on ochain, calling it
2746 * on nchain is sufficient.
2751 ochain->debug_reason += 0x1000;
2752 if ((ochain->debug_reason & 0xF000) > 0x1000) {
2753 kprintf("ochain %p\n", ochain);
2758 * First create a duplicate of the chain structure.
2759 * (nchain is allocated with one ref).
2761 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2762 if (flags & HAMMER2_DELDUP_RECORE)
2763 hammer2_chain_core_alloc(trans, nchain, NULL);
2765 hammer2_chain_core_alloc(trans, nchain, ochain);
2766 above = ochain->above;
2768 bytes = (hammer2_off_t)1 <<
2769 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2770 nchain->bytes = bytes;
2773 * Duplicate inherits ochain's live state including its modification
2774 * state. This function disposes of the original. Because we are
2775 * doing this in-place under the same parent the block array
2776 * inserted/deleted state does not change.
2778 * The caller isn't expected to make further modifications of ochain
2779 * but set the FORCECOW bit anyway, just in case it does. If ochain
2780 * was previously marked FORCECOW we also flag nchain FORCECOW
2781 * (used during hardlink splits).
2783 * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2784 * hammer2_chain_alloc()
2786 nchain->data_count += ochain->data_count;
2787 nchain->inode_count += ochain->inode_count;
2788 nchain->modify_tid = ochain->modify_tid;
2789 atomic_set_int(&nchain->flags,
2790 ochain->flags & (HAMMER2_CHAIN_INITIAL |
2791 HAMMER2_CHAIN_FORCECOW));
2792 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2795 * Lock nchain so both chains are now locked (extremely important
2796 * for atomicy). Mark ochain deleted and reinsert into the topology
2797 * and insert nchain all in one go.
2799 * If the ochain is already deleted it is left alone and nchain
2800 * is inserted into the topology as a deleted chain. This is
2801 * important because it allows ongoing operations to be executed
2802 * on a deleted inode which still has open descriptors.
2804 * The deleted case can also occur when a flush delete-duplicates
2805 * a node which is being concurrently modified by ongoing operations
2806 * in a later transaction. This creates a problem because the flush
2807 * is intended to update blockrefs which then propagate, allowing
2808 * the original covering in-memory chains to be freed up. In this
2809 * situation the flush code does NOT free the original covering
2810 * chains and will re-apply them to successive copies.
2812 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2813 hammer2_chain_dup_fixup(ochain, nchain);
2814 /* extra ref still present from original allocation */
2816 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2817 spin_lock(&above->cst.spin);
2818 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2820 if (ochain->flags & HAMMER2_CHAIN_DELETED) {
2821 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
2822 /* very important to inherit ochain's delete_tid */
2823 KKASSERT(ochain->delete_tid >= nchain->modify_tid);
2824 nchain->delete_tid = ochain->delete_tid;
2825 hammer2_chain_insert(above, nchain, 0);
2827 KKASSERT(trans->sync_tid >= ochain->modify_tid);
2828 ochain->delete_tid = trans->sync_tid;
2829 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2830 atomic_add_int(&above->live_count, -1);
2831 hammer2_chain_insert(above, nchain, HAMMER2_CHAIN_INSERT_LIVE);
2834 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2835 hammer2_chain_ref(ochain);
2836 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2838 spin_unlock(&above->cst.spin);
2841 * ochain must be unlocked because ochain and nchain might share
2842 * a buffer cache buffer. Assert that there's no buffer.
2844 hammer2_chain_unlock(ochain);
2845 KKASSERT(ochain->bp == NULL);
2848 * Finishing fixing up nchain. A new block will be allocated if
2849 * crossing a synchronization point (meta-data only).
2851 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2852 hammer2_chain_modify(trans, &nchain,
2853 HAMMER2_MODIFY_OPTDATA |
2854 HAMMER2_MODIFY_NOREALLOC |
2855 HAMMER2_MODIFY_INPLACE);
2856 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2857 hammer2_chain_modify(trans, &nchain,
2858 HAMMER2_MODIFY_OPTDATA |
2859 HAMMER2_MODIFY_INPLACE);
2861 hammer2_chain_modify(trans, &nchain,
2862 HAMMER2_MODIFY_INPLACE);
2864 hammer2_chain_drop(nchain);
2867 * Unconditionally set MOVED to force the parent blockrefs to
2868 * update, and adjust update_tid below nchain so nchain's
2869 * blockrefs are updated with the new attachment.
2871 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2872 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2873 hammer2_chain_ref(nchain);
2875 if (nchain->core->update_tid < trans->sync_tid) {
2876 spin_lock(&nchain->core->cst.spin);
2877 if (nchain->core->update_tid < trans->sync_tid)
2878 nchain->core->update_tid = trans->sync_tid;
2879 spin_unlock(&nchain->core->cst.spin);
2881 hammer2_chain_setsubmod(trans, nchain);
2886 * Helper function to fixup inodes. The caller procedure stack may hold
2887 * multiple locks on ochain if it represents an inode, preventing our
2888 * unlock from retiring its state to the buffer cache.
2890 * In this situation any attempt to access the buffer cache could result
2891 * either in stale data or a deadlock. Work around the problem by copying
2892 * the embedded data directly.
2896 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
2898 if (ochain->data == NULL)
2900 switch(ochain->bref.type) {
2901 case HAMMER2_BREF_TYPE_INODE:
2902 KKASSERT(nchain->data == NULL);
2903 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2904 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2905 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2906 nchain->data->ipdata = ochain->data->ipdata;
2908 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2909 KKASSERT(nchain->data == NULL);
2910 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2911 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
2912 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2913 bcopy(ochain->data->bmdata,
2914 nchain->data->bmdata,
2915 sizeof(nchain->data->bmdata));
2923 * Create a snapshot of the specified {parent, ochain} with the specified
2924 * label. The originating hammer2_inode must be exclusively locked for
2927 * The ioctl code has already synced the filesystem.
2930 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
2931 hammer2_ioc_pfs_t *pfs)
2933 hammer2_mount_t *hmp;
2934 hammer2_chain_t *ochain = *ochainp;
2935 hammer2_chain_t *nchain;
2936 hammer2_inode_data_t *ipdata;
2937 hammer2_inode_t *nip;
2944 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
2945 pfs->name, ochain->refs, ochain->flags);
2947 name_len = strlen(pfs->name);
2948 lhc = hammer2_dirhash(pfs->name, name_len);
2951 opfs_clid = ochain->data->ipdata.pfs_clid;
2952 KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2957 * Create the snapshot directory under the super-root
2959 * Set PFS type, generate a unique filesystem id, and generate
2960 * a cluster id. Use the same clid when snapshotting a PFS root,
2961 * which theoretically allows the snapshot to be used as part of
2962 * the same cluster (perhaps as a cache).
2964 * Copy the (flushed) ochain's blockref array. Theoretically we
2965 * could use chain_duplicate() but it becomes difficult to disentangle
2966 * the shared core so for now just brute-force it.
2972 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
2973 pfs->name, name_len, &nchain, &error);
2976 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
2977 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2978 kern_uuidgen(&ipdata->pfs_fsid, 1);
2979 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
2980 ipdata->pfs_clid = opfs_clid;
2982 kern_uuidgen(&ipdata->pfs_clid, 1);
2983 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
2984 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
2986 hammer2_inode_unlock_ex(nip, nchain);
2992 * Create an indirect block that covers one or more of the elements in the
2993 * current parent. Either returns the existing parent with no locking or
2994 * ref changes or returns the new indirect block locked and referenced
2995 * and leaving the original parent lock/ref intact as well.
2997 * If an error occurs, NULL is returned and *errorp is set to the error.
2999 * The returned chain depends on where the specified key falls.
3001 * The key/keybits for the indirect mode only needs to follow three rules:
3003 * (1) That all elements underneath it fit within its key space and
3005 * (2) That all elements outside it are outside its key space.
3007 * (3) When creating the new indirect block any elements in the current
3008 * parent that fit within the new indirect block's keyspace must be
3009 * moved into the new indirect block.
3011 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3012 * keyspace the the current parent, but lookup/iteration rules will
3013 * ensure (and must ensure) that rule (2) for all parents leading up
3014 * to the nearest inode or the root volume header is adhered to. This
3015 * is accomplished by always recursing through matching keyspaces in
3016 * the hammer2_chain_lookup() and hammer2_chain_next() API.
3018 * The current implementation calculates the current worst-case keyspace by
3019 * iterating the current parent and then divides it into two halves, choosing
3020 * whichever half has the most elements (not necessarily the half containing
3021 * the requested key).
3023 * We can also opt to use the half with the least number of elements. This
3024 * causes lower-numbered keys (aka logical file offsets) to recurse through
3025 * fewer indirect blocks and higher-numbered keys to recurse through more.
3026 * This also has the risk of not moving enough elements to the new indirect
3027 * block and being forced to create several indirect blocks before the element
3030 * Must be called with an exclusively locked parent.
3032 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3033 hammer2_key_t *keyp, int keybits,
3034 hammer2_blockref_t *base, int count);
3035 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3036 hammer2_key_t *keyp, int keybits,
3037 hammer2_blockref_t *base, int count);
3040 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3041 hammer2_key_t create_key, int create_bits,
3042 int for_type, int *errorp)
3044 hammer2_mount_t *hmp;
3045 hammer2_chain_core_t *above;
3046 hammer2_chain_core_t *icore;
3047 hammer2_blockref_t *base;
3048 hammer2_blockref_t *bref;
3049 hammer2_blockref_t bcopy;
3050 hammer2_chain_t *chain;
3051 hammer2_chain_t *ichain;
3052 hammer2_chain_t dummy;
3053 hammer2_key_t key = create_key;
3054 hammer2_key_t key_beg;
3055 hammer2_key_t key_end;
3056 hammer2_key_t key_next;
3057 int keybits = create_bits;
3064 * Calculate the base blockref pointer or NULL if the chain
3065 * is known to be empty. We need to calculate the array count
3066 * for RB lookups either way.
3070 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3071 above = parent->core;
3073 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3074 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3077 switch(parent->bref.type) {
3078 case HAMMER2_BREF_TYPE_INODE:
3079 count = HAMMER2_SET_COUNT;
3081 case HAMMER2_BREF_TYPE_INDIRECT:
3082 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3083 count = parent->bytes / sizeof(hammer2_blockref_t);
3085 case HAMMER2_BREF_TYPE_VOLUME:
3086 count = HAMMER2_SET_COUNT;
3088 case HAMMER2_BREF_TYPE_FREEMAP:
3089 count = HAMMER2_SET_COUNT;
3092 panic("hammer2_chain_create_indirect: "
3093 "unrecognized blockref type: %d",
3099 switch(parent->bref.type) {
3100 case HAMMER2_BREF_TYPE_INODE:
3101 base = &parent->data->ipdata.u.blockset.blockref[0];
3102 count = HAMMER2_SET_COUNT;
3104 case HAMMER2_BREF_TYPE_INDIRECT:
3105 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3106 base = &parent->data->npdata[0];
3107 count = parent->bytes / sizeof(hammer2_blockref_t);
3109 case HAMMER2_BREF_TYPE_VOLUME:
3110 base = &hmp->voldata.sroot_blockset.blockref[0];
3111 count = HAMMER2_SET_COUNT;
3113 case HAMMER2_BREF_TYPE_FREEMAP:
3114 base = &hmp->voldata.freemap_blockset.blockref[0];
3115 count = HAMMER2_SET_COUNT;
3118 panic("hammer2_chain_create_indirect: "
3119 "unrecognized blockref type: %d",
3127 * dummy used in later chain allocation (no longer used for lookups).
3129 bzero(&dummy, sizeof(dummy));
3130 dummy.delete_tid = HAMMER2_MAX_TID;
3133 * When creating an indirect block for a freemap node or leaf
3134 * the key/keybits must be fitted to static radix levels because
3135 * particular radix levels use particular reserved blocks in the
3138 * This routine calculates the key/radix of the indirect block
3139 * we need to create, and whether it is on the high-side or the
3142 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3143 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3144 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3147 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3152 * Normalize the key for the radix being represented, keeping the
3153 * high bits and throwing away the low bits.
3155 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3158 * How big should our new indirect block be? It has to be at least
3159 * as large as its parent.
3161 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3162 nbytes = HAMMER2_IND_BYTES_MIN;
3164 nbytes = HAMMER2_IND_BYTES_MAX;
3165 if (nbytes < count * sizeof(hammer2_blockref_t))
3166 nbytes = count * sizeof(hammer2_blockref_t);
3169 * Ok, create our new indirect block
3171 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3172 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3173 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3175 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3177 dummy.bref.key = key;
3178 dummy.bref.keybits = keybits;
3179 dummy.bref.data_off = hammer2_getradix(nbytes);
3180 dummy.bref.methods = parent->bref.methods;
3182 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3183 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3184 hammer2_chain_core_alloc(trans, ichain, NULL);
3185 icore = ichain->core;
3186 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3187 hammer2_chain_drop(ichain); /* excess ref from alloc */
3190 * We have to mark it modified to allocate its block, but use
3191 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3192 * it won't be acted upon by the flush code.
3194 * XXX leave the node unmodified, depend on the update_tid
3195 * flush to assign and modify parent blocks.
3197 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3200 * Iterate the original parent and move the matching brefs into
3201 * the new indirect block.
3203 * XXX handle flushes.
3206 key_end = HAMMER2_MAX_KEY;
3208 spin_lock(&above->cst.spin);
3212 if (++loops > 8192) {
3213 spin_unlock(&above->cst.spin);
3214 panic("shit parent=%p base/count %p:%d\n",
3215 parent, base, count);
3219 * NOTE: spinlock stays intact, returned chain (if not NULL)
3220 * is not referenced or locked.
3222 chain = hammer2_combined_find(parent, base, count,
3223 &cache_index, &key_next,
3228 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3229 if (key_next == 0 || key_next > key_end)
3236 * Use the full live (not deleted) element for the scan
3237 * iteration. HAMMER2 does not allow partial replacements.
3239 * XXX should be built into hammer2_combined_find().
3241 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3244 * Skip keys that are not within the key/radix of the new
3245 * indirect block. They stay in the parent.
3247 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3248 (key ^ bref->key)) != 0) {
3249 if (key_next == 0 || key_next > key_end)
3256 * Load the new indirect block by acquiring or allocating
3257 * the related chain, then move it to the new parent (ichain)
3258 * via DELETE-DUPLICATE.
3260 * WARNING! above->cst.spin must be held when parent is
3261 * modified, even though we own the full blown lock,
3262 * to deal with setsubmod and rename races.
3263 * (XXX remove this req).
3267 * Use chain already present in the RBTREE
3269 hammer2_chain_ref(chain);
3270 spin_unlock(&above->cst.spin);
3271 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3272 HAMMER2_RESOLVE_NOREF);
3275 * Get chain for blockref element. _get returns NULL
3276 * on insertion race.
3279 spin_unlock(&above->cst.spin);
3280 chain = hammer2_chain_get(parent, bref);
3283 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3284 hammer2_chain_drop(chain);
3287 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3288 HAMMER2_RESOLVE_NOREF);
3290 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
3291 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0);
3292 hammer2_chain_unlock(chain);
3293 KKASSERT(parent->refs > 0);
3295 spin_lock(&above->cst.spin);
3296 if (key_next == 0 || key_next > key_end)
3300 spin_unlock(&above->cst.spin);
3303 * Insert the new indirect block into the parent now that we've
3304 * cleared out some entries in the parent. We calculated a good
3305 * insertion index in the loop above (ichain->index).
3307 * We don't have to set MOVED here because we mark ichain modified
3308 * down below (so the normal modified -> flush -> set-moved sequence
3311 * The insertion shouldn't race as this is a completely new block
3312 * and the parent is locked.
3314 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3315 hammer2_chain_insert(above, ichain, HAMMER2_CHAIN_INSERT_SPIN |
3316 HAMMER2_CHAIN_INSERT_LIVE);
3319 * Mark the new indirect block modified after insertion, which
3320 * will propagate up through parent all the way to the root and
3321 * also allocate the physical block in ichain for our caller,
3322 * and assign ichain->data to a pre-zero'd space (because there
3323 * is not prior data to copy into it).
3325 * We have to set update_tid in ichain's flags manually so the
3326 * flusher knows it has to recurse through it to get to all of
3327 * our moved blocks, then call setsubmod() to set the bit
3330 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3331 if (ichain->core->update_tid < trans->sync_tid) {
3332 spin_lock(&ichain->core->cst.spin);
3333 if (ichain->core->update_tid < trans->sync_tid)
3334 ichain->core->update_tid = trans->sync_tid;
3335 spin_unlock(&ichain->core->cst.spin);
3337 hammer2_chain_setsubmod(trans, ichain);
3340 * Figure out what to return.
3342 if (~(((hammer2_key_t)1 << keybits) - 1) &
3343 (create_key ^ key)) {
3345 * Key being created is outside the key range,
3346 * return the original parent.
3348 hammer2_chain_unlock(ichain);
3351 * Otherwise its in the range, return the new parent.
3352 * (leave both the new and old parent locked).
3361 * Calculate the keybits and highside/lowside of the freemap node the
3362 * caller is creating.
3364 * This routine will specify the next higher-level freemap key/radix
3365 * representing the lowest-ordered set. By doing so, eventually all
3366 * low-ordered sets will be moved one level down.
3368 * We have to be careful here because the freemap reserves a limited
3369 * number of blocks for a limited number of levels. So we can't just
3370 * push indiscriminately.
3373 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3374 int keybits, hammer2_blockref_t *base, int count)
3376 hammer2_chain_core_t *above;
3377 hammer2_chain_t *chain;
3378 hammer2_blockref_t *bref;
3380 hammer2_key_t key_beg;
3381 hammer2_key_t key_end;
3382 hammer2_key_t key_next;
3389 above = parent->core;
3395 * Calculate the range of keys in the array being careful to skip
3396 * slots which are overridden with a deletion.
3399 key_end = HAMMER2_MAX_KEY;
3401 spin_lock(&above->cst.spin);
3404 if (++loops == 100000) {
3405 panic("indkey_freemap shit %p %p:%d\n",
3406 parent, base, count);
3408 chain = hammer2_combined_find(parent, base, count,
3409 &cache_index, &key_next,
3410 key_beg, key_end, &bref);
3417 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3418 if (key_next == 0 || key_next > key_end)
3425 * Use the full live (not deleted) element for the scan
3426 * iteration. HAMMER2 does not allow partial replacements.
3428 * XXX should be built into hammer2_combined_find().
3430 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3432 if (keybits > bref->keybits) {
3434 keybits = bref->keybits;
3435 } else if (keybits == bref->keybits && bref->key < key) {
3442 spin_unlock(&above->cst.spin);
3445 * Return the keybits for a higher-level FREEMAP_NODE covering
3449 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3450 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3452 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3453 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3455 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3456 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3458 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3459 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3461 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3462 panic("hammer2_chain_indkey_freemap: level too high");
3465 panic("hammer2_chain_indkey_freemap: bad radix");
3474 * Calculate the keybits and highside/lowside of the indirect block the
3475 * caller is creating.
3478 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3479 int keybits, hammer2_blockref_t *base, int count)
3481 hammer2_chain_core_t *above;
3482 hammer2_blockref_t *bref;
3483 hammer2_chain_t *chain;
3484 hammer2_key_t key_beg;
3485 hammer2_key_t key_end;
3486 hammer2_key_t key_next;
3495 above = parent->core;
3500 * Calculate the range of keys in the array being careful to skip
3501 * slots which are overridden with a deletion. Once the scan
3502 * completes we will cut the key range in half and shift half the
3503 * range into the new indirect block.
3506 key_end = HAMMER2_MAX_KEY;
3508 spin_lock(&above->cst.spin);
3511 if (++loops == 100000) {
3512 panic("indkey_freemap shit %p %p:%d\n",
3513 parent, base, count);
3515 chain = hammer2_combined_find(parent, base, count,
3516 &cache_index, &key_next,
3517 key_beg, key_end, &bref);
3524 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3525 if (key_next == 0 || key_next > key_end)
3532 * Use the full live (not deleted) element for the scan
3533 * iteration. HAMMER2 does not allow partial replacements.
3535 * XXX should be built into hammer2_combined_find().
3537 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3540 * Expand our calculated key range (key, keybits) to fit
3541 * the scanned key. nkeybits represents the full range
3542 * that we will later cut in half (two halves @ nkeybits - 1).
3545 if (nkeybits < bref->keybits) {
3546 if (bref->keybits > 64) {
3547 kprintf("bad bref chain %p bref %p\n",
3551 nkeybits = bref->keybits;
3553 while (nkeybits < 64 &&
3554 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3555 (key ^ bref->key)) != 0) {
3560 * If the new key range is larger we have to determine
3561 * which side of the new key range the existing keys fall
3562 * under by checking the high bit, then collapsing the
3563 * locount into the hicount or vise-versa.
3565 if (keybits != nkeybits) {
3566 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3577 * The newly scanned key will be in the lower half or the
3578 * upper half of the (new) key range.
3580 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3589 spin_unlock(&above->cst.spin);
3590 bref = NULL; /* now invalid (safety) */
3593 * Adjust keybits to represent half of the full range calculated
3594 * above (radix 63 max)
3599 * Select whichever half contains the most elements. Theoretically
3600 * we can select either side as long as it contains at least one
3601 * element (in order to ensure that a free slot is present to hold
3602 * the indirect block).
3604 if (hammer2_indirect_optimize) {
3606 * Insert node for least number of keys, this will arrange
3607 * the first few blocks of a large file or the first few
3608 * inodes in a directory with fewer indirect blocks when
3611 if (hicount < locount && hicount != 0)
3612 key |= (hammer2_key_t)1 << keybits;
3614 key &= ~(hammer2_key_t)1 << keybits;
3617 * Insert node for most number of keys, best for heavily
3620 if (hicount > locount)
3621 key |= (hammer2_key_t)1 << keybits;
3623 key &= ~(hammer2_key_t)1 << keybits;
3631 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3632 * set chain->delete_tid.
3634 * This function does NOT generate a modification to the parent. It
3635 * would be nearly impossible to figure out which parent to modify anyway.
3636 * Such modifications are handled by the flush code and are properly merged
3637 * using the flush synchronization point.
3639 * The find/get code will properly overload the RBTREE check on top of
3640 * the bref check to detect deleted entries.
3642 * This function is NOT recursive. Any entity already pushed into the
3643 * chain (such as an inode) may still need visibility into its contents,
3644 * as well as the ability to read and modify the contents. For example,
3645 * for an unlinked file which is still open.
3647 * NOTE: This function does NOT set chain->modify_tid, allowing future
3648 * code to distinguish between live and deleted chains by testing
3651 * NOTE: Deletions normally do not occur in the middle of a duplication
3652 * chain but we use a trick for hardlink migration that refactors
3653 * the originating inode without deleting it, so we make no assumptions
3657 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3659 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3662 * Nothing to do if already marked.
3664 if (chain->flags & HAMMER2_CHAIN_DELETED)
3668 * We must set MOVED along with DELETED for the flush code to
3669 * recognize the operation and properly disconnect the chain
3672 * The setting of DELETED causes finds, lookups, and _next iterations
3673 * to no longer recognize the chain. RB_SCAN()s will still have
3674 * visibility (needed for flush serialization points).
3676 * We need the spinlock on the core whos RBTREE contains chain
3677 * to protect against races.
3679 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3680 spin_lock(&chain->above->cst.spin);
3682 KKASSERT(trans->sync_tid >= chain->modify_tid);
3683 chain->delete_tid = trans->sync_tid;
3684 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3685 atomic_add_int(&chain->above->live_count, -1);
3686 ++chain->above->generation;
3688 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3689 hammer2_chain_ref(chain);
3690 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3692 spin_unlock(&chain->above->cst.spin);
3694 if (flags & HAMMER2_DELETE_WILLDUP)
3695 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
3697 if ((chain->flags & HAMMER2_CHAIN_FORCECOW) == 0) {
3698 hammer2_freemap_free(trans, chain->hmp, &chain->bref, 0);
3699 chain->bref.data_off &= ~HAMMER2_OFF_MASK_RADIX;
3701 hammer2_chain_setsubmod(trans, chain);
3705 * Called with the core spinlock held to check for freeable layers.
3706 * Used by the flush code. Layers can wind up not being freed due
3707 * to the temporary layer->refs count. This function frees up any
3708 * layers that were missed.
3711 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3712 hammer2_chain_core_t *core)
3714 hammer2_chain_layer_t *layer;
3715 hammer2_chain_layer_t *tmp;
3717 tmp = TAILQ_FIRST(&core->layerq);
3718 while ((layer = tmp) != NULL) {
3719 tmp = TAILQ_NEXT(tmp, entry);
3720 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
3721 TAILQ_REMOVE(&core->layerq, layer, entry);
3724 spin_unlock(&core->cst.spin);
3725 kfree(layer, hmp->mchain);
3726 spin_lock(&core->cst.spin);
3734 * Returns the index of the nearest element in the blockref array >= elm.
3735 * Returns (count) if no element could be found.
3737 * Sets *key_nextp to the next key for loop purposes but does not modify
3738 * it if the next key would be higher than the current value of *key_nextp.
3739 * Note that *key_nexp can overflow to 0, which should be tested by the
3742 * (*cache_indexp) is a heuristic and can be any value without effecting
3745 * The spin lock on the related chain must be held.
3748 hammer2_base_find(hammer2_chain_t *chain,
3749 hammer2_blockref_t *base, int count,
3750 int *cache_indexp, hammer2_key_t *key_nextp,
3751 hammer2_key_t key_beg, hammer2_key_t key_end)
3753 hammer2_chain_core_t *core = chain->core;
3754 hammer2_blockref_t *scan;
3755 hammer2_key_t scan_end;
3761 KKASSERT(core->flags & HAMMER2_CORE_COUNTEDBREFS);
3762 if (count == 0 || base == NULL)
3766 * Sequential optimization
3770 if (i >= core->live_zero)
3771 i = core->live_zero - 1;
3774 KKASSERT(i < count);
3780 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3787 * Search forwards, stop when we find a scan element which
3788 * encloses the key or until we know that there are no further
3792 if (scan->type != 0) {
3793 if (scan->key > key_beg)
3795 scan_end = scan->key +
3796 ((hammer2_key_t)1 << scan->keybits) - 1;
3797 if (scan_end >= key_beg)
3800 if (i >= core->live_zero)
3807 if (i >= core->live_zero) {
3810 scan_end = scan->key +
3811 ((hammer2_key_t)1 << scan->keybits);
3812 if (scan_end && (*key_nextp > scan_end ||
3814 *key_nextp = scan_end;
3822 * Do a combined search and return the next match either from the blockref
3823 * array or from the in-memory chain. Sets *bresp to the returned bref in
3824 * both cases, or sets it to NULL if the search exhausted. Only returns
3825 * a non-NULL chain if the search matched from the in-memory chain.
3827 * Must be called with above's spinlock held. Spinlock remains held
3828 * through the operation.
3830 * The returned chain is not locked or referenced. Use the returned bref
3831 * to determine if the search exhausted or not.
3833 static hammer2_chain_t *
3834 hammer2_combined_find(hammer2_chain_t *parent,
3835 hammer2_blockref_t *base, int count,
3836 int *cache_indexp, hammer2_key_t *key_nextp,
3837 hammer2_key_t key_beg, hammer2_key_t key_end,
3838 hammer2_blockref_t **bresp)
3840 hammer2_blockref_t *bref;
3841 hammer2_chain_t *chain;
3844 *key_nextp = key_end + 1;
3845 i = hammer2_base_find(parent, base, count, cache_indexp,
3846 key_nextp, key_beg, key_end);
3847 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3852 if (i == count && chain == NULL) {
3854 return(chain); /* NULL */
3858 * Only chain matched
3861 bref = &chain->bref;
3866 * Only blockref matched.
3868 if (chain == NULL) {
3874 * Both in-memory and blockref match.
3876 * If they are both flush with the left hand side select the chain.
3877 * If their starts match select the chain.
3878 * Otherwise the nearer element wins.
3880 if (chain->bref.key <= key_beg && base[i].key <= key_beg) {
3881 bref = &chain->bref;
3884 if (chain->bref.key <= base[i].key) {
3885 bref = &chain->bref;
3893 * If the bref is out of bounds we've exhausted our search.
3896 if (bref->key > key_end) {
3906 * Locate the specified block array element and delete it. The element
3909 * The spin lock on the related chain must be held.
3911 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3912 * need to be adjusted when we commit the media change.
3915 hammer2_base_delete(hammer2_chain_t *chain,
3916 hammer2_blockref_t *base, int count,
3917 int *cache_indexp, hammer2_chain_t *child)
3919 hammer2_blockref_t *elm = &child->bref;
3920 hammer2_chain_core_t *core = chain->core;
3921 hammer2_key_t key_next;
3925 * Delete element. Expect the element to exist.
3927 * XXX see caller, flush code not yet sophisticated enough to prevent
3928 * re-flushed in some cases.
3930 key_next = 0; /* max range */
3931 i = hammer2_base_find(chain, base, count, cache_indexp,
3932 &key_next, elm->key, elm->key);
3933 if (i == count || base[i].type == 0 ||
3934 base[i].key != elm->key || base[i].keybits != elm->keybits) {
3935 panic("delete base %p element not found at %d/%d elm %p\n",
3936 base, i, count, elm);
3939 bzero(&base[i], sizeof(*base));
3940 if (core->live_zero == i + 1) {
3941 while (--i >= 0 && base[i].type == 0)
3943 core->live_zero = i + 1;
3948 * Insert the specified element. The block array must not already have the
3949 * element and must have space available for the insertion.
3951 * The spin lock on the related chain must be held.
3953 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3954 * need to be adjusted when we commit the media change.
3957 hammer2_base_insert(hammer2_chain_t *parent,
3958 hammer2_blockref_t *base, int count,
3959 int *cache_indexp, hammer2_chain_t *child)
3961 hammer2_blockref_t *elm = &child->bref;
3962 hammer2_chain_core_t *core = parent->core;
3963 hammer2_key_t key_next;
3972 * Insert new element. Expect the element to not already exist
3973 * unless we are replacing it.
3975 * XXX see caller, flush code not yet sophisticated enough to prevent
3976 * re-flushed in some cases.
3978 key_next = 0; /* max range */
3979 i = hammer2_base_find(parent, base, count, cache_indexp,
3980 &key_next, elm->key, elm->key);
3983 * Shortcut fill optimization, typical ordered insertion(s) may not
3986 KKASSERT(i >= 0 && i <= count);
3988 if (i == count && core->live_zero < count) {
3989 i = core->live_zero++;
3994 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3995 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3996 panic("insert base %p overlapping elements at %d elm %p\n",
4001 * Try to find an empty slot before or after.
4005 while (j > 0 || k < count) {
4007 if (j >= 0 && base[j].type == 0) {
4011 bcopy(&base[j+1], &base[j],
4012 (i - j - 1) * sizeof(*base));
4018 if (k < count && base[k].type == 0) {
4019 bcopy(&base[i], &base[i+1],
4020 (k - i) * sizeof(hammer2_blockref_t));
4022 if (core->live_zero <= k)
4023 core->live_zero = k + 1;
4028 panic("hammer2_base_insert: no room!");
4035 for (l = 0; l < count; ++l) {
4037 key_next = base[l].key +
4038 ((hammer2_key_t)1 << base[l].keybits) - 1;
4042 while (++l < count) {
4044 if (base[l].key <= key_next)
4045 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4046 key_next = base[l].key +
4047 ((hammer2_key_t)1 << base[l].keybits) - 1;
4057 * Sort the blockref array for the chain. Used by the flush code to
4058 * sort the blockref[] array.
4060 * The chain must be exclusively locked AND spin-locked.
4062 typedef hammer2_blockref_t *hammer2_blockref_p;
4066 hammer2_base_sort_callback(const void *v1, const void *v2)
4068 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4069 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4072 * Make sure empty elements are placed at the end of the array
4074 if (bref1->type == 0) {
4075 if (bref2->type == 0)
4078 } else if (bref2->type == 0) {
4085 if (bref1->key < bref2->key)
4087 if (bref1->key > bref2->key)
4093 hammer2_base_sort(hammer2_chain_t *chain)
4095 hammer2_blockref_t *base;
4098 switch(chain->bref.type) {
4099 case HAMMER2_BREF_TYPE_INODE:
4101 * Special shortcut for embedded data returns the inode
4102 * itself. Callers must detect this condition and access
4103 * the embedded data (the strategy code does this for us).
4105 * This is only applicable to regular files and softlinks.
4107 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4109 base = &chain->data->ipdata.u.blockset.blockref[0];
4110 count = HAMMER2_SET_COUNT;
4112 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4113 case HAMMER2_BREF_TYPE_INDIRECT:
4115 * Optimize indirect blocks in the INITIAL state to avoid
4118 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4119 base = &chain->data->npdata[0];
4120 count = chain->bytes / sizeof(hammer2_blockref_t);
4122 case HAMMER2_BREF_TYPE_VOLUME:
4123 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4124 count = HAMMER2_SET_COUNT;
4126 case HAMMER2_BREF_TYPE_FREEMAP:
4127 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4128 count = HAMMER2_SET_COUNT;
4131 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4133 base = NULL; /* safety */
4134 count = 0; /* safety */
4136 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4142 * Chain memory management
4145 hammer2_chain_wait(hammer2_chain_t *chain)
4147 tsleep(chain, 0, "chnflw", 1);
4151 * Manage excessive memory resource use for chain and related
4155 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4158 while (pmp->inmem_chains > desiredvnodes / 10 &&
4159 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 2) {
4161 speedup_syncer(pmp->mp);
4162 pmp->inmem_waiting = 1;
4163 tsleep(&pmp->inmem_waiting, 0, "chnmem", hz);
4167 if (pmp->inmem_chains > desiredvnodes / 10 &&
4168 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 7 / 4) {
4169 speedup_syncer(pmp->mp);
4175 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4177 if (pmp->inmem_waiting &&
4178 (pmp->inmem_chains <= desiredvnodes / 10 ||
4179 pmp->inmem_chains <= pmp->mp->mnt_nvnodelistsize * 2)) {
4181 pmp->inmem_waiting = 0;
4182 wakeup(&pmp->inmem_waiting);
4188 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4192 switch(bref->type) {
4193 case HAMMER2_BREF_TYPE_DATA:
4194 counterp = &hammer2_iod_file_read;
4196 case HAMMER2_BREF_TYPE_INODE:
4197 counterp = &hammer2_iod_meta_read;
4199 case HAMMER2_BREF_TYPE_INDIRECT:
4200 counterp = &hammer2_iod_indr_read;
4202 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4203 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4204 counterp = &hammer2_iod_fmap_read;
4207 counterp = &hammer2_iod_volu_read;