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
62 #include <sys/cdefs.h>
63 #include <sys/param.h>
64 #include <sys/systm.h>
65 #include <sys/types.h>
67 #include <sys/kern_syscall.h>
72 static int hammer2_indirect_optimize; /* XXX SYSCTL */
74 static hammer2_chain_t *hammer2_chain_create_indirect(
75 hammer2_trans_t *trans, hammer2_chain_t *parent,
76 hammer2_key_t key, int keybits, int for_type, int *errorp);
77 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
78 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
79 static hammer2_chain_t *hammer2_combined_find(
80 hammer2_chain_t *parent,
81 hammer2_blockref_t *base, int count,
82 int *cache_indexp, hammer2_key_t *key_nextp,
83 hammer2_key_t key_beg, hammer2_key_t key_end,
84 hammer2_blockref_t **bresp);
87 * Basic RBTree for chains. Chains cannot overlap within any given
88 * core->rbtree without recursing through chain->rbtree. We effectively
89 * guarantee this by checking the full range rather than just the first
90 * key element. By matching on the full range callers can detect when
91 * recursrion through chain->rbtree is needed.
93 * NOTE: This also means the a delete-duplicate on the same key will
94 * overload by placing the deleted element in the new element's
95 * chain->rbtree (when doing a direct replacement).
97 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
100 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
102 hammer2_key_t c1_beg;
103 hammer2_key_t c1_end;
104 hammer2_key_t c2_beg;
105 hammer2_key_t c2_end;
107 c1_beg = chain1->bref.key;
108 c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
109 c2_beg = chain2->bref.key;
110 c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
112 if (c1_end < c2_beg) /* fully to the left */
114 if (c1_beg > c2_end) /* fully to the right */
116 return(0); /* overlap (must not cross edge boundary) */
121 hammer2_isclusterable(hammer2_chain_t *chain)
123 if (hammer2_cluster_enable) {
124 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
125 chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
126 chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
134 * Recursively set the update_tid flag up to the root starting at chain's
135 * parent->core. update_tid is not set in chain's core.
137 * This controls top-down visibility for flushes. The child has just one
138 * 'above' core, but the core itself can be multi-homed with parents iterated
141 * However, this function is only used on the live tree which we can locate
142 * by finding the first non-DUPLICATED parent. Note that this parent might
145 * The live tree can be ripped out while *any* deeper node is held
146 * (XXX is that still true?), so we can recurse upward without locks.
149 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
151 hammer2_chain_core_t *above;
154 (HAMMER2_TRANS_ISFLUSH | HAMMER2_TRANS_ISALLOCATING)) ==
155 HAMMER2_TRANS_ISFLUSH) {
158 while ((above = chain->above) != NULL) {
159 spin_lock(&above->cst.spin);
160 if (above->update_tid < trans->sync_tid)
161 above->update_tid = trans->sync_tid;
162 chain = TAILQ_FIRST(&above->ownerq);
163 while (chain->flags & HAMMER2_CHAIN_DUPLICATED)
164 chain = TAILQ_NEXT(chain, core_entry);
165 spin_unlock(&above->cst.spin);
170 * Allocate a new disconnected chain element representing the specified
171 * bref. chain->refs is set to 1 and the passed bref is copied to
172 * chain->bref. chain->bytes is derived from the bref.
174 * chain->core is NOT allocated and the media data and bp pointers are left
175 * NULL. The caller must call chain_core_alloc() to allocate or associate
176 * a core with the chain.
178 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
181 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
182 hammer2_trans_t *trans, hammer2_blockref_t *bref)
184 hammer2_chain_t *chain;
185 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
188 * Construct the appropriate system structure.
191 case HAMMER2_BREF_TYPE_INODE:
192 case HAMMER2_BREF_TYPE_INDIRECT:
193 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
194 case HAMMER2_BREF_TYPE_DATA:
195 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
197 * Chain's are really only associated with the hmp but we
198 * maintain a pmp association for per-mount memory tracking
199 * purposes. The pmp can be NULL.
201 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
204 atomic_add_long(&pmp->inmem_chains, 1);
207 case HAMMER2_BREF_TYPE_VOLUME:
208 case HAMMER2_BREF_TYPE_FREEMAP:
210 panic("hammer2_chain_alloc volume type illegal for op");
213 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
219 chain->bytes = bytes;
221 chain->flags = HAMMER2_CHAIN_ALLOCATED;
222 chain->delete_tid = HAMMER2_MAX_TID;
225 * Set modify_tid if a transaction is creating the chain. When
226 * loading a chain from backing store modify_tid is left set to 0,
227 * which forces a delete-duplication.
230 chain->modify_tid = trans->sync_tid;
236 * Associate an existing core with the chain or allocate a new core.
238 * The core is not locked. No additional refs on the chain are made.
239 * (trans) must not be NULL if (core) is not NULL.
241 * When chains are delete-duplicated during flushes we insert nchain on
242 * the ownerq after ochain instead of at the end in order to give the
243 * drop code visibility in the correct order, otherwise drops can be missed.
246 hammer2_chain_core_alloc(hammer2_trans_t *trans,
247 hammer2_chain_t *nchain, hammer2_chain_t *ochain)
249 hammer2_chain_core_t *core;
251 KKASSERT(nchain->core == NULL);
253 if (ochain == NULL) {
255 * Fresh core under nchain (no multi-homing of ochain's
258 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
260 TAILQ_INIT(&core->layerq);
261 TAILQ_INIT(&core->ownerq);
265 ccms_cst_init(&core->cst, nchain);
266 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
269 * Propagate the PFSROOT flag which we set on all subdirs
270 * under the super-root.
272 atomic_set_int(&nchain->flags,
273 ochain->flags & HAMMER2_CHAIN_PFSROOT);
276 * Duplicating ochain -> nchain. Set the DUPLICATED flag on
277 * ochain if nchain is not a snapshot.
279 * It is possible for the DUPLICATED flag to already be
280 * set when called via a flush operation because flush
281 * operations may have to work on elements with delete_tid's
282 * beyond the flush sync_tid. In this situation we must
283 * ensure that nchain is placed just after ochain in the
284 * ownerq and that the DUPLICATED flag is set on nchain so
285 * 'live' operations skip past it to the correct chain.
287 * The flusher understands the blockref synchronization state
288 * for any stale chains by observing bref.mirror_tid, which
289 * delete-duplicate replicates.
291 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
292 KKASSERT(trans->flags & HAMMER2_TRANS_ISFLUSH);
293 atomic_set_int(&nchain->flags,
294 HAMMER2_CHAIN_DUPLICATED);
296 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
297 atomic_set_int(&ochain->flags,
298 HAMMER2_CHAIN_DUPLICATED);
301 atomic_add_int(&core->sharecnt, 1);
303 spin_lock(&core->cst.spin);
307 * Maintain ordering for refactor test so we don't skip over
308 * a snapshot. Also, during flushes, delete-duplications
309 * for block-table updates can occur on blocks already
310 * deleted (delete-duplicated by a later transaction). We
311 * must insert nchain after ochain but before the later
312 * transaction's copy.
314 TAILQ_INSERT_AFTER(&core->ownerq, ochain, nchain, core_entry);
316 spin_unlock(&core->cst.spin);
321 * Add a reference to a chain element, preventing its destruction.
324 hammer2_chain_ref(hammer2_chain_t *chain)
326 atomic_add_int(&chain->refs, 1);
330 * Insert the chain in the core rbtree at the first layer
331 * which accepts it (for now we don't sort layers by the transaction tid)
333 #define HAMMER2_CHAIN_INSERT_SPIN 0x0001
334 #define HAMMER2_CHAIN_INSERT_LIVE 0x0002
335 #define HAMMER2_CHAIN_INSERT_RACE 0x0004
339 hammer2_chain_insert(hammer2_chain_core_t *above, hammer2_chain_t *chain,
342 hammer2_chain_layer_t *layer;
343 hammer2_chain_t *xchain;
345 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
346 spin_lock(&above->cst.spin);
347 chain->above = above;
348 layer = TAILQ_FIRST(&above->layerq);
355 (xchain = RB_INSERT(hammer2_chain_tree,
356 &layer->rbtree, chain)) != NULL) {
358 * Either no layers have been allocated or the insertion
359 * failed. This is fatal if the conflicted xchain is not
360 * flagged as deleted. Caller may or may allow the failure.
362 if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
363 xchain && (xchain->flags & HAMMER2_CHAIN_DELETED) == 0) {
365 chain->inlayer = NULL;
366 kprintf("insertion race against %p\n", xchain);
371 * Allocate a new layer to resolve the issue.
373 spin_unlock(&above->cst.spin);
374 layer = kmalloc(sizeof(*layer), chain->hmp->mchain,
376 RB_INIT(&layer->rbtree);
377 layer->good = 0xABCD;
378 spin_lock(&above->cst.spin);
379 TAILQ_INSERT_HEAD(&above->layerq, layer, entry);
380 RB_INSERT(hammer2_chain_tree, &layer->rbtree, chain);
382 chain->inlayer = layer;
383 ++above->chain_count;
385 if ((flags & HAMMER2_CHAIN_INSERT_LIVE) &&
386 (chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
387 atomic_add_int(&above->live_count, 1);
389 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
391 if (flags & HAMMER2_CHAIN_INSERT_SPIN)
392 spin_unlock(&above->cst.spin);
396 * Drop the caller's reference to the chain. When the ref count drops to
397 * zero this function will disassociate the chain from its parent and
398 * deallocate it, then recursely drop the parent using the implied ref
399 * from the chain's chain->parent.
401 * WARNING! Just because we are able to deallocate a chain doesn't mean
402 * that chain->core->rbtree is empty. There can still be a sharecnt
403 * on chain->core and RBTREE entries that refer to different parents.
405 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
408 hammer2_chain_drop(hammer2_chain_t *chain)
413 if (chain->flags & HAMMER2_CHAIN_MOVED)
415 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
417 KKASSERT(chain->refs > need);
425 chain = hammer2_chain_lastdrop(chain);
427 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
429 /* retry the same chain */
435 * Safe handling of the 1->0 transition on chain. Returns a chain for
436 * recursive drop or NULL, possibly returning the same chain if the atomic
439 * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
443 hammer2_chain_lastdrop(hammer2_chain_t *chain)
445 hammer2_pfsmount_t *pmp;
446 hammer2_mount_t *hmp;
447 hammer2_chain_core_t *above;
448 hammer2_chain_core_t *core;
449 hammer2_chain_layer_t *layer;
450 hammer2_chain_t *rdrop1;
451 hammer2_chain_t *rdrop2;
454 * Spinlock the core and check to see if it is empty. If it is
455 * not empty we leave chain intact with refs == 0. The elements
456 * in core->rbtree are associated with other chains contemporary
457 * with ours but not with our chain directly.
459 if ((core = chain->core) != NULL) {
460 spin_lock(&core->cst.spin);
463 * We can't drop any chains if they have children because
464 * there might be a flush dependency.
466 * NOTE: We return (chain) on failure to retry.
468 if (core->chain_count) {
469 if (atomic_cmpset_int(&chain->refs, 1, 0))
470 chain = NULL; /* success */
471 spin_unlock(&core->cst.spin);
474 /* no chains left under us */
477 * We can't drop a live chain unless it is a the head
478 * of its ownerq. If we were to then the go-to chain
479 * would revert to the prior deleted chain.
481 if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
482 (chain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0 &&
483 TAILQ_FIRST(&core->ownerq) != chain) {
484 if (atomic_cmpset_int(&chain->refs, 1, 0))
485 chain = NULL; /* success */
486 spin_unlock(&core->cst.spin);
493 pmp = chain->pmp; /* can be NULL */
499 * Spinlock the parent and try to drop the last ref. On success
500 * remove chain from its parent, otherwise return NULL.
502 * (multiple spinlocks on core's are allowed in a bottom-up fashion).
504 if ((above = chain->above) != NULL) {
505 spin_lock(&above->cst.spin);
506 if (!atomic_cmpset_int(&chain->refs, 1, 0)) {
507 /* 1->0 transition failed */
508 spin_unlock(&above->cst.spin);
510 spin_unlock(&core->cst.spin);
511 return(chain); /* retry */
515 * 1->0 transition successful, remove chain from its
516 * above core. Track layer for removal/freeing.
518 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
519 layer = chain->inlayer;
520 RB_REMOVE(hammer2_chain_tree, &layer->rbtree, chain);
521 --above->chain_count;
522 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
524 chain->inlayer = NULL;
526 if (RB_EMPTY(&layer->rbtree) && layer->refs == 0) {
527 TAILQ_REMOVE(&above->layerq, layer, entry);
534 * If our chain was the last chain in the parent's core the
535 * core is now empty. Try to drop the first multi-homed
538 if (above->chain_count == 0) {
539 rdrop1 = TAILQ_FIRST(&above->ownerq);
541 atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
546 spin_unlock(&above->cst.spin);
547 above = NULL; /* safety */
551 * We still have the core spinlock (if core is non-NULL). The
552 * above spinlock is gone.
554 * Remove chain from ownerq. This may change the first element of
555 * ownerq to something we can remove.
560 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
561 rdrop2 = TAILQ_FIRST(&core->ownerq);
563 atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0) {
566 spin_unlock(&core->cst.spin);
569 * We can do the final 1->0 transition with an atomic op
570 * after releasing core's spinlock.
572 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
574 * On the 1->0 transition of core we can destroy
575 * it. Any remaining layers should no longer be
576 * referenced or visibile to other threads.
578 KKASSERT(TAILQ_EMPTY(&core->ownerq));
580 layer->good = 0xEF00;
581 kfree(layer, hmp->mchain);
583 while ((layer = TAILQ_FIRST(&core->layerq)) != NULL) {
584 KKASSERT(layer->refs == 0 &&
585 RB_EMPTY(&layer->rbtree));
586 TAILQ_REMOVE(&core->layerq, layer, entry);
587 layer->good = 0xEF01;
588 kfree(layer, hmp->mchain);
591 KKASSERT(core->cst.count == 0);
592 KKASSERT(core->cst.upgrade == 0);
594 kfree(core, hmp->mchain);
596 core = NULL; /* safety */
600 * All spin locks are gone, finish freeing stuff.
602 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
603 HAMMER2_CHAIN_MODIFIED)) == 0);
604 hammer2_chain_drop_data(chain, 1);
606 KKASSERT(chain->bp == NULL);
609 if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
610 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
611 kfree(chain, hmp->mchain);
613 atomic_add_long(&pmp->inmem_chains, -1);
614 hammer2_chain_memory_wakeup(pmp);
619 * Free saved empty layer and return chained drop.
622 layer->good = 0xEF02;
623 kfree(layer, hmp->mchain);
626 hammer2_chain_drop(rdrop2);
631 * On either last lock release or last drop
634 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
636 hammer2_mount_t *hmp = chain->hmp;
638 switch(chain->bref.type) {
639 case HAMMER2_BREF_TYPE_VOLUME:
640 case HAMMER2_BREF_TYPE_FREEMAP:
644 case HAMMER2_BREF_TYPE_INODE:
646 kfree(chain->data, hmp->mchain);
650 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
652 kfree(chain->data, hmp->mchain);
657 KKASSERT(chain->data == NULL);
663 * Ref and lock a chain element, acquiring its data with I/O if necessary,
664 * and specify how you would like the data to be resolved.
666 * Returns 0 on success or an error code if the data could not be acquired.
667 * The chain element is locked on return regardless of whether an error
670 * The lock is allowed to recurse, multiple locking ops will aggregate
671 * the requested resolve types. Once data is assigned it will not be
672 * removed until the last unlock.
674 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
675 * (typically used to avoid device/logical buffer
678 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
679 * the INITIAL-create state (indirect blocks only).
681 * Do not resolve data elements for DATA chains.
682 * (typically used to avoid device/logical buffer
685 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
687 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
688 * it will be locked exclusive.
690 * NOTE: Embedded elements (volume header, inodes) are always resolved
693 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
694 * element will instantiate and zero its buffer, and flush it on
697 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
698 * so as not to instantiate a device buffer, which could alias against
699 * a logical file buffer. However, if ALWAYS is specified the
700 * device buffer will be instantiated anyway.
702 * WARNING! If data must be fetched a shared lock will temporarily be
703 * upgraded to exclusive. However, a deadlock can occur if
704 * the caller owns more than one shared lock.
707 hammer2_chain_lock(hammer2_chain_t *chain, int how)
709 hammer2_mount_t *hmp;
710 hammer2_chain_core_t *core;
711 hammer2_blockref_t *bref;
722 * Ref and lock the element. Recursive locks are allowed.
724 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
725 hammer2_chain_ref(chain);
726 atomic_add_int(&chain->lockcnt, 1);
729 KKASSERT(hmp != NULL);
732 * Get the appropriate lock.
735 if (how & HAMMER2_RESOLVE_SHARED)
736 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
738 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
741 * If we already have a valid data pointer no further action is
748 * Do we have to resolve the data?
750 switch(how & HAMMER2_RESOLVE_MASK) {
751 case HAMMER2_RESOLVE_NEVER:
753 case HAMMER2_RESOLVE_MAYBE:
754 if (chain->flags & HAMMER2_CHAIN_INITIAL)
756 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
759 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
762 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
765 case HAMMER2_RESOLVE_ALWAYS:
770 * Upgrade to an exclusive lock so we can safely manipulate the
771 * buffer cache. If another thread got to it before us we
774 ostate = ccms_thread_lock_upgrade(&core->cst);
776 ccms_thread_lock_downgrade(&core->cst, ostate);
781 * We must resolve to a device buffer, either by issuing I/O or
782 * by creating a zero-fill element. We do not mark the buffer
783 * dirty when creating a zero-fill element (the hammer2_chain_modify()
784 * API must still be used to do that).
786 * The device buffer is variable-sized in powers of 2 down
787 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
788 * chunk always contains buffers of the same size. (XXX)
790 * The minimum physical IO size may be larger than the variable
795 psize = hammer2_devblksize(chain->bytes);
796 pmask = (hammer2_off_t)psize - 1;
797 pbase = bref->data_off & ~pmask;
798 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
799 KKASSERT(pbase != 0);
800 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
803 * The getblk() optimization can only be used on newly created
804 * elements if the physical block size matches the request.
806 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
807 chain->bytes == psize) {
808 chain->bp = getblk(hmp->devvp, pbase, psize, 0, 0);
810 } else if (hammer2_isclusterable(chain)) {
811 error = cluster_read(hmp->devvp, peof, pbase, psize,
812 psize, HAMMER2_PBUFSIZE*4,
814 adjreadcounter(&chain->bref, chain->bytes);
816 error = bread(hmp->devvp, pbase, psize, &chain->bp);
817 adjreadcounter(&chain->bref, chain->bytes);
821 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
822 (intmax_t)pbase, error);
825 ccms_thread_lock_downgrade(&core->cst, ostate);
830 * Zero the data area if the chain is in the INITIAL-create state.
831 * Mark the buffer for bdwrite(). This clears the INITIAL state
832 * but does not mark the chain modified.
834 bdata = (char *)chain->bp->b_data + boff;
835 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
836 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
837 bzero(bdata, chain->bytes);
838 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
842 * Setup the data pointer, either pointing it to an embedded data
843 * structure and copying the data from the buffer, or pointing it
846 * The buffer is not retained when copying to an embedded data
847 * structure in order to avoid potential deadlocks or recursions
848 * on the same physical buffer.
850 switch (bref->type) {
851 case HAMMER2_BREF_TYPE_VOLUME:
852 case HAMMER2_BREF_TYPE_FREEMAP:
854 * Copy data from bp to embedded buffer
856 panic("hammer2_chain_lock: called on unresolved volume header");
859 KKASSERT(pbase == 0);
860 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
861 bcopy(bdata, &hmp->voldata, chain->bytes);
862 chain->data = (void *)&hmp->voldata;
867 case HAMMER2_BREF_TYPE_INODE:
869 * Copy data from bp to embedded buffer, do not retain the
872 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
873 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
874 chain->data = kmalloc(sizeof(chain->data->ipdata),
875 hmp->mchain, M_WAITOK | M_ZERO);
876 bcopy(bdata, &chain->data->ipdata, chain->bytes);
880 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
881 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
882 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
883 chain->data = kmalloc(sizeof(chain->data->bmdata),
884 hmp->mchain, M_WAITOK | M_ZERO);
885 bcopy(bdata, &chain->data->bmdata, chain->bytes);
889 case HAMMER2_BREF_TYPE_INDIRECT:
890 case HAMMER2_BREF_TYPE_DATA:
891 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
894 * Point data at the device buffer and leave bp intact.
896 chain->data = (void *)bdata;
901 * Make sure the bp is not specifically owned by this thread before
902 * restoring to a possibly shared lock, so another hammer2 thread
906 BUF_KERNPROC(chain->bp);
907 ccms_thread_lock_downgrade(&core->cst, ostate);
912 * Asynchronously read the device buffer (dbp) and execute the specified
913 * callback. The caller should pass-in a locked chain (shared lock is ok).
914 * The function is responsible for unlocking the chain and for disposing
917 * NOTE! A NULL dbp (but non-NULL data) will be passed to the function
918 * if the dbp is integrated into the chain, because we do not want
919 * the caller to dispose of dbp in that situation.
921 static void hammer2_chain_load_async_callback(struct bio *bio);
924 hammer2_chain_load_async(hammer2_chain_t *chain,
925 void (*func)(hammer2_chain_t *, struct buf *, char *, void *),
928 hammer2_cbinfo_t *cbinfo;
929 hammer2_mount_t *hmp;
930 hammer2_blockref_t *bref;
940 func(chain, NULL, (char *)chain->data, arg);
945 * We must resolve to a device buffer, either by issuing I/O or
946 * by creating a zero-fill element. We do not mark the buffer
947 * dirty when creating a zero-fill element (the hammer2_chain_modify()
948 * API must still be used to do that).
950 * The device buffer is variable-sized in powers of 2 down
951 * to HAMMER2_MIN_ALLOC (typically 1K). A 64K physical storage
952 * chunk always contains buffers of the same size. (XXX)
954 * The minimum physical IO size may be larger than the variable
959 psize = hammer2_devblksize(chain->bytes);
960 pmask = (hammer2_off_t)psize - 1;
961 pbase = bref->data_off & ~pmask;
962 boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
963 KKASSERT(pbase != 0);
964 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
969 * The getblk() optimization can only be used on newly created
970 * elements if the physical block size matches the request.
972 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
973 chain->bytes == psize) {
974 dbp = getblk(hmp->devvp, pbase, psize, 0, 0);
975 /*atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);*/
976 bdata = (char *)dbp->b_data + boff;
977 bzero(bdata, chain->bytes);
978 /*atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);*/
979 func(chain, dbp, bdata, arg);
984 adjreadcounter(&chain->bref, chain->bytes);
985 cbinfo = kmalloc(sizeof(*cbinfo), hmp->mchain, M_INTWAIT | M_ZERO);
986 cbinfo->chain = chain;
991 cluster_readcb(hmp->devvp, peof, pbase, psize,
992 HAMMER2_PBUFSIZE*4, HAMMER2_PBUFSIZE*4,
993 hammer2_chain_load_async_callback, cbinfo);
997 hammer2_chain_load_async_callback(struct bio *bio)
999 hammer2_cbinfo_t *cbinfo;
1000 hammer2_mount_t *hmp;
1005 * Nobody is waiting for bio/dbp to complete, we are
1006 * responsible for handling the biowait() equivalent
1007 * on dbp which means clearing BIO_DONE and BIO_SYNC
1008 * and calling bpdone() if it hasn't already been called
1009 * to restore any covered holes in the buffer's backing
1013 if ((bio->bio_flags & BIO_DONE) == 0)
1015 bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
1018 * Extract the auxillary info and issue the callback.
1019 * Finish up with the dbp after it returns.
1021 cbinfo = bio->bio_caller_info1.ptr;
1022 /*ccms_thread_lock_setown(cbinfo->chain->core);*/
1023 data = dbp->b_data + cbinfo->boff;
1024 hmp = cbinfo->chain->hmp;
1026 cbinfo = bio->bio_caller_info1.ptr;
1027 if (cbinfo->chain->flags & HAMMER2_CHAIN_INITIAL)
1028 bzero(data, cbinfo->chain->bytes);
1029 cbinfo->func(cbinfo->chain, dbp, data, cbinfo->arg);
1030 /* cbinfo->chain is stale now */
1032 kfree(cbinfo, hmp->mchain);
1036 * Unlock and deref a chain element.
1038 * On the last lock release any non-embedded data (chain->bp) will be
1042 hammer2_chain_unlock(hammer2_chain_t *chain)
1044 hammer2_chain_core_t *core = chain->core;
1045 ccms_state_t ostate;
1050 * The core->cst lock can be shared across several chains so we
1051 * need to track the per-chain lockcnt separately.
1053 * If multiple locks are present (or being attempted) on this
1054 * particular chain we can just unlock, drop refs, and return.
1056 * Otherwise fall-through on the 1->0 transition.
1059 lockcnt = chain->lockcnt;
1060 KKASSERT(lockcnt > 0);
1063 if (atomic_cmpset_int(&chain->lockcnt,
1064 lockcnt, lockcnt - 1)) {
1065 ccms_thread_unlock(&core->cst);
1066 hammer2_chain_drop(chain);
1070 if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1077 * On the 1->0 transition we upgrade the core lock (if necessary)
1078 * to exclusive for terminal processing. If after upgrading we find
1079 * that lockcnt is non-zero, another thread is racing us and will
1080 * handle the unload for us later on, so just cleanup and return
1081 * leaving the data/bp intact
1083 * Otherwise if lockcnt is still 0 it is possible for it to become
1084 * non-zero and race, but since we hold the core->cst lock
1085 * exclusively all that will happen is that the chain will be
1086 * reloaded after we unload it.
1088 ostate = ccms_thread_lock_upgrade(&core->cst);
1089 if (chain->lockcnt) {
1090 ccms_thread_unlock_upgraded(&core->cst, ostate);
1091 hammer2_chain_drop(chain);
1096 * Shortcut the case if the data is embedded or not resolved.
1098 * Do NOT NULL out chain->data (e.g. inode data), it might be
1101 * The DIRTYBP flag is non-applicable in this situation and can
1102 * be cleared to keep the flags state clean.
1104 if (chain->bp == NULL) {
1105 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1106 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1107 hammer2_chain_drop_data(chain, 0);
1108 ccms_thread_unlock_upgraded(&core->cst, ostate);
1109 hammer2_chain_drop(chain);
1116 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
1118 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1119 switch(chain->bref.type) {
1120 case HAMMER2_BREF_TYPE_DATA:
1121 counterp = &hammer2_ioa_file_write;
1123 case HAMMER2_BREF_TYPE_INODE:
1124 counterp = &hammer2_ioa_meta_write;
1126 case HAMMER2_BREF_TYPE_INDIRECT:
1127 counterp = &hammer2_ioa_indr_write;
1129 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1130 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1131 counterp = &hammer2_ioa_fmap_write;
1134 counterp = &hammer2_ioa_volu_write;
1137 *counterp += chain->bytes;
1139 switch(chain->bref.type) {
1140 case HAMMER2_BREF_TYPE_DATA:
1141 counterp = &hammer2_iod_file_write;
1143 case HAMMER2_BREF_TYPE_INODE:
1144 counterp = &hammer2_iod_meta_write;
1146 case HAMMER2_BREF_TYPE_INDIRECT:
1147 counterp = &hammer2_iod_indr_write;
1149 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1150 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1151 counterp = &hammer2_iod_fmap_write;
1154 counterp = &hammer2_iod_volu_write;
1157 *counterp += chain->bytes;
1163 * If a device buffer was used for data be sure to destroy the
1164 * buffer when we are done to avoid aliases (XXX what about the
1165 * underlying VM pages?).
1167 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1172 * XXX our primary cache is now the block device, not
1173 * the logical file. don't release the buffer.
1175 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
1176 chain->bp->b_flags |= B_RELBUF;
1180 * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
1181 * or not. The flag will get re-set when chain_modify() is called,
1182 * even if MODIFIED is already set, allowing the OS to retire the
1183 * buffer independent of a hammer2 flus.
1186 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1187 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1188 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1189 atomic_clear_int(&chain->flags,
1190 HAMMER2_CHAIN_IOFLUSH);
1191 chain->bp->b_flags |= B_RELBUF;
1192 cluster_awrite(chain->bp);
1194 chain->bp->b_flags |= B_CLUSTEROK;
1198 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1199 atomic_clear_int(&chain->flags,
1200 HAMMER2_CHAIN_IOFLUSH);
1201 chain->bp->b_flags |= B_RELBUF;
1204 /* bp might still be dirty */
1209 ccms_thread_unlock_upgraded(&core->cst, ostate);
1210 hammer2_chain_drop(chain);
1214 * This counts the number of live blockrefs in a block array and
1215 * also calculates the point at which all remaining blockrefs are empty.
1217 * NOTE: Flag is not set until after the count is complete, allowing
1218 * callers to test the flag without holding the spinlock.
1220 * NOTE: If base is NULL the related chain is still in the INITIAL
1221 * state and there are no blockrefs to count.
1223 * NOTE: live_count may already have some counts accumulated due to
1224 * creation and deletion and could even be initially negative.
1227 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1228 hammer2_blockref_t *base, int count)
1230 hammer2_chain_core_t *core = chain->core;
1232 spin_lock(&core->cst.spin);
1233 if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1235 while (--count >= 0) {
1236 if (base[count].type)
1239 core->live_zero = count + 1;
1240 while (count >= 0) {
1241 if (base[count].type)
1242 atomic_add_int(&core->live_count, 1);
1246 core->live_zero = 0;
1248 /* else do not modify live_count */
1249 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1251 spin_unlock(&core->cst.spin);
1255 * Resize the chain's physical storage allocation in-place. This may
1256 * replace the passed-in chain with a new chain.
1258 * Chains can be resized smaller without reallocating the storage.
1259 * Resizing larger will reallocate the storage.
1261 * Must be passed an exclusively locked parent and chain, returns a new
1262 * exclusively locked chain at the same index and unlocks the old chain.
1263 * Flushes the buffer if necessary.
1265 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1266 * to avoid instantiating a device buffer that conflicts with the vnode
1267 * data buffer. That is, the passed-in bp is a logical buffer, whereas
1268 * any chain-oriented bp would be a device buffer.
1270 * XXX flags currently ignored, uses chain->bp to detect data/no-data.
1271 * XXX return error if cannot resize.
1274 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1275 hammer2_chain_t *parent, hammer2_chain_t **chainp,
1276 int nradix, int flags)
1278 hammer2_mount_t *hmp;
1279 hammer2_chain_t *chain;
1280 hammer2_off_t pbase;
1290 * Only data and indirect blocks can be resized for now.
1291 * (The volu root, inodes, and freemap elements use a fixed size).
1293 KKASSERT(chain != &hmp->vchain);
1294 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1295 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1298 * Nothing to do if the element is already the proper size
1300 obytes = chain->bytes;
1301 nbytes = 1U << nradix;
1302 if (obytes == nbytes)
1306 * Delete the old chain and duplicate it at the same (parent, index),
1307 * returning a new chain. This allows the old chain to still be
1308 * used by the flush code. The new chain will be returned in a
1311 * The parent does not have to be locked for the delete/duplicate call,
1312 * but is in this particular code path.
1314 * NOTE: If we are not crossing a synchronization point the
1315 * duplication code will simply reuse the existing chain
1318 hammer2_chain_delete_duplicate(trans, &chain, 0);
1321 * Relocate the block, even if making it smaller (because different
1322 * block sizes may be in different regions).
1324 hammer2_freemap_alloc(trans, chain->hmp, &chain->bref, nbytes);
1325 chain->bytes = nbytes;
1326 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1329 * The device buffer may be larger than the allocation size.
1331 bbytes = hammer2_devblksize(chain->bytes);
1332 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1333 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1336 * For now just support it on DATA chains (and not on indirect
1339 KKASSERT(chain->bp == NULL);
1342 * Make sure the chain is marked MOVED and propagate the update
1343 * to the root for flush.
1345 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1346 hammer2_chain_ref(chain);
1347 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1349 hammer2_chain_setsubmod(trans, chain);
1354 * Set a chain modified, making it read-write and duplicating it if necessary.
1355 * This function will assign a new physical block to the chain if necessary
1357 * Duplication of already-modified chains is possible when the modification
1358 * crosses a flush synchronization boundary.
1360 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1361 * level or the COW operation will not work.
1363 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
1364 * run the data through the device buffers.
1366 * This function may return a different chain than was passed, in which case
1367 * the old chain will be unlocked and the new chain will be locked.
1369 * ip->chain may be adjusted by hammer2_chain_modify_ip().
1371 hammer2_inode_data_t *
1372 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1373 hammer2_chain_t **chainp, int flags)
1375 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1376 hammer2_chain_modify(trans, chainp, flags);
1377 if (ip->chain != *chainp)
1378 hammer2_inode_repoint(ip, NULL, *chainp);
1380 vsetisdirty(ip->vp);
1381 return(&ip->chain->data->ipdata);
1385 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1388 hammer2_mount_t *hmp;
1389 hammer2_chain_t *chain;
1390 hammer2_off_t pbase;
1391 hammer2_off_t pmask;
1404 * Data must be resolved if already assigned unless explicitly
1405 * flagged otherwise.
1407 if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1408 (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1409 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1410 hammer2_chain_unlock(chain);
1414 * data is not optional for freemap chains (we must always be sure
1415 * to copy the data on COW storage allocations).
1417 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1418 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1419 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1420 (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1424 * Determine if a delete-duplicate is needed.
1426 * (a) Modify_tid is part of a prior flush
1427 * (b) Concurrent post-flush sync and modify_tid is part of current
1429 * (c) and chain is not in the initial state (freshly created)
1430 * (d) and caller didn't request an in-place modification.
1432 * The freemap and volume header special chains are never D-Dd.
1434 if ((chain->modify_tid <= hmp->last_flush_tid ||
1435 (trans->sync_tid > hmp->topo_flush_tid &&
1436 chain->modify_tid <= hmp->topo_flush_tid)) &&
1437 (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1438 (flags & HAMMER2_MODIFY_INPLACE) == 0) {
1439 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1440 KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1441 hammer2_chain_delete_duplicate(trans, chainp, 0);
1444 /* fall through if fchain or vchain */
1448 * Otherwise do initial-chain handling
1450 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1451 chain->bref.modify_tid = trans->sync_tid;
1453 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1454 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1455 hammer2_chain_ref(chain);
1457 chain->modify_tid = trans->sync_tid;
1460 * The modification or re-modification requires an allocation and
1463 * We normally always allocate new storage here. If storage exists
1464 * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1466 if (chain != &hmp->vchain &&
1467 chain != &hmp->fchain &&
1468 ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1469 (flags & HAMMER2_MODIFY_NOREALLOC) == 0 ||
1470 chain->modify_tid <= hmp->last_flush_tid ||
1471 (trans->sync_tid > hmp->topo_flush_tid &&
1472 chain->modify_tid <= hmp->topo_flush_tid))
1474 hammer2_freemap_alloc(trans, chain->hmp,
1475 &chain->bref, chain->bytes);
1476 /* XXX failed allocation */
1480 * Do not COW if OPTDATA is set. INITIAL flag remains unchanged.
1481 * (OPTDATA does not prevent [re]allocation of storage, only the
1482 * related copy-on-write op).
1484 if (flags & HAMMER2_MODIFY_OPTDATA)
1488 * Clearing the INITIAL flag (for indirect blocks) indicates that
1489 * we've processed the uninitialized storage allocation.
1491 * If this flag is already clear we are likely in a copy-on-write
1492 * situation but we have to be sure NOT to bzero the storage if
1493 * no data is present.
1495 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1496 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1503 * Instantiate data buffer and possibly execute COW operation
1505 switch(chain->bref.type) {
1506 case HAMMER2_BREF_TYPE_VOLUME:
1507 case HAMMER2_BREF_TYPE_FREEMAP:
1508 case HAMMER2_BREF_TYPE_INODE:
1509 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1511 * The data is embedded, no copy-on-write operation is
1514 KKASSERT(chain->bp == NULL);
1516 case HAMMER2_BREF_TYPE_DATA:
1517 case HAMMER2_BREF_TYPE_INDIRECT:
1518 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1520 * Perform the copy-on-write operation
1522 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1524 psize = hammer2_devblksize(chain->bytes);
1525 pmask = (hammer2_off_t)psize - 1;
1526 pbase = chain->bref.data_off & ~pmask;
1527 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1528 KKASSERT(pbase != 0);
1529 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1532 * The getblk() optimization can only be used if the
1533 * chain element size matches the physical block size.
1535 if (chain->bp && chain->bp->b_loffset == pbase) {
1538 } else if (chain->bytes == psize) {
1539 nbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1541 } else if (hammer2_isclusterable(chain)) {
1542 error = cluster_read(hmp->devvp, peof, pbase, psize,
1543 psize, HAMMER2_PBUFSIZE*4,
1545 adjreadcounter(&chain->bref, chain->bytes);
1547 error = bread(hmp->devvp, pbase, psize, &nbp);
1548 adjreadcounter(&chain->bref, chain->bytes);
1550 KKASSERT(error == 0);
1551 bdata = (char *)nbp->b_data + boff;
1554 * Copy or zero-fill on write depending on whether
1555 * chain->data exists or not. Retire the existing bp
1556 * based on the DIRTYBP flag. Set the DIRTYBP flag to
1557 * indicate that retirement of nbp should use bdwrite().
1560 KKASSERT(chain->bp != NULL);
1561 if (chain->data != bdata) {
1562 bcopy(chain->data, bdata, chain->bytes);
1564 } else if (wasinitial) {
1565 bzero(bdata, chain->bytes);
1568 * We have a problem. We were asked to COW but
1569 * we don't have any data to COW with!
1571 panic("hammer2_chain_modify: having a COW %p\n",
1574 if (chain->bp != nbp) {
1576 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1577 chain->bp->b_flags |= B_CLUSTEROK;
1580 chain->bp->b_flags |= B_RELBUF;
1585 BUF_KERNPROC(chain->bp);
1587 chain->data = bdata;
1588 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1591 panic("hammer2_chain_modify: illegal non-embedded type %d",
1597 hammer2_chain_setsubmod(trans, chain);
1601 * Mark the volume as having been modified. This short-cut version
1602 * does not have to lock the volume's chain, which allows the ioctl
1603 * code to make adjustments to connections without deadlocking. XXX
1605 * No ref is made on vchain when flagging it MODIFIED.
1608 hammer2_modify_volume(hammer2_mount_t *hmp)
1610 hammer2_voldata_lock(hmp);
1611 hammer2_voldata_unlock(hmp, 1);
1615 * This function returns the chain at the nearest key within the specified
1616 * range with the highest delete_tid. The core spinlock must be held on
1617 * call and the returned chain will be referenced but not locked.
1619 * The returned chain may or may not be in a deleted state. Note that
1620 * live chains have a delete_tid = MAX_TID.
1622 * This function will recurse through chain->rbtree as necessary and will
1623 * return a *key_nextp suitable for iteration. *key_nextp is only set if
1624 * the iteration value is less than the current value of *key_nextp.
1626 * The caller should use (*key_nextp) to calculate the actual range of
1627 * the returned element, which will be (key_beg to *key_nextp - 1), because
1628 * there might be another element which is superior to the returned element
1631 * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1632 * chains continue to be returned. On EOF (*key_nextp) may overflow since
1633 * it will wind up being (key_end + 1).
1635 struct hammer2_chain_find_info {
1636 hammer2_chain_t *best;
1637 hammer2_key_t key_beg;
1638 hammer2_key_t key_end;
1639 hammer2_key_t key_next;
1642 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1643 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1647 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1648 hammer2_key_t key_beg, hammer2_key_t key_end)
1650 struct hammer2_chain_find_info info;
1651 hammer2_chain_layer_t *layer;
1654 info.key_beg = key_beg;
1655 info.key_end = key_end;
1656 info.key_next = *key_nextp;
1658 KKASSERT(parent->core->good == 0x1234);
1659 TAILQ_FOREACH(layer, &parent->core->layerq, entry) {
1660 KKASSERT(layer->good == 0xABCD);
1661 RB_SCAN(hammer2_chain_tree, &layer->rbtree,
1662 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1665 *key_nextp = info.key_next;
1667 kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1668 parent, key_beg, key_end, *key_nextp);
1676 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1678 struct hammer2_chain_find_info *info = data;
1679 hammer2_key_t child_beg;
1680 hammer2_key_t child_end;
1682 child_beg = child->bref.key;
1683 child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1685 if (child_end < info->key_beg)
1687 if (child_beg > info->key_end)
1694 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1696 struct hammer2_chain_find_info *info = data;
1697 hammer2_chain_t *best;
1698 hammer2_key_t child_end;
1702 * Skip deleted chains which have been flushed (MOVED no longer set),
1703 * causes caller to check blockref array.
1705 if ((child->flags & (HAMMER2_CHAIN_DELETED | HAMMER2_CHAIN_MOVED)) ==
1706 HAMMER2_CHAIN_DELETED) {
1715 if ((best = info->best) == NULL) {
1717 * No previous best. Assign best
1720 } else if (best->bref.key <= info->key_beg &&
1721 child->bref.key <= info->key_beg) {
1723 * If our current best is flush with key_beg and child is
1724 * also flush with key_beg choose based on delete_tid.
1726 * key_next will automatically be limited to the smaller of
1727 * the two end-points.
1729 if (child->delete_tid > best->delete_tid)
1731 } else if (child->bref.key < best->bref.key) {
1733 * Child has a nearer key and best is not flush with key_beg.
1734 * Truncate key_next to the old best key iff it had a better
1738 if (best->delete_tid >= child->delete_tid &&
1739 (info->key_next > best->bref.key || info->key_next == 0))
1740 info->key_next = best->bref.key;
1741 } else if (child->bref.key == best->bref.key) {
1743 * If our current best is flush with the child then choose
1744 * based on delete_tid.
1746 * key_next will automatically be limited to the smaller of
1747 * the two end-points.
1749 if (child->delete_tid > best->delete_tid)
1753 * Keep the current best but truncate key_next to the child's
1754 * base iff the child has a higher delete_tid.
1756 * key_next will also automatically be limited to the smaller
1757 * of the two end-points (probably not necessary for this case
1758 * but we do it anyway).
1760 if (child->delete_tid >= best->delete_tid &&
1761 (info->key_next > child->bref.key || info->key_next == 0))
1762 info->key_next = child->bref.key;
1766 * Always truncate key_next based on child's end-of-range.
1768 child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1769 if (child_end && (info->key_next > child_end || info->key_next == 0))
1770 info->key_next = child_end;
1776 * Retrieve the specified chain from a media blockref, creating the
1777 * in-memory chain structure which reflects it. modify_tid will be
1778 * left 0 which forces any modifications to issue a delete-duplicate.
1780 * NULL is returned if the insertion races.
1782 * Caller must hold the parent locked shared or exclusive since we may
1783 * need the parent's bref array to find our block.
1786 hammer2_chain_get(hammer2_chain_t *parent, hammer2_blockref_t *bref)
1788 hammer2_mount_t *hmp = parent->hmp;
1789 hammer2_chain_core_t *above = parent->core;
1790 hammer2_chain_t *chain;
1793 * Allocate a chain structure representing the existing media
1794 * entry. Resulting chain has one ref and is not locked.
1796 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1797 hammer2_chain_core_alloc(NULL, chain, NULL);
1798 /* ref'd chain returned */
1801 * Link the chain into its parent. A spinlock is required to safely
1802 * access the RBTREE, and it is possible to collide with another
1803 * hammer2_chain_get() operation because the caller might only hold
1804 * a shared lock on the parent.
1806 KKASSERT(parent->refs > 0);
1807 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
1808 HAMMER2_CHAIN_INSERT_RACE);
1809 if ((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0) {
1810 kprintf("chain %p not on RBTREE\n", chain);
1811 hammer2_chain_drop(chain);
1816 * Return our new chain referenced but not locked.
1822 * Lookup initialization/completion API
1825 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1827 if (flags & HAMMER2_LOOKUP_SHARED) {
1828 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1829 HAMMER2_RESOLVE_SHARED);
1831 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1837 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1840 hammer2_chain_unlock(parent);
1845 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1847 hammer2_chain_t *oparent;
1848 hammer2_chain_t *bparent;
1849 hammer2_chain_t *nparent;
1850 hammer2_chain_core_t *above;
1853 above = oparent->above;
1855 spin_lock(&above->cst.spin);
1856 bparent = TAILQ_FIRST(&above->ownerq);
1857 hammer2_chain_ref(bparent);
1861 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1862 nparent = TAILQ_NEXT(nparent, core_entry);
1863 hammer2_chain_ref(nparent);
1864 spin_unlock(&above->cst.spin);
1867 * Be careful of order
1869 hammer2_chain_unlock(oparent);
1870 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1871 hammer2_chain_drop(bparent);
1874 * We might have raced a delete-duplicate.
1876 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1877 spin_lock(&above->cst.spin);
1878 if (nparent->flags & HAMMER2_CHAIN_DUPLICATED) {
1879 spin_unlock(&above->cst.spin);
1880 hammer2_chain_ref(nparent);
1881 hammer2_chain_unlock(nparent);
1883 spin_lock(&above->cst.spin);
1884 continue; /* retry */
1886 spin_unlock(&above->cst.spin);
1896 * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1897 * (*parentp) typically points to an inode but can also point to a related
1898 * indirect block and this function will recurse upwards and find the inode
1901 * (*parentp) must be exclusively locked and referenced and can be an inode
1902 * or an existing indirect block within the inode.
1904 * On return (*parentp) will be modified to point at the deepest parent chain
1905 * element encountered during the search, as a helper for an insertion or
1906 * deletion. The new (*parentp) will be locked and referenced and the old
1907 * will be unlocked and dereferenced (no change if they are both the same).
1909 * The matching chain will be returned exclusively locked. If NOLOCK is
1910 * requested the chain will be returned only referenced.
1912 * NULL is returned if no match was found, but (*parentp) will still
1913 * potentially be adjusted.
1915 * On return (*key_nextp) will point to an iterative value for key_beg.
1916 * (If NULL is returned (*key_nextp) is set to key_end).
1918 * This function will also recurse up the chain if the key is not within the
1919 * current parent's range. (*parentp) can never be set to NULL. An iteration
1920 * can simply allow (*parentp) to float inside the loop.
1922 * NOTE! chain->data is not always resolved. By default it will not be
1923 * resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF. Use
1924 * HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1925 * BREF_TYPE_DATA as the device buffer can alias the logical file
1929 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1930 hammer2_key_t key_beg, hammer2_key_t key_end,
1931 int *cache_indexp, int flags)
1933 hammer2_mount_t *hmp;
1934 hammer2_chain_t *parent;
1935 hammer2_chain_t *chain;
1936 hammer2_blockref_t *base;
1937 hammer2_blockref_t *bref;
1938 hammer2_blockref_t bcopy;
1939 hammer2_key_t scan_beg;
1940 hammer2_key_t scan_end;
1941 hammer2_chain_core_t *above;
1943 int how_always = HAMMER2_RESOLVE_ALWAYS;
1944 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1947 if (flags & HAMMER2_LOOKUP_ALWAYS) {
1948 how_maybe = how_always;
1949 how = HAMMER2_RESOLVE_ALWAYS;
1950 } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1951 how = HAMMER2_RESOLVE_NEVER;
1953 how = HAMMER2_RESOLVE_MAYBE;
1955 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1956 how_maybe |= HAMMER2_RESOLVE_SHARED;
1957 how_always |= HAMMER2_RESOLVE_SHARED;
1958 how |= HAMMER2_RESOLVE_SHARED;
1962 * Recurse (*parentp) upward if necessary until the parent completely
1963 * encloses the key range or we hit the inode.
1965 * This function handles races against the flusher doing a delete-
1966 * duplicate above us and re-homes the parent to the duplicate in
1967 * that case, otherwise we'd wind up recursing down a stale chain.
1972 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1973 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1974 scan_beg = parent->bref.key;
1975 scan_end = scan_beg +
1976 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1977 if (key_beg >= scan_beg && key_end <= scan_end)
1979 parent = hammer2_chain_getparent(parentp, how_maybe);
1984 * Locate the blockref array. Currently we do a fully associative
1985 * search through the array.
1987 switch(parent->bref.type) {
1988 case HAMMER2_BREF_TYPE_INODE:
1990 * Special shortcut for embedded data returns the inode
1991 * itself. Callers must detect this condition and access
1992 * the embedded data (the strategy code does this for us).
1994 * This is only applicable to regular files and softlinks.
1996 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1997 if (flags & HAMMER2_LOOKUP_NOLOCK)
1998 hammer2_chain_ref(parent);
2000 hammer2_chain_lock(parent, how_always);
2001 *key_nextp = key_end + 1;
2004 base = &parent->data->ipdata.u.blockset.blockref[0];
2005 count = HAMMER2_SET_COUNT;
2007 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2008 case HAMMER2_BREF_TYPE_INDIRECT:
2010 * Handle MATCHIND on the parent
2012 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2013 scan_beg = parent->bref.key;
2014 scan_end = scan_beg +
2015 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2016 if (key_beg == scan_beg && key_end == scan_end) {
2018 hammer2_chain_lock(chain, how_maybe);
2019 *key_nextp = scan_end + 1;
2024 * Optimize indirect blocks in the INITIAL state to avoid
2027 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2030 if (parent->data == NULL)
2031 panic("parent->data is NULL");
2032 base = &parent->data->npdata[0];
2034 count = parent->bytes / sizeof(hammer2_blockref_t);
2036 case HAMMER2_BREF_TYPE_VOLUME:
2037 base = &hmp->voldata.sroot_blockset.blockref[0];
2038 count = HAMMER2_SET_COUNT;
2040 case HAMMER2_BREF_TYPE_FREEMAP:
2041 base = &hmp->voldata.freemap_blockset.blockref[0];
2042 count = HAMMER2_SET_COUNT;
2045 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2047 base = NULL; /* safety */
2048 count = 0; /* safety */
2052 * Merged scan to find next candidate.
2054 * hammer2_base_*() functions require the above->live_* fields
2055 * to be synchronized.
2057 * We need to hold the spinlock to access the block array and RB tree
2058 * and to interlock chain creation.
2060 above = parent->core;
2061 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2062 hammer2_chain_countbrefs(parent, base, count);
2067 spin_lock(&above->cst.spin);
2068 chain = hammer2_combined_find(parent, base, count,
2069 cache_indexp, key_nextp,
2070 key_beg, key_end, &bref);
2073 * Exhausted parent chain, iterate.
2076 spin_unlock(&above->cst.spin);
2077 if (key_beg == key_end) /* short cut single-key case */
2079 return (hammer2_chain_next(parentp, NULL, key_nextp,
2081 cache_indexp, flags));
2085 * Selected from blockref or in-memory chain.
2087 if (chain == NULL) {
2089 spin_unlock(&above->cst.spin);
2090 chain = hammer2_chain_get(parent, &bcopy);
2091 if (chain == NULL) {
2092 kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2093 parent, key_beg, key_end);
2096 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2097 hammer2_chain_drop(chain);
2101 hammer2_chain_ref(chain);
2102 spin_unlock(&above->cst.spin);
2104 /* chain is referenced but not locked */
2107 * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2109 * NOTE: chain's key range is not relevant as there might be
2110 * one-offs within the range that are not deleted.
2112 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2113 hammer2_chain_drop(chain);
2114 key_beg = *key_nextp;
2115 if (key_beg == 0 || key_beg > key_end)
2121 * If the chain element is an indirect block it becomes the new
2122 * parent and we loop on it. We must maintain our top-down locks
2123 * to prevent the flusher from interfering (i.e. doing a
2124 * delete-duplicate and leaving us recursing down a deleted chain).
2126 * The parent always has to be locked with at least RESOLVE_MAYBE
2127 * so we can access its data. It might need a fixup if the caller
2128 * passed incompatible flags. Be careful not to cause a deadlock
2129 * as a data-load requires an exclusive lock.
2131 * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2132 * range is within the requested key range we return the indirect
2133 * block and do NOT loop. This is usually only used to acquire
2136 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2137 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2138 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2139 hammer2_chain_unlock(parent);
2140 *parentp = parent = chain;
2144 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2147 * All done, return the chain
2153 * After having issued a lookup we can iterate all matching keys.
2155 * If chain is non-NULL we continue the iteration from just after it's index.
2157 * If chain is NULL we assume the parent was exhausted and continue the
2158 * iteration at the next parent.
2160 * parent must be locked on entry and remains locked throughout. chain's
2161 * lock status must match flags. Chain is always at least referenced.
2163 * WARNING! The MATCHIND flag does not apply to this function.
2166 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2167 hammer2_key_t *key_nextp,
2168 hammer2_key_t key_beg, hammer2_key_t key_end,
2169 int *cache_indexp, int flags)
2171 hammer2_chain_t *parent;
2175 * Calculate locking flags for upward recursion.
2177 how_maybe = HAMMER2_RESOLVE_MAYBE;
2178 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2179 how_maybe |= HAMMER2_RESOLVE_SHARED;
2184 * Calculate the next index and recalculate the parent if necessary.
2187 key_beg = chain->bref.key +
2188 ((hammer2_key_t)1 << chain->bref.keybits);
2189 if (flags & HAMMER2_LOOKUP_NOLOCK)
2190 hammer2_chain_drop(chain);
2192 hammer2_chain_unlock(chain);
2195 * Any scan where the lookup returned degenerate data embedded
2196 * in the inode has an invalid index and must terminate.
2198 if (chain == parent)
2200 if (key_beg == 0 || key_beg > key_end)
2203 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2204 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2206 * We reached the end of the iteration.
2211 * Continue iteration with next parent unless the current
2212 * parent covers the range.
2214 key_beg = parent->bref.key +
2215 ((hammer2_key_t)1 << parent->bref.keybits);
2216 if (key_beg == 0 || key_beg > key_end)
2218 parent = hammer2_chain_getparent(parentp, how_maybe);
2224 return (hammer2_chain_lookup(parentp, key_nextp,
2226 cache_indexp, flags));
2230 * Create and return a new hammer2 system memory structure of the specified
2231 * key, type and size and insert it under (*parentp). This is a full
2232 * insertion, based on the supplied key/keybits, and may involve creating
2233 * indirect blocks and moving other chains around via delete/duplicate.
2235 * (*parentp) must be exclusive locked and may be replaced on return
2236 * depending on how much work the function had to do.
2238 * (*chainp) usually starts out NULL and returns the newly created chain,
2239 * but if the caller desires the caller may allocate a disconnected chain
2240 * and pass it in instead. (It is also possible for the caller to use
2241 * chain_duplicate() to create a disconnected chain, manipulate it, then
2242 * pass it into this function to insert it).
2244 * This function should NOT be used to insert INDIRECT blocks. It is
2245 * typically used to create/insert inodes and data blocks.
2247 * Caller must pass-in an exclusively locked parent the new chain is to
2248 * be inserted under, and optionally pass-in a disconnected, exclusively
2249 * locked chain to insert (else we create a new chain). The function will
2250 * adjust (*parentp) as necessary, create or connect the chain, and
2251 * return an exclusively locked chain in *chainp.
2254 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2255 hammer2_chain_t **chainp,
2256 hammer2_key_t key, int keybits, int type, size_t bytes)
2258 hammer2_mount_t *hmp;
2259 hammer2_chain_t *chain;
2260 hammer2_chain_t *parent = *parentp;
2261 hammer2_chain_core_t *above;
2262 hammer2_blockref_t *base;
2263 hammer2_blockref_t dummy;
2268 above = parent->core;
2269 KKASSERT(ccms_thread_lock_owned(&above->cst));
2273 if (chain == NULL) {
2275 * First allocate media space and construct the dummy bref,
2276 * then allocate the in-memory chain structure. Set the
2277 * INITIAL flag for fresh chains.
2279 bzero(&dummy, sizeof(dummy));
2282 dummy.keybits = keybits;
2283 dummy.data_off = hammer2_getradix(bytes);
2284 dummy.methods = parent->bref.methods;
2285 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2286 hammer2_chain_core_alloc(trans, chain, NULL);
2288 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2291 * Lock the chain manually, chain_lock will load the chain
2292 * which we do NOT want to do. (note: chain->refs is set
2293 * to 1 by chain_alloc() for us, but lockcnt is not).
2296 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2300 * We do NOT set INITIAL here (yet). INITIAL is only
2301 * used for indirect blocks.
2303 * Recalculate bytes to reflect the actual media block
2306 bytes = (hammer2_off_t)1 <<
2307 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2308 chain->bytes = bytes;
2311 case HAMMER2_BREF_TYPE_VOLUME:
2312 case HAMMER2_BREF_TYPE_FREEMAP:
2313 panic("hammer2_chain_create: called with volume type");
2315 case HAMMER2_BREF_TYPE_INODE:
2316 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2317 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2318 chain->data = kmalloc(sizeof(chain->data->ipdata),
2319 hmp->mchain, M_WAITOK | M_ZERO);
2321 case HAMMER2_BREF_TYPE_INDIRECT:
2322 panic("hammer2_chain_create: cannot be used to"
2323 "create indirect block");
2325 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2326 panic("hammer2_chain_create: cannot be used to"
2327 "create freemap root or node");
2329 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2330 KKASSERT(bytes == sizeof(chain->data->bmdata));
2331 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2332 chain->data = kmalloc(sizeof(chain->data->bmdata),
2333 hmp->mchain, M_WAITOK | M_ZERO);
2335 case HAMMER2_BREF_TYPE_DATA:
2337 /* leave chain->data NULL */
2338 KKASSERT(chain->data == NULL);
2343 * Potentially update the existing chain's key/keybits.
2345 * Do NOT mess with the current state of the INITIAL flag.
2347 chain->bref.key = key;
2348 chain->bref.keybits = keybits;
2349 KKASSERT(chain->above == NULL);
2353 * Calculate how many entries we have in the blockref array and
2354 * determine if an indirect block is required.
2357 above = parent->core;
2359 switch(parent->bref.type) {
2360 case HAMMER2_BREF_TYPE_INODE:
2361 KKASSERT((parent->data->ipdata.op_flags &
2362 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2363 KKASSERT(parent->data != NULL);
2364 base = &parent->data->ipdata.u.blockset.blockref[0];
2365 count = HAMMER2_SET_COUNT;
2367 case HAMMER2_BREF_TYPE_INDIRECT:
2368 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2369 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2372 base = &parent->data->npdata[0];
2373 count = parent->bytes / sizeof(hammer2_blockref_t);
2375 case HAMMER2_BREF_TYPE_VOLUME:
2376 KKASSERT(parent->data != NULL);
2377 base = &hmp->voldata.sroot_blockset.blockref[0];
2378 count = HAMMER2_SET_COUNT;
2380 case HAMMER2_BREF_TYPE_FREEMAP:
2381 KKASSERT(parent->data != NULL);
2382 base = &hmp->voldata.freemap_blockset.blockref[0];
2383 count = HAMMER2_SET_COUNT;
2386 panic("hammer2_chain_create: unrecognized blockref type: %d",
2394 * Make sure we've counted the brefs
2396 if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2397 hammer2_chain_countbrefs(parent, base, count);
2399 KKASSERT(above->live_count >= 0 && above->live_count <= count);
2402 * If no free blockref could be found we must create an indirect
2403 * block and move a number of blockrefs into it. With the parent
2404 * locked we can safely lock each child in order to delete+duplicate
2405 * it without causing a deadlock.
2407 * This may return the new indirect block or the old parent depending
2408 * on where the key falls. NULL is returned on error.
2410 if (above->live_count == count) {
2411 hammer2_chain_t *nparent;
2413 nparent = hammer2_chain_create_indirect(trans, parent,
2416 if (nparent == NULL) {
2418 hammer2_chain_drop(chain);
2422 if (parent != nparent) {
2423 hammer2_chain_unlock(parent);
2424 parent = *parentp = nparent;
2430 * Link the chain into its parent. Later on we will have to set
2431 * the MOVED bit in situations where we don't mark the new chain
2432 * as being modified.
2434 if (chain->above != NULL)
2435 panic("hammer2: hammer2_chain_create: chain already connected");
2436 KKASSERT(chain->above == NULL);
2437 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2438 hammer2_chain_insert(above, chain, HAMMER2_CHAIN_INSERT_SPIN |
2439 HAMMER2_CHAIN_INSERT_LIVE);
2443 * Mark the newly created chain modified.
2445 * Device buffers are not instantiated for DATA elements
2446 * as these are handled by logical buffers.
2448 * Indirect and freemap node indirect blocks are handled
2449 * by hammer2_chain_create_indirect() and not by this
2452 * Data for all other bref types is expected to be
2453 * instantiated (INODE, LEAF).
2455 switch(chain->bref.type) {
2456 case HAMMER2_BREF_TYPE_DATA:
2457 hammer2_chain_modify(trans, &chain,
2458 HAMMER2_MODIFY_OPTDATA |
2459 HAMMER2_MODIFY_ASSERTNOCOPY);
2461 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2462 case HAMMER2_BREF_TYPE_INODE:
2463 hammer2_chain_modify(trans, &chain,
2464 HAMMER2_MODIFY_ASSERTNOCOPY);
2468 * Remaining types are not supported by this function.
2469 * In particular, INDIRECT and LEAF_NODE types are
2470 * handled by create_indirect().
2472 panic("hammer2_chain_create: bad type: %d",
2479 * When reconnecting a chain we must set MOVED and setsubmod
2480 * so the flush recognizes that it must update the bref in
2483 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2484 hammer2_chain_ref(chain);
2485 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2487 hammer2_chain_setsubmod(trans, chain);
2497 * Replace (*chainp) with a duplicate. The original *chainp is unlocked
2498 * and the replacement will be returned locked. Both the original and the
2499 * new chain will share the same RBTREE (have the same chain->core), with
2500 * the new chain becoming the 'current' chain (meaning it is the first in
2501 * the linked list at core->chain_first).
2503 * If (parent) is non-NULL then the new duplicated chain is inserted under
2506 * If (parent) is NULL then the new duplicated chain is not inserted anywhere,
2507 * similar to if it had just been chain_alloc()'d (suitable for passing into
2508 * hammer2_chain_create() after this function returns).
2510 * NOTE! Duplication is used in order to retain the original topology to
2511 * support flush synchronization points. Both the original and the
2512 * new chain will have the same transaction id and thus the operation
2513 * appears atomic w/regards to media flushes.
2515 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2516 hammer2_chain_t *nchain);
2519 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2520 hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2523 hammer2_mount_t *hmp;
2524 hammer2_blockref_t *base;
2525 hammer2_chain_t *parent;
2526 hammer2_chain_t *ochain;
2527 hammer2_chain_t *nchain;
2528 hammer2_chain_core_t *above;
2534 * First create a duplicate of the chain structure, associating
2535 * it with the same core, making it the same size, pointing it
2536 * to the same bref (the same media block).
2541 bref = &ochain->bref;
2543 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2544 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2546 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2548 hammer2_chain_core_alloc(trans, nchain, ochain);
2549 bytes = (hammer2_off_t)1 <<
2550 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2551 nchain->bytes = bytes;
2552 nchain->modify_tid = ochain->modify_tid;
2555 * Fixup (copy) any embedded data. Non-embedded data relies on the
2558 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2559 HAMMER2_RESOLVE_NOREF);
2560 hammer2_chain_dup_fixup(ochain, nchain);
2561 /* nchain has 1 ref */
2564 * If parent is not NULL, insert the duplicated chain into the
2565 * parent. The newly duplicated chain must be marked MOVED and
2566 * update_tid set in its parent(s).
2568 * Having both chains locked is extremely important for atomicy.
2570 if (parentp && (parent = *parentp) != NULL) {
2572 * Locate a free blockref in the parent's array
2574 above = parent->core;
2575 KKASSERT(ccms_thread_lock_owned(&above->cst));
2577 switch(parent->bref.type) {
2578 case HAMMER2_BREF_TYPE_INODE:
2579 KKASSERT((parent->data->ipdata.op_flags &
2580 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2581 KKASSERT(parent->data != NULL);
2582 base = &parent->data->ipdata.u.blockset.blockref[0];
2583 count = HAMMER2_SET_COUNT;
2585 case HAMMER2_BREF_TYPE_INDIRECT:
2586 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2587 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2590 KKASSERT(parent->data != NULL);
2591 base = &parent->data->npdata[0];
2593 count = parent->bytes / sizeof(hammer2_blockref_t);
2595 case HAMMER2_BREF_TYPE_VOLUME:
2596 KKASSERT(parent->data != NULL);
2597 base = &hmp->voldata.sroot_blockset.blockref[0];
2598 count = HAMMER2_SET_COUNT;
2600 case HAMMER2_BREF_TYPE_FREEMAP:
2601 KKASSERT(parent->data != NULL);
2602 base = &hmp->voldata.freemap_blockset.blockref[0];
2603 count = HAMMER2_SET_COUNT;
2606 panic("hammer2_chain_create: unrecognized "
2607 "blockref type: %d",
2613 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2614 KKASSERT(parent->refs > 0);
2616 hammer2_chain_create(trans, parentp, &nchain,
2617 nchain->bref.key, nchain->bref.keybits,
2618 nchain->bref.type, nchain->bytes);
2621 hammer2_chain_insert(above, nchain, HAMMER2_CHAIN_INSERT_SPIN |
2622 HAMMER2_CHAIN_INSERT_LIVE);
2625 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2626 hammer2_chain_ref(nchain);
2627 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2629 hammer2_chain_setsubmod(trans, nchain);
2633 * We have to unlock ochain before we can mark nchain modified to
2634 * avoid deadlocking due to the media blocks currently being the
2637 * Assert that (data == NULL) to catch any extra locks that might
2638 * have been present. Extra locks are not allowed.
2640 oflags = ochain->flags;
2641 hammer2_chain_unlock(ochain);
2642 KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2643 ochain->data == NULL);
2645 if (oflags & HAMMER2_CHAIN_INITIAL)
2646 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2649 * WARNING! We should never resolve DATA to device buffers
2650 * (XXX allow it if the caller did?), and since
2651 * we currently do not have the logical buffer cache
2652 * buffer in-hand to fix its cached physical offset
2653 * we also force the modify code to not COW it. XXX
2655 * WARNING! nchain should have only one manual ref plus additional
2656 * refs related to flags or the hammer2_chain_modify()
2657 * replacement could leave a ref hanging.
2659 if (oflags & HAMMER2_CHAIN_MODIFIED) {
2660 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2661 hammer2_chain_modify(trans, &nchain,
2662 HAMMER2_MODIFY_OPTDATA |
2663 HAMMER2_MODIFY_NOREALLOC |
2664 HAMMER2_MODIFY_INPLACE);
2665 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2666 hammer2_chain_modify(trans, &nchain,
2667 HAMMER2_MODIFY_OPTDATA |
2668 HAMMER2_MODIFY_INPLACE);
2670 hammer2_chain_modify(trans, &nchain,
2671 HAMMER2_MODIFY_INPLACE);
2674 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2676 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2679 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_ALWAYS);
2680 hammer2_chain_unlock(nchain);
2683 spin_lock(&nchain->core->cst.spin);
2684 if (nchain->core->update_tid < trans->sync_tid)
2685 nchain->core->update_tid = trans->sync_tid;
2686 spin_unlock(&nchain->core->cst.spin);
2691 * Special in-place delete-duplicate sequence which does not require a
2692 * locked parent. (*chainp) is marked DELETED and atomically replaced
2693 * with a duplicate. Atomicy is at the very-fine spin-lock level in
2694 * order to ensure that lookups do not race us.
2696 * If the input chain is already marked deleted the duplicated chain will
2697 * also be marked deleted. This case can occur when an inode is removed
2698 * from the filesystem but programs still have an open descriptor to it.
2701 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2704 hammer2_mount_t *hmp;
2705 hammer2_chain_t *ochain;
2706 hammer2_chain_t *nchain;
2707 hammer2_chain_core_t *above;
2712 oflags = ochain->flags;
2717 * Shortcut DELETED case if possible (only if delete_tid already
2718 * matches the transaction id).
2720 if ((oflags & HAMMER2_CHAIN_DELETED) &&
2721 ochain->delete_tid == trans->sync_tid) {
2727 * First create a duplicate of the chain structure.
2728 * (nchain is allocated with one ref).
2730 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
2731 if (flags & HAMMER2_DELDUP_RECORE)
2732 hammer2_chain_core_alloc(trans, nchain, NULL);
2734 hammer2_chain_core_alloc(trans, nchain, ochain);
2735 above = ochain->above;
2737 bytes = (hammer2_off_t)1 <<
2738 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2739 nchain->bytes = bytes;
2740 nchain->modify_tid = trans->sync_tid;
2741 nchain->data_count += ochain->data_count;
2742 nchain->inode_count += ochain->inode_count;
2745 * Lock nchain so both chains are now locked (extremely important
2746 * for atomicy). Mark ochain deleted and reinsert into the topology
2747 * and insert nchain all in one go.
2749 * If the ochain is already deleted it is left alone and nchain
2750 * is inserted into the topology as a deleted chain. This is
2751 * important because it allows ongoing operations to be executed
2752 * on a deleted inode which still has open descriptors.
2754 * The deleted case can also occur when a flush delete-duplicates
2755 * a node which is being concurrently modified by ongoing operations
2756 * in a later transaction. This creates a problem because the flush
2757 * is intended to update blockrefs which then propagate, allowing
2758 * the original covering in-memory chains to be freed up. In this
2759 * situation the flush code does NOT free the original covering
2760 * chains and will re-apply them to successive copies.
2762 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2763 hammer2_chain_dup_fixup(ochain, nchain);
2764 /* extra ref still present from original allocation */
2766 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2767 spin_lock(&above->cst.spin);
2768 KKASSERT(ochain->flags & HAMMER2_CHAIN_ONRBTREE);
2770 if (oflags & HAMMER2_CHAIN_DELETED) {
2771 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
2772 nchain->delete_tid = trans->sync_tid;
2773 /*nchain->delete_gen = ++trans->delete_gen;*/
2774 hammer2_chain_insert(above, nchain, 0);
2776 ochain->delete_tid = trans->sync_tid;
2777 /*ochain->delete_gen = ++trans->delete_gen;*/
2778 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2779 atomic_add_int(&above->live_count, -1);
2780 hammer2_chain_insert(above, nchain, HAMMER2_CHAIN_INSERT_LIVE);
2783 if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2784 hammer2_chain_ref(ochain);
2785 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2787 spin_unlock(&above->cst.spin);
2790 * ochain must be unlocked because ochain and nchain might share
2791 * a buffer cache buffer. Assert that there's no buffer.
2793 hammer2_chain_unlock(ochain);
2794 KKASSERT(ochain->bp == NULL);
2799 if (oflags & HAMMER2_CHAIN_INITIAL)
2800 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2803 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2804 hammer2_chain_modify(trans, &nchain,
2805 HAMMER2_MODIFY_OPTDATA |
2806 HAMMER2_MODIFY_NOREALLOC |
2807 HAMMER2_MODIFY_INPLACE);
2808 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2809 hammer2_chain_modify(trans, &nchain,
2810 HAMMER2_MODIFY_OPTDATA |
2811 HAMMER2_MODIFY_INPLACE);
2813 hammer2_chain_modify(trans, &nchain,
2814 HAMMER2_MODIFY_INPLACE);
2816 hammer2_chain_drop(nchain);
2819 * Unconditionally set the MOVED and update_tid bit to force
2820 * update of parent bref and indirect blockrefs during flush.
2822 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2823 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2824 hammer2_chain_ref(nchain);
2826 spin_lock(&nchain->core->cst.spin);
2827 if (nchain->core->update_tid < trans->sync_tid)
2828 nchain->core->update_tid = trans->sync_tid;
2829 spin_unlock(&nchain->core->cst.spin);
2830 hammer2_chain_setsubmod(trans, nchain);
2835 * Helper function to fixup inodes. The caller procedure stack may hold
2836 * multiple locks on ochain if it represents an inode, preventing our
2837 * unlock from retiring its state to the buffer cache.
2839 * In this situation any attempt to access the buffer cache could result
2840 * either in stale data or a deadlock. Work around the problem by copying
2841 * the embedded data directly.
2845 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
2847 if (ochain->data == NULL)
2849 switch(ochain->bref.type) {
2850 case HAMMER2_BREF_TYPE_INODE:
2851 KKASSERT(nchain->data == NULL);
2852 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2853 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2854 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2855 nchain->data->ipdata = ochain->data->ipdata;
2857 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2858 KKASSERT(nchain->data == NULL);
2859 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2860 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
2861 ochain->hmp->mchain, M_WAITOK | M_ZERO);
2862 bcopy(ochain->data->bmdata,
2863 nchain->data->bmdata,
2864 sizeof(nchain->data->bmdata));
2872 * Create a snapshot of the specified {parent, ochain} with the specified
2873 * label. The originating hammer2_inode must be exclusively locked for
2876 * The ioctl code has already synced the filesystem.
2879 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
2880 hammer2_ioc_pfs_t *pfs)
2882 hammer2_mount_t *hmp;
2883 hammer2_chain_t *ochain = *ochainp;
2884 hammer2_chain_t *nchain;
2885 hammer2_inode_data_t *ipdata;
2886 hammer2_inode_t *nip;
2893 kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
2894 pfs->name, ochain->refs, ochain->flags);
2896 name_len = strlen(pfs->name);
2897 lhc = hammer2_dirhash(pfs->name, name_len);
2900 opfs_clid = ochain->data->ipdata.pfs_clid;
2901 KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2906 * Create the snapshot directory under the super-root
2908 * Set PFS type, generate a unique filesystem id, and generate
2909 * a cluster id. Use the same clid when snapshotting a PFS root,
2910 * which theoretically allows the snapshot to be used as part of
2911 * the same cluster (perhaps as a cache).
2913 * Copy the (flushed) ochain's blockref array. Theoretically we
2914 * could use chain_duplicate() but it becomes difficult to disentangle
2915 * the shared core so for now just brute-force it.
2921 nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
2922 pfs->name, name_len, &nchain, &error);
2925 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
2926 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2927 kern_uuidgen(&ipdata->pfs_fsid, 1);
2928 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
2929 ipdata->pfs_clid = opfs_clid;
2931 kern_uuidgen(&ipdata->pfs_clid, 1);
2932 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
2933 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
2935 hammer2_inode_unlock_ex(nip, nchain);
2941 * Create an indirect block that covers one or more of the elements in the
2942 * current parent. Either returns the existing parent with no locking or
2943 * ref changes or returns the new indirect block locked and referenced
2944 * and leaving the original parent lock/ref intact as well.
2946 * If an error occurs, NULL is returned and *errorp is set to the error.
2948 * The returned chain depends on where the specified key falls.
2950 * The key/keybits for the indirect mode only needs to follow three rules:
2952 * (1) That all elements underneath it fit within its key space and
2954 * (2) That all elements outside it are outside its key space.
2956 * (3) When creating the new indirect block any elements in the current
2957 * parent that fit within the new indirect block's keyspace must be
2958 * moved into the new indirect block.
2960 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2961 * keyspace the the current parent, but lookup/iteration rules will
2962 * ensure (and must ensure) that rule (2) for all parents leading up
2963 * to the nearest inode or the root volume header is adhered to. This
2964 * is accomplished by always recursing through matching keyspaces in
2965 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2967 * The current implementation calculates the current worst-case keyspace by
2968 * iterating the current parent and then divides it into two halves, choosing
2969 * whichever half has the most elements (not necessarily the half containing
2970 * the requested key).
2972 * We can also opt to use the half with the least number of elements. This
2973 * causes lower-numbered keys (aka logical file offsets) to recurse through
2974 * fewer indirect blocks and higher-numbered keys to recurse through more.
2975 * This also has the risk of not moving enough elements to the new indirect
2976 * block and being forced to create several indirect blocks before the element
2979 * Must be called with an exclusively locked parent.
2981 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2982 hammer2_key_t *keyp, int keybits,
2983 hammer2_blockref_t *base, int count);
2984 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2985 hammer2_key_t *keyp, int keybits,
2986 hammer2_blockref_t *base, int count);
2989 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2990 hammer2_key_t create_key, int create_bits,
2991 int for_type, int *errorp)
2993 hammer2_mount_t *hmp;
2994 hammer2_chain_core_t *above;
2995 hammer2_chain_core_t *icore;
2996 hammer2_blockref_t *base;
2997 hammer2_blockref_t *bref;
2998 hammer2_blockref_t bcopy;
2999 hammer2_chain_t *chain;
3000 hammer2_chain_t *ichain;
3001 hammer2_chain_t dummy;
3002 hammer2_key_t key = create_key;
3003 hammer2_key_t key_beg;
3004 hammer2_key_t key_end;
3005 hammer2_key_t key_next;
3006 int keybits = create_bits;
3013 * Calculate the base blockref pointer or NULL if the chain
3014 * is known to be empty. We need to calculate the array count
3015 * for RB lookups either way.
3019 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3020 above = parent->core;
3022 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3023 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3026 switch(parent->bref.type) {
3027 case HAMMER2_BREF_TYPE_INODE:
3028 count = HAMMER2_SET_COUNT;
3030 case HAMMER2_BREF_TYPE_INDIRECT:
3031 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3032 count = parent->bytes / sizeof(hammer2_blockref_t);
3034 case HAMMER2_BREF_TYPE_VOLUME:
3035 count = HAMMER2_SET_COUNT;
3037 case HAMMER2_BREF_TYPE_FREEMAP:
3038 count = HAMMER2_SET_COUNT;
3041 panic("hammer2_chain_create_indirect: "
3042 "unrecognized blockref type: %d",
3048 switch(parent->bref.type) {
3049 case HAMMER2_BREF_TYPE_INODE:
3050 base = &parent->data->ipdata.u.blockset.blockref[0];
3051 count = HAMMER2_SET_COUNT;
3053 case HAMMER2_BREF_TYPE_INDIRECT:
3054 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3055 base = &parent->data->npdata[0];
3056 count = parent->bytes / sizeof(hammer2_blockref_t);
3058 case HAMMER2_BREF_TYPE_VOLUME:
3059 base = &hmp->voldata.sroot_blockset.blockref[0];
3060 count = HAMMER2_SET_COUNT;
3062 case HAMMER2_BREF_TYPE_FREEMAP:
3063 base = &hmp->voldata.freemap_blockset.blockref[0];
3064 count = HAMMER2_SET_COUNT;
3067 panic("hammer2_chain_create_indirect: "
3068 "unrecognized blockref type: %d",
3076 * dummy used in later chain allocation (no longer used for lookups).
3078 bzero(&dummy, sizeof(dummy));
3079 dummy.delete_tid = HAMMER2_MAX_TID;
3082 * When creating an indirect block for a freemap node or leaf
3083 * the key/keybits must be fitted to static radix levels because
3084 * particular radix levels use particular reserved blocks in the
3087 * This routine calculates the key/radix of the indirect block
3088 * we need to create, and whether it is on the high-side or the
3091 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3092 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3093 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3096 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3101 * Normalize the key for the radix being represented, keeping the
3102 * high bits and throwing away the low bits.
3104 key &= ~(((hammer2_key_t)1 << keybits) - 1);
3107 * How big should our new indirect block be? It has to be at least
3108 * as large as its parent.
3110 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3111 nbytes = HAMMER2_IND_BYTES_MIN;
3113 nbytes = HAMMER2_IND_BYTES_MAX;
3114 if (nbytes < count * sizeof(hammer2_blockref_t))
3115 nbytes = count * sizeof(hammer2_blockref_t);
3118 * Ok, create our new indirect block
3120 if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3121 for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3122 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3124 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3126 dummy.bref.key = key;
3127 dummy.bref.keybits = keybits;
3128 dummy.bref.data_off = hammer2_getradix(nbytes);
3129 dummy.bref.methods = parent->bref.methods;
3131 ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3132 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3133 hammer2_chain_core_alloc(trans, ichain, NULL);
3134 icore = ichain->core;
3135 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3136 hammer2_chain_drop(ichain); /* excess ref from alloc */
3139 * We have to mark it modified to allocate its block, but use
3140 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
3141 * it won't be acted upon by the flush code.
3143 * XXX leave the node unmodified, depend on the update_tid
3144 * flush to assign and modify parent blocks.
3146 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3149 * Iterate the original parent and move the matching brefs into
3150 * the new indirect block.
3152 * XXX handle flushes.
3155 key_end = HAMMER2_MAX_KEY;
3157 spin_lock(&above->cst.spin);
3161 if (++loops > 8192) {
3162 spin_unlock(&above->cst.spin);
3163 panic("shit parent=%p base/count %p:%d\n",
3164 parent, base, count);
3168 * NOTE: spinlock stays intact, returned chain (if not NULL)
3169 * is not referenced or locked.
3171 chain = hammer2_combined_find(parent, base, count,
3172 &cache_index, &key_next,
3177 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3178 if (key_next == 0 || key_next > key_end)
3185 * Use the full live (not deleted) element for the scan
3186 * iteration. HAMMER2 does not allow partial replacements.
3188 * XXX should be built into hammer2_combined_find().
3190 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3193 * Skip keys that are not within the key/radix of the new
3194 * indirect block. They stay in the parent.
3196 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3197 (key ^ bref->key)) != 0) {
3198 if (key_next == 0 || key_next > key_end)
3205 * Load the new indirect block by acquiring or allocating
3206 * the related chain, then move it to the new parent (ichain)
3207 * via DELETE-DUPLICATE.
3209 * WARNING! above->cst.spin must be held when parent is
3210 * modified, even though we own the full blown lock,
3211 * to deal with setsubmod and rename races.
3212 * (XXX remove this req).
3216 * Use chain already present in the RBTREE
3218 hammer2_chain_ref(chain);
3219 spin_unlock(&above->cst.spin);
3220 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3221 HAMMER2_RESOLVE_NOREF);
3224 * Get chain for blockref element. _get returns NULL
3225 * on insertion race.
3228 spin_unlock(&above->cst.spin);
3229 chain = hammer2_chain_get(parent, bref);
3232 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3233 hammer2_chain_drop(chain);
3236 hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3237 HAMMER2_RESOLVE_NOREF);
3239 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
3240 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0);
3241 hammer2_chain_unlock(chain);
3242 KKASSERT(parent->refs > 0);
3244 spin_lock(&above->cst.spin);
3245 if (key_next == 0 || key_next > key_end)
3249 spin_unlock(&above->cst.spin);
3252 * Insert the new indirect block into the parent now that we've
3253 * cleared out some entries in the parent. We calculated a good
3254 * insertion index in the loop above (ichain->index).
3256 * We don't have to set MOVED here because we mark ichain modified
3257 * down below (so the normal modified -> flush -> set-moved sequence
3260 * The insertion shouldn't race as this is a completely new block
3261 * and the parent is locked.
3263 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3264 hammer2_chain_insert(above, ichain, HAMMER2_CHAIN_INSERT_SPIN |
3265 HAMMER2_CHAIN_INSERT_LIVE);
3268 * Mark the new indirect block modified after insertion, which
3269 * will propagate up through parent all the way to the root and
3270 * also allocate the physical block in ichain for our caller,
3271 * and assign ichain->data to a pre-zero'd space (because there
3272 * is not prior data to copy into it).
3274 * We have to set update_tid in ichain's flags manually so the
3275 * flusher knows it has to recurse through it to get to all of
3276 * our moved blocks, then call setsubmod() to set the bit
3279 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3280 spin_lock(&ichain->core->cst.spin);
3281 if (ichain->core->update_tid < trans->sync_tid)
3282 ichain->core->update_tid = trans->sync_tid;
3283 spin_unlock(&ichain->core->cst.spin);
3284 hammer2_chain_setsubmod(trans, ichain);
3287 * Figure out what to return.
3289 if (~(((hammer2_key_t)1 << keybits) - 1) &
3290 (create_key ^ key)) {
3292 * Key being created is outside the key range,
3293 * return the original parent.
3295 hammer2_chain_unlock(ichain);
3298 * Otherwise its in the range, return the new parent.
3299 * (leave both the new and old parent locked).
3308 * Calculate the keybits and highside/lowside of the freemap node the
3309 * caller is creating.
3311 * This routine will specify the next higher-level freemap key/radix
3312 * representing the lowest-ordered set. By doing so, eventually all
3313 * low-ordered sets will be moved one level down.
3315 * We have to be careful here because the freemap reserves a limited
3316 * number of blocks for a limited number of levels. So we can't just
3317 * push indiscriminately.
3320 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3321 int keybits, hammer2_blockref_t *base, int count)
3323 hammer2_chain_core_t *above;
3324 hammer2_chain_t *chain;
3325 hammer2_blockref_t *bref;
3327 hammer2_key_t key_beg;
3328 hammer2_key_t key_end;
3329 hammer2_key_t key_next;
3336 above = parent->core;
3342 * Calculate the range of keys in the array being careful to skip
3343 * slots which are overridden with a deletion.
3346 key_end = HAMMER2_MAX_KEY;
3348 spin_lock(&above->cst.spin);
3351 if (++loops == 100000) {
3352 panic("indkey_freemap shit %p %p:%d\n",
3353 parent, base, count);
3355 chain = hammer2_combined_find(parent, base, count,
3356 &cache_index, &key_next,
3357 key_beg, key_end, &bref);
3364 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3365 if (key_next == 0 || key_next > key_end)
3372 * Use the full live (not deleted) element for the scan
3373 * iteration. HAMMER2 does not allow partial replacements.
3375 * XXX should be built into hammer2_combined_find().
3377 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3379 if (keybits > bref->keybits) {
3381 keybits = bref->keybits;
3382 } else if (keybits == bref->keybits && bref->key < key) {
3389 spin_unlock(&above->cst.spin);
3392 * Return the keybits for a higher-level FREEMAP_NODE covering
3396 case HAMMER2_FREEMAP_LEVEL0_RADIX:
3397 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3399 case HAMMER2_FREEMAP_LEVEL1_RADIX:
3400 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3402 case HAMMER2_FREEMAP_LEVEL2_RADIX:
3403 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3405 case HAMMER2_FREEMAP_LEVEL3_RADIX:
3406 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3408 case HAMMER2_FREEMAP_LEVEL4_RADIX:
3409 panic("hammer2_chain_indkey_freemap: level too high");
3412 panic("hammer2_chain_indkey_freemap: bad radix");
3421 * Calculate the keybits and highside/lowside of the indirect block the
3422 * caller is creating.
3425 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3426 int keybits, hammer2_blockref_t *base, int count)
3428 hammer2_chain_core_t *above;
3429 hammer2_blockref_t *bref;
3430 hammer2_chain_t *chain;
3431 hammer2_key_t key_beg;
3432 hammer2_key_t key_end;
3433 hammer2_key_t key_next;
3442 above = parent->core;
3447 * Calculate the range of keys in the array being careful to skip
3448 * slots which are overridden with a deletion. Once the scan
3449 * completes we will cut the key range in half and shift half the
3450 * range into the new indirect block.
3453 key_end = HAMMER2_MAX_KEY;
3455 spin_lock(&above->cst.spin);
3458 if (++loops == 100000) {
3459 panic("indkey_freemap shit %p %p:%d\n",
3460 parent, base, count);
3462 chain = hammer2_combined_find(parent, base, count,
3463 &cache_index, &key_next,
3464 key_beg, key_end, &bref);
3471 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3472 if (key_next == 0 || key_next > key_end)
3479 * Use the full live (not deleted) element for the scan
3480 * iteration. HAMMER2 does not allow partial replacements.
3482 * XXX should be built into hammer2_combined_find().
3484 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3487 * Expand our calculated key range (key, keybits) to fit
3488 * the scanned key. nkeybits represents the full range
3489 * that we will later cut in half (two halves @ nkeybits - 1).
3492 if (nkeybits < bref->keybits) {
3493 if (bref->keybits > 64) {
3494 kprintf("bad bref chain %p bref %p\n",
3498 nkeybits = bref->keybits;
3500 while (nkeybits < 64 &&
3501 (~(((hammer2_key_t)1 << nkeybits) - 1) &
3502 (key ^ bref->key)) != 0) {
3507 * If the new key range is larger we have to determine
3508 * which side of the new key range the existing keys fall
3509 * under by checking the high bit, then collapsing the
3510 * locount into the hicount or vise-versa.
3512 if (keybits != nkeybits) {
3513 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3524 * The newly scanned key will be in the lower half or the
3525 * upper half of the (new) key range.
3527 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3536 spin_unlock(&above->cst.spin);
3537 bref = NULL; /* now invalid (safety) */
3540 * Adjust keybits to represent half of the full range calculated
3541 * above (radix 63 max)
3546 * Select whichever half contains the most elements. Theoretically
3547 * we can select either side as long as it contains at least one
3548 * element (in order to ensure that a free slot is present to hold
3549 * the indirect block).
3551 if (hammer2_indirect_optimize) {
3553 * Insert node for least number of keys, this will arrange
3554 * the first few blocks of a large file or the first few
3555 * inodes in a directory with fewer indirect blocks when
3558 if (hicount < locount && hicount != 0)
3559 key |= (hammer2_key_t)1 << keybits;
3561 key &= ~(hammer2_key_t)1 << keybits;
3564 * Insert node for most number of keys, best for heavily
3567 if (hicount > locount)
3568 key |= (hammer2_key_t)1 << keybits;
3570 key &= ~(hammer2_key_t)1 << keybits;
3578 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3579 * set chain->delete_tid.
3581 * This function does NOT generate a modification to the parent. It
3582 * would be nearly impossible to figure out which parent to modify anyway.
3583 * Such modifications are handled by the flush code and are properly merged
3584 * using the flush synchronization point.
3586 * The find/get code will properly overload the RBTREE check on top of
3587 * the bref check to detect deleted entries.
3589 * This function is NOT recursive. Any entity already pushed into the
3590 * chain (such as an inode) may still need visibility into its contents,
3591 * as well as the ability to read and modify the contents. For example,
3592 * for an unlinked file which is still open.
3594 * NOTE: This function does NOT set chain->modify_tid, allowing future
3595 * code to distinguish between live and deleted chains by testing
3598 * NOTE: Deletions normally do not occur in the middle of a duplication
3599 * chain but we use a trick for hardlink migration that refactors
3600 * the originating inode without deleting it, so we make no assumptions
3604 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3606 KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3609 * Nothing to do if already marked.
3611 if (chain->flags & HAMMER2_CHAIN_DELETED)
3615 * We must set MOVED along with DELETED for the flush code to
3616 * recognize the operation and properly disconnect the chain
3619 * The setting of DELETED causes finds, lookups, and _next iterations
3620 * to no longer recognize the chain. RB_SCAN()s will still have
3621 * visibility (needed for flush serialization points).
3623 * We need the spinlock on the core whos RBTREE contains chain
3624 * to protect against races.
3626 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3627 spin_lock(&chain->above->cst.spin);
3629 chain->delete_tid = trans->sync_tid;
3630 /*chain->delete_gen = ++trans->delete_gen;*/
3631 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3632 atomic_add_int(&chain->above->live_count, -1);
3634 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3635 hammer2_chain_ref(chain);
3636 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3638 spin_unlock(&chain->above->cst.spin);
3641 * Mark the underlying block as possibly being free unless WILLDUP
3642 * is set. Duplication can occur in many situations, particularly
3643 * when chains are moved to indirect blocks.
3645 if ((flags & HAMMER2_DELETE_WILLDUP) == 0)
3646 hammer2_freemap_free(trans, chain->hmp, &chain->bref, 0);
3647 hammer2_chain_setsubmod(trans, chain);
3651 * Called with the core spinlock held to check for freeable layers.
3652 * Used by the flush code. Layers can wind up not being freed due
3653 * to the temporary layer->refs count. This function frees up any
3654 * layers that were missed.
3657 hammer2_chain_layer_check_locked(hammer2_mount_t *hmp,
3658 hammer2_chain_core_t *core)
3660 hammer2_chain_layer_t *layer;
3661 hammer2_chain_layer_t *tmp;
3663 tmp = TAILQ_FIRST(&core->layerq);
3664 while ((layer = tmp) != NULL) {
3665 tmp = TAILQ_NEXT(tmp, entry);
3666 if (layer->refs == 0 && RB_EMPTY(&layer->rbtree)) {
3667 TAILQ_REMOVE(&core->layerq, layer, entry);
3670 spin_unlock(&core->cst.spin);
3671 kfree(layer, hmp->mchain);
3672 spin_lock(&core->cst.spin);
3680 * Returns the index of the nearest element in the blockref array >= elm.
3681 * Returns (count) if no element could be found.
3683 * Sets *key_nextp to the next key for loop purposes but does not modify
3684 * it if the next key would be higher than the current value of *key_nextp.
3685 * Note that *key_nexp can overflow to 0, which should be tested by the
3688 * (*cache_indexp) is a heuristic and can be any value without effecting
3691 * The spin lock on the related chain must be held.
3694 hammer2_base_find(hammer2_chain_t *chain,
3695 hammer2_blockref_t *base, int count,
3696 int *cache_indexp, hammer2_key_t *key_nextp,
3697 hammer2_key_t key_beg, hammer2_key_t key_end)
3699 hammer2_chain_core_t *core = chain->core;
3700 hammer2_blockref_t *scan;
3701 hammer2_key_t scan_end;
3707 KKASSERT(core->flags & HAMMER2_CORE_COUNTEDBREFS);
3708 if (count == 0 || base == NULL)
3712 * Sequential optimization
3716 if (i >= core->live_zero)
3717 i = core->live_zero - 1;
3720 KKASSERT(i < count);
3726 while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3733 * Search forwards, stop when we find a scan element which
3734 * encloses the key or until we know that there are no further
3738 if (scan->type != 0) {
3739 if (scan->key > key_beg)
3741 scan_end = scan->key +
3742 ((hammer2_key_t)1 << scan->keybits) - 1;
3743 if (scan_end >= key_beg)
3746 if (i >= core->live_zero)
3753 if (i >= core->live_zero) {
3756 scan_end = scan->key +
3757 ((hammer2_key_t)1 << scan->keybits);
3758 if (scan_end && (*key_nextp > scan_end ||
3760 *key_nextp = scan_end;
3768 * Do a combined search and return the next match either from the blockref
3769 * array or from the in-memory chain. Sets *bresp to the returned bref in
3770 * both cases, or sets it to NULL if the search exhausted. Only returns
3771 * a non-NULL chain if the search matched from the in-memory chain.
3773 * Must be called with above's spinlock held. Spinlock remains held
3774 * through the operation.
3776 * The returned chain is not locked or referenced. Use the returned bref
3777 * to determine if the search exhausted or not.
3779 static hammer2_chain_t *
3780 hammer2_combined_find(hammer2_chain_t *parent,
3781 hammer2_blockref_t *base, int count,
3782 int *cache_indexp, hammer2_key_t *key_nextp,
3783 hammer2_key_t key_beg, hammer2_key_t key_end,
3784 hammer2_blockref_t **bresp)
3786 hammer2_blockref_t *bref;
3787 hammer2_chain_t *chain;
3790 *key_nextp = key_end + 1;
3791 i = hammer2_base_find(parent, base, count, cache_indexp,
3792 key_nextp, key_beg, key_end);
3793 chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3798 if (i == count && chain == NULL) {
3800 return(chain); /* NULL */
3804 * Only chain matched
3807 bref = &chain->bref;
3812 * Only blockref matched.
3814 if (chain == NULL) {
3820 * Both in-memory and blockref match.
3822 * If they are both flush with the left hand side select the chain.
3823 * If their starts match select the chain.
3824 * Otherwise the nearer element wins.
3826 if (chain->bref.key <= key_beg && base[i].key <= key_beg) {
3827 bref = &chain->bref;
3830 if (chain->bref.key <= base[i].key) {
3831 bref = &chain->bref;
3839 * If the bref is out of bounds we've exhausted our search.
3842 if (bref->key > key_end) {
3852 * Locate the specified block array element and delete it. The element
3855 * The spin lock on the related chain must be held.
3857 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3858 * need to be adjusted when we commit the media change.
3861 hammer2_base_delete(hammer2_chain_t *chain,
3862 hammer2_blockref_t *base, int count,
3863 int *cache_indexp, hammer2_chain_t *child)
3865 hammer2_blockref_t *elm = &child->bref;
3866 hammer2_chain_core_t *core = chain->core;
3867 hammer2_key_t key_next;
3871 kprintf("base delete %p.%d %016jx/%d\n",
3872 child, child->bref.type,
3873 child->bref.key, child->bref.keybits);
3877 * Delete element. Expect the element to exist.
3879 * XXX see caller, flush code not yet sophisticated enough to prevent
3880 * re-flushed in some cases.
3882 key_next = 0; /* max range */
3883 i = hammer2_base_find(chain, base, count, cache_indexp,
3884 &key_next, elm->key, elm->key);
3885 if (i == count || base[i].type == 0 ||
3886 base[i].key != elm->key || base[i].keybits != elm->keybits) {
3887 panic("delete base %p element not found at %d/%d elm %p\n",
3888 base, i, count, elm);
3891 bzero(&base[i], sizeof(*base));
3892 if (core->live_zero == i + 1) {
3893 while (--i >= 0 && base[i].type == 0)
3895 core->live_zero = i + 1;
3900 * Insert the specified element. The block array must not already have the
3901 * element and must have space available for the insertion.
3903 * The spin lock on the related chain must be held.
3905 * NOTE: live_count was adjusted when the chain was deleted, so it does not
3906 * need to be adjusted when we commit the media change.
3909 hammer2_base_insert(hammer2_chain_t *parent,
3910 hammer2_blockref_t *base, int count,
3911 int *cache_indexp, hammer2_chain_t *child)
3913 hammer2_blockref_t *elm = &child->bref;
3914 hammer2_chain_core_t *core = parent->core;
3915 hammer2_key_t key_next;
3924 kprintf("base insert %p.%d %016jx/%d\n",
3925 child, child->bref.type,
3926 child->bref.key, child->bref.keybits);
3929 * Insert new element. Expect the element to not already exist
3930 * unless we are replacing it.
3932 * XXX see caller, flush code not yet sophisticated enough to prevent
3933 * re-flushed in some cases.
3935 key_next = 0; /* max range */
3936 i = hammer2_base_find(parent, base, count, cache_indexp,
3937 &key_next, elm->key, elm->key);
3940 * Shortcut fill optimization, typical ordered insertion(s) may not
3943 KKASSERT(i >= 0 && i <= count);
3945 if (i == count && core->live_zero < count) {
3946 i = core->live_zero++;
3951 xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3952 if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3953 panic("insert base %p overlapping elements at %d elm %p\n",
3958 * Try to find an empty slot before or after.
3962 while (j > 0 || k < count) {
3964 if (j >= 0 && base[j].type == 0) {
3968 bcopy(&base[j+1], &base[j],
3969 (i - j - 1) * sizeof(*base));
3975 if (k < count && base[k].type == 0) {
3976 bcopy(&base[i], &base[i+1],
3977 (k - i) * sizeof(hammer2_blockref_t));
3979 if (core->live_zero <= k)
3980 core->live_zero = k + 1;
3985 panic("hammer2_base_insert: no room!");
3992 for (l = 0; l < count; ++l) {
3994 key_next = base[l].key +
3995 ((hammer2_key_t)1 << base[l].keybits) - 1;
3999 while (++l < count) {
4001 if (base[l].key <= key_next)
4002 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4003 key_next = base[l].key +
4004 ((hammer2_key_t)1 << base[l].keybits) - 1;
4014 * Sort the blockref array for the chain. Used by the flush code to
4015 * sort the blockref[] array.
4017 * The chain must be exclusively locked AND spin-locked.
4019 typedef hammer2_blockref_t *hammer2_blockref_p;
4023 hammer2_base_sort_callback(const void *v1, const void *v2)
4025 hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4026 hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4029 * Make sure empty elements are placed at the end of the array
4031 if (bref1->type == 0) {
4032 if (bref2->type == 0)
4035 } else if (bref2->type == 0) {
4042 if (bref1->key < bref2->key)
4044 if (bref1->key > bref2->key)
4050 hammer2_base_sort(hammer2_chain_t *chain)
4052 hammer2_blockref_t *base;
4055 switch(chain->bref.type) {
4056 case HAMMER2_BREF_TYPE_INODE:
4058 * Special shortcut for embedded data returns the inode
4059 * itself. Callers must detect this condition and access
4060 * the embedded data (the strategy code does this for us).
4062 * This is only applicable to regular files and softlinks.
4064 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4066 base = &chain->data->ipdata.u.blockset.blockref[0];
4067 count = HAMMER2_SET_COUNT;
4069 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4070 case HAMMER2_BREF_TYPE_INDIRECT:
4072 * Optimize indirect blocks in the INITIAL state to avoid
4075 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4076 base = &chain->data->npdata[0];
4077 count = chain->bytes / sizeof(hammer2_blockref_t);
4079 case HAMMER2_BREF_TYPE_VOLUME:
4080 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4081 count = HAMMER2_SET_COUNT;
4083 case HAMMER2_BREF_TYPE_FREEMAP:
4084 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4085 count = HAMMER2_SET_COUNT;
4088 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4090 base = NULL; /* safety */
4091 count = 0; /* safety */
4093 kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4099 * Chain memory management
4102 hammer2_chain_wait(hammer2_chain_t *chain)
4104 tsleep(chain, 0, "chnflw", 1);
4108 * Manage excessive memory resource use for chain and related
4112 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4115 while (pmp->inmem_chains > desiredvnodes / 10 &&
4116 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 2) {
4118 speedup_syncer(pmp->mp);
4119 pmp->inmem_waiting = 1;
4120 tsleep(&pmp->inmem_waiting, 0, "chnmem", hz);
4124 if (pmp->inmem_chains > desiredvnodes / 10 &&
4125 pmp->inmem_chains > pmp->mp->mnt_nvnodelistsize * 7 / 4) {
4126 speedup_syncer(pmp->mp);
4132 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4134 if (pmp->inmem_waiting &&
4135 (pmp->inmem_chains <= desiredvnodes / 10 ||
4136 pmp->inmem_chains <= pmp->mp->mnt_nvnodelistsize * 2)) {
4138 pmp->inmem_waiting = 0;
4139 wakeup(&pmp->inmem_waiting);
4145 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4149 switch(bref->type) {
4150 case HAMMER2_BREF_TYPE_DATA:
4151 counterp = &hammer2_iod_file_read;
4153 case HAMMER2_BREF_TYPE_INODE:
4154 counterp = &hammer2_iod_meta_read;
4156 case HAMMER2_BREF_TYPE_INDIRECT:
4157 counterp = &hammer2_iod_indr_read;
4159 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4160 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4161 counterp = &hammer2_iod_fmap_read;
4164 counterp = &hammer2_iod_volu_read;