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 and hammer2_chain_core structures.
39 * Chains represent the filesystem media topology in-memory. Any given
40 * chain can represent an inode, indirect block, data, or other types
43 * This module provides APIs for direct and indirect block searches,
44 * iterations, recursions, creation, deletion, replication, and snapshot
45 * views (used by the flush and snapshot code).
47 * Generally speaking any modification made to a chain must propagate all
48 * the way back to the volume header, issuing copy-on-write updates to the
49 * blockref tables all the way up. Any chain except the volume header itself
50 * can be flushed to disk at any time, in any order. None of it matters
51 * until we get to the point where we want to synchronize the volume header
52 * (see the flush code).
54 * The chain structure supports snapshot views in time, which are primarily
55 * used until the related data and meta-data is flushed to allow the
56 * filesystem to make snapshots without requiring it to first flush,
57 * and to allow the filesystem flush and modify the filesystem concurrently
58 * with minimal or no stalls.
60 #include <sys/cdefs.h>
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/types.h>
65 #include <sys/kern_syscall.h>
70 static int hammer2_indirect_optimize; /* XXX SYSCTL */
72 static hammer2_chain_t *hammer2_chain_create_indirect(
73 hammer2_trans_t *trans, hammer2_chain_t *parent,
74 hammer2_key_t key, int keybits, int *errorp);
77 * We use a red-black tree to guarantee safe lookups under shared locks.
79 * Chains can be overloaded onto the same index, creating a different
80 * view of a blockref table based on a transaction id. The RBTREE
81 * deconflicts the view by sub-sorting on delete_tid.
83 * NOTE: Any 'current' chain which is not yet deleted will have a
84 * delete_tid of HAMMER2_MAX_TID (0xFFF....FFFLLU).
86 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
89 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
91 if (chain1->index < chain2->index)
93 if (chain1->index > chain2->index)
95 if (chain1->delete_tid < chain2->delete_tid)
97 if (chain1->delete_tid > chain2->delete_tid)
103 * Flag chain->parent SUBMODIFIED recursively up to the root. The
104 * recursion can terminate when a parent is encountered with SUBMODIFIED
105 * already set. The flag is NOT set on the passed-in chain.
107 * This can be confusing because even though chains are multi-homed,
108 * each chain has a specific idea of its parent (chain->parent) which
111 * This flag is used by the flusher's downward recursion to detect
112 * modifications and can only be cleared bottom-up.
114 * The parent pointer is protected by all the modified children below it
115 * and cannot be changed until they have all been flushed. However, setsubmod
116 * operations on new modifications can race flushes in progress, so we use
117 * the chain->core->cst.spin lock to handle collisions.
120 hammer2_chain_parent_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
122 hammer2_chain_t *parent;
123 hammer2_chain_core_t *core;
125 while ((parent = chain->parent) != NULL) {
127 spin_lock(&core->cst.spin);
129 * XXX flush synchronization
131 while (parent->duplink &&
132 (parent->flags & HAMMER2_CHAIN_DELETED)) {
133 parent = parent->duplink;
135 if (parent->flags & HAMMER2_CHAIN_SUBMODIFIED) {
136 spin_unlock(&core->cst.spin);
139 atomic_set_int(&parent->flags, HAMMER2_CHAIN_SUBMODIFIED);
140 spin_unlock(&core->cst.spin);
146 * Allocate a new disconnected chain element representing the specified
147 * bref. chain->refs is set to 1 and the passed bref is copied to
148 * chain->bref. chain->bytes is derived from the bref.
150 * chain->core is NOT allocated and the media data and bp pointers are left
151 * NULL. The caller must call chain_core_alloc() to allocate or associate
152 * a core with the chain.
154 * NOTE: Returns a referenced but unlocked (because there is no core) chain.
157 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_blockref_t *bref)
159 hammer2_chain_t *chain;
160 u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
163 * Construct the appropriate system structure.
166 case HAMMER2_BREF_TYPE_INODE:
167 case HAMMER2_BREF_TYPE_INDIRECT:
168 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
169 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
170 case HAMMER2_BREF_TYPE_DATA:
171 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
172 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
174 case HAMMER2_BREF_TYPE_VOLUME:
176 panic("hammer2_chain_alloc volume type illegal for op");
179 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
185 chain->index = -1; /* not yet assigned */
186 chain->bytes = bytes;
188 chain->flags = HAMMER2_CHAIN_ALLOCATED;
189 chain->delete_tid = HAMMER2_MAX_TID;
195 * Associate an existing core with the chain or allocate a new core.
197 * The core is not locked. No additional refs on the chain are made.
200 hammer2_chain_core_alloc(hammer2_chain_t *chain, hammer2_chain_core_t *core)
202 KKASSERT(chain->core == NULL);
205 core = kmalloc(sizeof(*core), chain->hmp->mchain,
207 RB_INIT(&core->rbtree);
210 ccms_cst_init(&core->cst, chain);
212 atomic_add_int(&core->sharecnt, 1);
218 * Deallocate a chain after the caller has transitioned its refs to 0
219 * and disassociated it from its parent.
221 * We must drop sharecnt on the core (if any) and handle its 1->0 transition
225 hammer2_chain_dealloc(hammer2_chain_t *chain)
227 hammer2_chain_core_t *core;
230 * Chain's flags are expected to be sane.
232 KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
233 HAMMER2_CHAIN_MODIFIED |
234 HAMMER2_CHAIN_ONRBTREE)) == 0);
235 KKASSERT(chain->duplink == NULL);
238 * Disconnect chain->core from chain and free core if it was the
239 * last core. If any children are present in the core's rbtree
240 * they cannot have a pointer to our chain by definition because
241 * our chain's refs have dropped to 0. If this is the last sharecnt
242 * on core, then core's rbtree must be empty by definition.
244 if ((core = chain->core) != NULL) {
246 * Other chains may reference the same core so the core's
247 * spinlock is needed to safely disconnect it.
249 spin_lock(&core->cst.spin);
251 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
252 spin_unlock(&core->cst.spin);
253 KKASSERT(RB_EMPTY(&core->rbtree));
254 KKASSERT(core->cst.count == 0);
255 KKASSERT(core->cst.upgrade == 0);
256 kfree(core, chain->hmp->mchain);
258 spin_unlock(&core->cst.spin);
260 core = NULL; /* safety */
264 * Finally free the structure and return for possible recursion.
266 hammer2_chain_free(chain);
270 * Free a disconnected chain element.
273 hammer2_chain_free(hammer2_chain_t *chain)
275 hammer2_mount_t *hmp = chain->hmp;
277 switch(chain->bref.type) {
278 case HAMMER2_BREF_TYPE_VOLUME:
281 case HAMMER2_BREF_TYPE_INODE:
283 kfree(chain->data, hmp->minode);
288 KKASSERT(chain->data == NULL);
292 KKASSERT(chain->core == NULL);
293 KKASSERT(chain->bp == NULL);
296 if (chain->flags & HAMMER2_CHAIN_ALLOCATED)
297 kfree(chain, hmp->mchain);
301 * Add a reference to a chain element, preventing its destruction.
304 hammer2_chain_ref(hammer2_chain_t *chain)
306 atomic_add_int(&chain->refs, 1);
310 * Drop the caller's reference to the chain. When the ref count drops to
311 * zero this function will disassociate the chain from its parent and
312 * deallocate it, then recursely drop the parent using the implied ref
313 * from the chain's chain->parent.
315 * WARNING! Just because we are able to deallocate a chain doesn't mean
316 * that chain->core->rbtree is empty. There can still be a sharecnt
317 * on chain->core and RBTREE entries that refer to different parents.
319 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
322 hammer2_chain_drop(hammer2_chain_t *chain)
328 if (chain->flags & HAMMER2_CHAIN_MOVED)
330 if (chain->flags & HAMMER2_CHAIN_MODIFIED)
332 KKASSERT(chain->refs > need);
342 chain = hammer2_chain_lastdrop(chain);
343 /* recursively drop parent or retry same */
344 } else if (atomic_cmpset_int(&chain->refs, 1, 0)) {
345 hammer2_chain_dealloc(chain);
347 /* no parent to recurse on */
349 /* retry the same chain */
352 if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
354 /* retry the same chain */
360 * Safe handling of the 1->0 transition on chain when the chain has a
363 * NOTE: A chain can only be removed from its parent core's RBTREE on
364 * the 1->0 transition by definition. No other code is allowed
365 * to remove chain from its RBTREE, so no race is possible.
369 hammer2_chain_lastdrop(hammer2_chain_t *chain)
371 hammer2_chain_t *parent;
372 hammer2_chain_t *tmp;
373 hammer2_chain_core_t *parent_core;
375 parent = chain->parent;
376 parent_core = parent->core;
377 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
379 spin_lock(&parent_core->cst.spin);
380 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
381 RB_REMOVE(hammer2_chain_tree, &parent_core->rbtree, chain);
382 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
383 chain->parent = NULL; /* NULL field, must drop implied ref */
384 spin_unlock(&parent_core->cst.spin);
385 if ((tmp = chain->duplink) != NULL) {
386 chain->duplink = NULL;
387 hammer2_chain_drop(tmp);
389 hammer2_chain_dealloc(chain);
390 chain = parent; /* recursively drop parent */
392 spin_unlock(&parent_core->cst.spin);
398 * Ref and lock a chain element, acquiring its data with I/O if necessary,
399 * and specify how you would like the data to be resolved.
401 * Returns 0 on success or an error code if the data could not be acquired.
402 * The chain element is locked either way.
404 * The lock is allowed to recurse, multiple locking ops will aggregate
405 * the requested resolve types. Once data is assigned it will not be
406 * removed until the last unlock.
408 * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
409 * (typically used to avoid device/logical buffer
412 * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
413 * the INITIAL-create state (indirect blocks only).
415 * Do not resolve data elements for DATA chains.
416 * (typically used to avoid device/logical buffer
419 * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
421 * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
422 * it will be locked exclusive.
424 * NOTE: Embedded elements (volume header, inodes) are always resolved
427 * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
428 * element will instantiate and zero its buffer, and flush it on
431 * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
432 * so as not to instantiate a device buffer, which could alias against
433 * a logical file buffer. However, if ALWAYS is specified the
434 * device buffer will be instantiated anyway.
436 * WARNING! If data must be fetched a shared lock will temporarily be
437 * upgraded to exclusive. However, a deadlock can occur if
438 * the caller owns more than one shared lock.
441 hammer2_chain_lock(hammer2_chain_t *chain, int how)
443 hammer2_mount_t *hmp;
444 hammer2_chain_core_t *core;
445 hammer2_blockref_t *bref;
455 * Ref and lock the element. Recursive locks are allowed.
457 if ((how & HAMMER2_RESOLVE_NOREF) == 0)
458 hammer2_chain_ref(chain);
460 KKASSERT(hmp != NULL);
463 * Get the appropriate lock.
466 if (how & HAMMER2_RESOLVE_SHARED)
467 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
469 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
472 * If we already have a valid data pointer no further action is
479 * Do we have to resolve the data?
481 switch(how & HAMMER2_RESOLVE_MASK) {
482 case HAMMER2_RESOLVE_NEVER:
484 case HAMMER2_RESOLVE_MAYBE:
485 if (chain->flags & HAMMER2_CHAIN_INITIAL)
487 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
489 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
492 case HAMMER2_RESOLVE_ALWAYS:
497 * Upgrade to an exclusive lock so we can safely manipulate the
498 * buffer cache. If another thread got to it before us we
501 ostate = ccms_thread_lock_upgrade(&core->cst);
503 ccms_thread_lock_downgrade(&core->cst, ostate);
508 * We must resolve to a device buffer, either by issuing I/O or
509 * by creating a zero-fill element. We do not mark the buffer
510 * dirty when creating a zero-fill element (the hammer2_chain_modify()
511 * API must still be used to do that).
513 * The device buffer is variable-sized in powers of 2 down
514 * to HAMMER2_MINALLOCSIZE (typically 1K). A 64K physical storage
515 * chunk always contains buffers of the same size. (XXX)
517 * The minimum physical IO size may be larger than the variable
522 if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
523 bbytes = HAMMER2_MINIOSIZE;
524 pbase = bref->data_off & ~(hammer2_off_t)(bbytes - 1);
525 peof = (pbase + HAMMER2_PBUFSIZE64) & ~HAMMER2_PBUFMASK64;
526 boff = bref->data_off & HAMMER2_OFF_MASK & (bbytes - 1);
527 KKASSERT(pbase != 0);
530 * The getblk() optimization can only be used on newly created
531 * elements if the physical block size matches the request.
533 if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
534 chain->bytes == bbytes) {
535 chain->bp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
537 } else if (hammer2_cluster_enable) {
538 error = cluster_read(hmp->devvp, peof, pbase, bbytes,
539 HAMMER2_PBUFSIZE, HAMMER2_PBUFSIZE,
542 error = bread(hmp->devvp, pbase, bbytes, &chain->bp);
546 kprintf("hammer2_chain_get: I/O error %016jx: %d\n",
547 (intmax_t)pbase, error);
550 ccms_thread_lock_downgrade(&core->cst, ostate);
555 * Zero the data area if the chain is in the INITIAL-create state.
556 * Mark the buffer for bdwrite().
558 bdata = (char *)chain->bp->b_data + boff;
559 if (chain->flags & HAMMER2_CHAIN_INITIAL) {
560 bzero(bdata, chain->bytes);
561 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
565 * Setup the data pointer, either pointing it to an embedded data
566 * structure and copying the data from the buffer, or pointing it
569 * The buffer is not retained when copying to an embedded data
570 * structure in order to avoid potential deadlocks or recursions
571 * on the same physical buffer.
573 switch (bref->type) {
574 case HAMMER2_BREF_TYPE_VOLUME:
576 * Copy data from bp to embedded buffer
578 panic("hammer2_chain_lock: called on unresolved volume header");
581 KKASSERT(pbase == 0);
582 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
583 bcopy(bdata, &hmp->voldata, chain->bytes);
584 chain->data = (void *)&hmp->voldata;
589 case HAMMER2_BREF_TYPE_INODE:
591 * Copy data from bp to embedded buffer, do not retain the
594 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
595 chain->data = kmalloc(sizeof(chain->data->ipdata),
596 hmp->minode, M_WAITOK | M_ZERO);
597 bcopy(bdata, &chain->data->ipdata, chain->bytes);
601 case HAMMER2_BREF_TYPE_INDIRECT:
602 case HAMMER2_BREF_TYPE_DATA:
603 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
604 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
605 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
608 * Point data at the device buffer and leave bp intact.
610 chain->data = (void *)bdata;
615 * Make sure the bp is not specifically owned by this thread before
616 * restoring to a possibly shared lock, so another hammer2 thread
620 BUF_KERNPROC(chain->bp);
621 ccms_thread_lock_downgrade(&core->cst, ostate);
626 * Unlock and deref a chain element.
628 * On the last lock release any non-embedded data (chain->bp) will be
632 hammer2_chain_unlock(hammer2_chain_t *chain)
634 hammer2_chain_core_t *core = chain->core;
638 * Release the CST lock but with a special 1->0 transition case
639 * to also drop the refs on chain. Multiple CST locks only
641 * Returns non-zero if lock references remain. When zero is
642 * returned the last lock reference is retained and any shared
643 * lock is upgraded to an exclusive lock for final disposition.
645 if (ccms_thread_unlock_zero(&core->cst)) {
646 KKASSERT(chain->refs > 1);
647 atomic_add_int(&chain->refs, -1);
652 * Shortcut the case if the data is embedded or not resolved.
654 * Do NOT NULL out chain->data (e.g. inode data), it might be
657 * The DIRTYBP flag is non-applicable in this situation and can
658 * be cleared to keep the flags state clean.
660 if (chain->bp == NULL) {
661 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
662 ccms_thread_unlock(&core->cst);
663 hammer2_chain_drop(chain);
670 if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
672 } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
673 switch(chain->bref.type) {
674 case HAMMER2_BREF_TYPE_DATA:
675 counterp = &hammer2_ioa_file_write;
677 case HAMMER2_BREF_TYPE_INODE:
678 counterp = &hammer2_ioa_meta_write;
680 case HAMMER2_BREF_TYPE_INDIRECT:
681 counterp = &hammer2_ioa_indr_write;
683 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
684 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
685 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
686 counterp = &hammer2_ioa_fmap_write;
689 counterp = &hammer2_ioa_volu_write;
694 switch(chain->bref.type) {
695 case HAMMER2_BREF_TYPE_DATA:
696 counterp = &hammer2_iod_file_write;
698 case HAMMER2_BREF_TYPE_INODE:
699 counterp = &hammer2_iod_meta_write;
701 case HAMMER2_BREF_TYPE_INDIRECT:
702 counterp = &hammer2_iod_indr_write;
704 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
705 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
706 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
707 counterp = &hammer2_iod_fmap_write;
710 counterp = &hammer2_iod_volu_write;
719 * If a device buffer was used for data be sure to destroy the
720 * buffer when we are done to avoid aliases (XXX what about the
721 * underlying VM pages?).
723 * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
726 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
727 chain->bp->b_flags |= B_RELBUF;
730 * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
731 * or not. The flag will get re-set when chain_modify() is called,
732 * even if MODIFIED is already set, allowing the OS to retire the
733 * buffer independent of a hammer2 flus.
736 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
737 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
738 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
739 atomic_clear_int(&chain->flags,
740 HAMMER2_CHAIN_IOFLUSH);
741 chain->bp->b_flags |= B_RELBUF;
742 cluster_awrite(chain->bp);
744 chain->bp->b_flags |= B_CLUSTEROK;
748 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
749 atomic_clear_int(&chain->flags,
750 HAMMER2_CHAIN_IOFLUSH);
751 chain->bp->b_flags |= B_RELBUF;
754 /* bp might still be dirty */
759 ccms_thread_unlock(&core->cst);
760 hammer2_chain_drop(chain);
764 * Resize the chain's physical storage allocation in-place. This may
765 * replace the passed-in chain with a new chain.
767 * Chains can be resized smaller without reallocating the storage.
768 * Resizing larger will reallocate the storage.
770 * Must be passed an exclusively locked parent and chain, returns a new
771 * exclusively locked chain at the same index and unlocks the old chain.
772 * Flushes the buffer if necessary.
774 * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
775 * to avoid instantiating a device buffer that conflicts with the vnode
776 * data buffer. That is, the passed-in bp is a logical buffer, whereas
777 * any chain-oriented bp would be a device buffer.
779 * XXX flags currently ignored, uses chain->bp to detect data/no-data.
780 * XXX return error if cannot resize.
783 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
785 hammer2_chain_t *parent, hammer2_chain_t **chainp,
786 int nradix, int flags)
788 hammer2_mount_t *hmp = trans->hmp;
789 hammer2_chain_t *chain = *chainp;
802 * Only data and indirect blocks can be resized for now.
803 * (The volu root, inodes, and freemap elements use a fixed size).
805 KKASSERT(chain != &hmp->vchain);
806 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
807 chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
810 * Nothing to do if the element is already the proper size
812 obytes = chain->bytes;
813 nbytes = 1U << nradix;
814 if (obytes == nbytes)
818 * Delete the old chain and duplicate it at the same (parent, index),
819 * returning a new chain. This allows the old chain to still be
820 * used by the flush code. Duplication occurs in-place.
822 * NOTE: If we are not crossing a synchronization point the
823 * duplication code will simply reuse the existing chain
826 hammer2_chain_delete(trans, parent, chain);
827 hammer2_chain_duplicate(trans, parent, chain->index, &chain, NULL);
830 * Set MODIFIED and add a chain ref to prevent destruction. Both
831 * modified flags share the same ref. (duplicated chains do not
832 * start out MODIFIED unless possibly if the duplication code
833 * decided to reuse the existing chain as-is).
835 * If the chain is already marked MODIFIED then we can safely
836 * return the previous allocation to the pool without having to
837 * worry about snapshots. XXX check flush synchronization.
839 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
840 atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
841 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
842 hammer2_chain_ref(chain);
845 hammer2_freemap_free(hmp, chain->bref.data_off,
851 * Relocate the block, even if making it smaller (because different
852 * block sizes may be in different regions).
854 chain->bref.data_off = hammer2_freemap_alloc(hmp, chain->bref.type,
856 chain->bytes = nbytes;
857 /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
860 * The device buffer may be larger than the allocation size.
862 if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
863 bbytes = HAMMER2_MINIOSIZE;
864 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
865 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
867 KKASSERT(chain->bp == NULL);
870 * Only copy the data if resolved, otherwise the caller is
873 * XXX handle device-buffer resizing case too. Right now we
874 * only handle logical buffer resizing.
877 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
878 chain->bref.type == HAMMER2_BREF_TYPE_DATA);
879 KKASSERT(chain != &hmp->vchain); /* safety */
882 * The getblk() optimization can only be used if the
883 * physical block size matches the request.
885 if (nbytes == bbytes) {
886 nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
889 error = bread(hmp->devvp, pbase, bbytes, &nbp);
890 KKASSERT(error == 0);
892 bdata = (char *)nbp->b_data + boff;
895 * chain->bp and chain->data represent the on-disk version
896 * of the data, where as the passed-in bp is usually a
897 * more up-to-date logical buffer. However, there is no
898 * need to synchronize the more up-to-date data in (bp)
899 * as it will do that on its own when it flushes.
901 if (nbytes < obytes) {
902 bcopy(chain->data, bdata, nbytes);
904 bcopy(chain->data, bdata, obytes);
905 bzero(bdata + obytes, nbytes - obytes);
909 * NOTE: The INITIAL state of the chain is left intact.
910 * We depend on hammer2_chain_modify() to do the
913 * NOTE: We set B_NOCACHE to throw away the previous bp and
914 * any VM backing store, even if it was dirty.
915 * Otherwise we run the risk of a logical/device
916 * conflict on reallocation.
918 chain->bp->b_flags |= B_RELBUF | B_NOCACHE;
921 chain->data = (void *)bdata;
922 hammer2_chain_modify(trans, &chain, 0);
927 * Make sure the chain is marked MOVED and SUBMOD is set in the
928 * parent(s) so the adjustments are picked up by flush.
930 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
931 hammer2_chain_ref(chain);
932 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
934 hammer2_chain_parent_setsubmod(trans, chain);
939 * Convert a locked chain that was retrieved read-only to read-write,
940 * duplicating it if necessary to satisfy active flush points.
942 * If not already marked modified a new physical block will be allocated
943 * and assigned to the bref.
945 * If already modified and the new modification crosses a synchronization
946 * point the chain is duplicated in order to allow the flush to synchronize
947 * the old chain. The new chain replaces the old.
949 * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
950 * level or the COW operation will not work.
952 * Data blocks - The chain is usually locked RESOLVE_NEVER so as not to
953 * run the data through the device buffers.
955 * This function may return a different chain than was passed, in which case
956 * the old chain will be unlocked and the new chain will be locked.
958 hammer2_inode_data_t *
959 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip, int flags)
961 hammer2_chain_t *ochain;
964 hammer2_chain_modify(trans, &ip->chain, flags);
965 if (ochain != ip->chain) {
966 hammer2_chain_ref(ip->chain);
967 hammer2_chain_drop(ochain);
969 return(&ip->chain->data->ipdata);
973 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
976 hammer2_mount_t *hmp = trans->hmp;
977 hammer2_chain_t *chain = *chainp;
986 * modify_tid is only update for primary modifications, not for
987 * propagated brefs. mirror_tid will be updated regardless during
988 * the flush, no need to set it here.
990 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
991 chain->bref.modify_tid = trans->sync_tid;
994 * If the chain is already marked MODIFIED we can usually just
997 * WARNING! It is possible that a prior lock/modify sequence
998 * retired the buffer. During this lock/modify sequence
999 * MODIFIED may still be set but the buffer could wind up
1000 * clean. Since the caller is going to modify the buffer
1001 * further we have to be sure that DIRTYBP is set again.
1003 * WARNING! Currently the caller is responsible for handling
1004 * any delete/duplication roll of the chain to account
1005 * for modifications crossing synchronization points.
1007 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1008 if ((flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1009 chain->bp == NULL) {
1012 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1017 * Set MODIFIED and add a chain ref to prevent destruction. Both
1018 * modified flags share the same ref.
1020 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1021 hammer2_chain_ref(chain);
1024 * Adjust chain->modify_tid so the flusher knows when the
1025 * modification occurred.
1027 chain->modify_tid = trans->sync_tid;
1030 * We must allocate the copy-on-write block.
1032 * If the data is embedded no other action is required.
1034 * If the data is not embedded we acquire and clear the
1035 * new block. If chain->data is not NULL we then do the
1036 * copy-on-write. chain->data will then be repointed to the new
1037 * buffer and the old buffer will be released.
1039 * For newly created elements with no prior allocation we go
1040 * through the copy-on-write steps except without the copying part.
1042 if (chain != &hmp->vchain) {
1043 if ((hammer2_debug & 0x0001) &&
1044 (chain->bref.data_off & HAMMER2_OFF_MASK)) {
1045 kprintf("Replace %d\n", chain->bytes);
1047 chain->bref.data_off =
1048 hammer2_freemap_alloc(hmp, chain->bref.type,
1050 /* XXX failed allocation */
1054 * If data instantiation is optional and the chain has no current
1055 * data association (typical for DATA and newly-created INDIRECT
1056 * elements), don't instantiate the buffer now.
1058 if ((flags & HAMMER2_MODIFY_OPTDATA) && chain->bp == NULL)
1063 * Setting the DIRTYBP flag will cause the buffer to be dirtied or
1064 * written-out on unlock. This bit is independent of the MODIFIED
1065 * bit because the chain may still need meta-data adjustments done
1066 * by virtue of MODIFIED for its parent, and the buffer can be
1067 * flushed out (possibly multiple times) by the OS before that.
1069 * Clearing the INITIAL flag (for indirect blocks) indicates that
1070 * a zero-fill buffer has been instantiated.
1072 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1073 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1076 * We currently should never instantiate a device buffer for a
1077 * file data chain. (We definitely can for a freemap chain).
1079 KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_DATA);
1082 * Execute COW operation
1084 switch(chain->bref.type) {
1085 case HAMMER2_BREF_TYPE_VOLUME:
1086 case HAMMER2_BREF_TYPE_INODE:
1088 * The data is embedded, no copy-on-write operation is
1091 KKASSERT(chain->bp == NULL);
1093 case HAMMER2_BREF_TYPE_DATA:
1094 case HAMMER2_BREF_TYPE_INDIRECT:
1095 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1096 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1097 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1099 * Perform the copy-on-write operation
1101 KKASSERT(chain != &hmp->vchain); /* safety */
1103 * The device buffer may be larger than the allocation size.
1105 if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
1106 bbytes = HAMMER2_MINIOSIZE;
1107 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1108 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1111 * The getblk() optimization can only be used if the
1112 * physical block size matches the request.
1114 if (chain->bytes == bbytes) {
1115 nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
1118 error = bread(hmp->devvp, pbase, bbytes, &nbp);
1119 KKASSERT(error == 0);
1121 bdata = (char *)nbp->b_data + boff;
1124 * Copy or zero-fill on write depending on whether
1125 * chain->data exists or not.
1128 bcopy(chain->data, bdata, chain->bytes);
1129 KKASSERT(chain->bp != NULL);
1131 bzero(bdata, chain->bytes);
1134 chain->bp->b_flags |= B_RELBUF;
1138 chain->data = bdata;
1141 panic("hammer2_chain_modify: illegal non-embedded type %d",
1147 if ((flags & HAMMER2_MODIFY_NOSUB) == 0)
1148 hammer2_chain_parent_setsubmod(trans, chain);
1152 * Mark the volume as having been modified. This short-cut version
1153 * does not have to lock the volume's chain, which allows the ioctl
1154 * code to make adjustments to connections without deadlocking. XXX
1156 * No ref is made on vchain when flagging it MODIFIED.
1159 hammer2_modify_volume(hammer2_mount_t *hmp)
1161 hammer2_voldata_lock(hmp);
1162 hammer2_voldata_unlock(hmp, 1);
1166 * Locate an in-memory chain. The parent must be locked. The in-memory
1167 * chain is returned with a reference and without a lock, or NULL
1170 * This function returns the chain at the specified index with the highest
1171 * delete_tid. The caller must check whether the chain is flagged
1172 * CHAIN_DELETED or not.
1174 * NOTE: If no chain is found the caller usually must check the on-media
1175 * array to determine if a blockref exists at the index.
1177 struct hammer2_chain_find_info {
1178 hammer2_chain_t *best;
1179 hammer2_tid_t delete_tid;
1185 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1187 struct hammer2_chain_find_info *info = data;
1189 if (child->index < info->index)
1191 if (child->index > info->index)
1198 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1200 struct hammer2_chain_find_info *info = data;
1202 if (info->delete_tid < child->delete_tid) {
1203 info->delete_tid = child->delete_tid;
1211 hammer2_chain_find_locked(hammer2_chain_t *parent, int index)
1213 struct hammer2_chain_find_info info;
1216 info.delete_tid = 0;
1219 RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1220 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1227 hammer2_chain_find(hammer2_chain_t *parent, int index)
1229 hammer2_chain_t *chain;
1231 spin_lock(&parent->core->cst.spin);
1232 chain = hammer2_chain_find_locked(parent, index);
1234 hammer2_chain_ref(chain);
1235 spin_unlock(&parent->core->cst.spin);
1241 * Return a locked chain structure with all associated data acquired.
1242 * (if LOOKUP_NOLOCK is requested the returned chain is only referenced).
1244 * Caller must hold the parent locked shared or exclusive since we may
1245 * need the parent's bref array to find our block.
1247 * The returned child is locked as requested. If NOLOCK, the returned
1248 * child is still at least referenced.
1251 hammer2_chain_get(hammer2_chain_t *parent, int index, int flags)
1253 hammer2_blockref_t *bref;
1254 hammer2_mount_t *hmp = parent->hmp;
1255 hammer2_chain_t *chain;
1256 hammer2_chain_t dummy;
1260 * Figure out how to lock. MAYBE can be used to optimized
1261 * the initial-create state for indirect blocks.
1263 if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK))
1264 how = HAMMER2_RESOLVE_NEVER;
1266 how = HAMMER2_RESOLVE_MAYBE;
1267 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1268 how |= HAMMER2_RESOLVE_SHARED;
1272 * First see if we have a (possibly modified) chain element cached
1273 * for this (parent, index). Acquire the data if necessary.
1275 * If chain->data is non-NULL the chain should already be marked
1279 dummy.index = index;
1280 dummy.delete_tid = HAMMER2_MAX_TID;
1281 spin_lock(&parent->core->cst.spin);
1282 chain = RB_FIND(hammer2_chain_tree, &parent->core->rbtree, &dummy);
1284 hammer2_chain_ref(chain);
1285 spin_unlock(&parent->core->cst.spin);
1286 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1287 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1290 spin_unlock(&parent->core->cst.spin);
1293 * The parent chain must not be in the INITIAL state.
1295 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1296 panic("hammer2_chain_get: Missing bref(1)");
1301 * No RBTREE entry found, lookup the bref and issue I/O (switch on
1302 * the parent's bref to determine where and how big the array is).
1304 switch(parent->bref.type) {
1305 case HAMMER2_BREF_TYPE_INODE:
1306 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1307 bref = &parent->data->ipdata.u.blockset.blockref[index];
1309 case HAMMER2_BREF_TYPE_INDIRECT:
1310 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1311 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1312 KKASSERT(parent->data != NULL);
1313 KKASSERT(index >= 0 &&
1314 index < parent->bytes / sizeof(hammer2_blockref_t));
1315 bref = &parent->data->npdata.blockref[index];
1317 case HAMMER2_BREF_TYPE_VOLUME:
1318 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1319 bref = &hmp->voldata.sroot_blockset.blockref[index];
1323 panic("hammer2_chain_get: unrecognized blockref type: %d",
1326 if (bref->type == 0) {
1327 panic("hammer2_chain_get: Missing bref(2)");
1332 * Allocate a chain structure representing the existing media
1333 * entry. Resulting chain has one ref and is not locked.
1335 * The locking operation we do later will issue I/O to read it.
1337 chain = hammer2_chain_alloc(hmp, bref);
1338 hammer2_chain_core_alloc(chain, NULL); /* ref'd chain returned */
1341 * Link the chain into its parent. A spinlock is required to safely
1342 * access the RBTREE, and it is possible to collide with another
1343 * hammer2_chain_get() operation because the caller might only hold
1344 * a shared lock on the parent.
1346 KKASSERT(parent->refs > 0);
1347 spin_lock(&parent->core->cst.spin);
1348 chain->parent = parent;
1349 chain->index = index;
1350 if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, chain)) {
1351 chain->parent = NULL;
1353 spin_unlock(&parent->core->cst.spin);
1354 hammer2_chain_drop(chain);
1357 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
1358 hammer2_chain_ref(parent); /* chain->parent ref */
1359 spin_unlock(&parent->core->cst.spin);
1362 * Our new chain is referenced but NOT locked. Lock the chain
1363 * below. The locking operation also resolves its data.
1365 * If NOLOCK is set the release will release the one-and-only lock.
1367 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0) {
1368 hammer2_chain_lock(chain, how); /* recusive lock */
1369 hammer2_chain_drop(chain); /* excess ref */
1375 * Lookup initialization/completion API
1378 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1380 if (flags & HAMMER2_LOOKUP_SHARED) {
1381 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1382 HAMMER2_RESOLVE_SHARED);
1384 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1390 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1393 hammer2_chain_unlock(parent);
1398 * Locate any key between key_beg and key_end inclusive. (*parentp)
1399 * typically points to an inode but can also point to a related indirect
1400 * block and this function will recurse upwards and find the inode again.
1402 * WARNING! THIS DOES NOT RETURN KEYS IN LOGICAL KEY ORDER! ANY KEY
1403 * WITHIN THE RANGE CAN BE RETURNED. HOWEVER, AN ITERATION
1404 * WHICH PICKS UP WHERE WE LEFT OFF WILL CONTINUE THE SCAN.
1406 * (*parentp) must be exclusively locked and referenced and can be an inode
1407 * or an existing indirect block within the inode.
1409 * On return (*parentp) will be modified to point at the deepest parent chain
1410 * element encountered during the search, as a helper for an insertion or
1411 * deletion. The new (*parentp) will be locked and referenced and the old
1412 * will be unlocked and dereferenced (no change if they are both the same).
1414 * The matching chain will be returned exclusively locked. If NOLOCK is
1415 * requested the chain will be returned only referenced.
1417 * NULL is returned if no match was found, but (*parentp) will still
1418 * potentially be adjusted.
1420 * This function will also recurse up the chain if the key is not within the
1421 * current parent's range. (*parentp) can never be set to NULL. An iteration
1422 * can simply allow (*parentp) to float inside the loop.
1425 hammer2_chain_lookup(hammer2_chain_t **parentp,
1426 hammer2_key_t key_beg, hammer2_key_t key_end,
1429 hammer2_mount_t *hmp;
1430 hammer2_chain_t *parent;
1431 hammer2_chain_t *chain;
1432 hammer2_chain_t *tmp;
1433 hammer2_blockref_t *base;
1434 hammer2_blockref_t *bref;
1435 hammer2_key_t scan_beg;
1436 hammer2_key_t scan_end;
1439 int how_always = HAMMER2_RESOLVE_ALWAYS;
1440 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1442 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1443 how_maybe |= HAMMER2_RESOLVE_SHARED;
1444 how_always |= HAMMER2_RESOLVE_SHARED;
1448 * Recurse (*parentp) upward if necessary until the parent completely
1449 * encloses the key range or we hit the inode.
1454 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1455 parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1456 scan_beg = parent->bref.key;
1457 scan_end = scan_beg +
1458 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1459 if (key_beg >= scan_beg && key_end <= scan_end)
1462 * XXX flush synchronization
1464 tmp = parent->parent;
1465 while (tmp->duplink &&
1466 (tmp->flags & HAMMER2_CHAIN_DELETED)) {
1469 hammer2_chain_ref(tmp); /* ref new parent */
1470 hammer2_chain_unlock(parent); /* unlock old parent */
1471 /* lock new parent */
1472 hammer2_chain_lock(tmp, how_maybe |
1473 HAMMER2_RESOLVE_NOREF);
1474 *parentp = parent = tmp; /* new parent */
1479 * Locate the blockref array. Currently we do a fully associative
1480 * search through the array.
1482 switch(parent->bref.type) {
1483 case HAMMER2_BREF_TYPE_INODE:
1485 * Special shortcut for embedded data returns the inode
1486 * itself. Callers must detect this condition and access
1487 * the embedded data (the strategy code does this for us).
1489 * This is only applicable to regular files and softlinks.
1491 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1492 if (flags & HAMMER2_LOOKUP_NOLOCK)
1493 hammer2_chain_ref(parent);
1495 hammer2_chain_lock(parent, how_always);
1498 base = &parent->data->ipdata.u.blockset.blockref[0];
1499 count = HAMMER2_SET_COUNT;
1501 case HAMMER2_BREF_TYPE_INDIRECT:
1502 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1503 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1505 * Optimize indirect blocks in the INITIAL state to avoid
1508 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1511 if (parent->data == NULL)
1512 panic("parent->data is NULL");
1513 base = &parent->data->npdata.blockref[0];
1515 count = parent->bytes / sizeof(hammer2_blockref_t);
1517 case HAMMER2_BREF_TYPE_VOLUME:
1518 base = &hmp->voldata.sroot_blockset.blockref[0];
1519 count = HAMMER2_SET_COUNT;
1522 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1524 base = NULL; /* safety */
1525 count = 0; /* safety */
1529 * If the element and key overlap we use the element.
1531 * NOTE! Deleted elements are effectively invisible. Deletions
1532 * proactively clear the parent bref to the deleted child
1533 * so we do not try to shadow here to avoid parent updates
1534 * (which would be difficult since multiple deleted elements
1535 * might represent different flush synchronization points).
1538 for (i = 0; i < count; ++i) {
1539 tmp = hammer2_chain_find(parent, i);
1541 if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1542 hammer2_chain_drop(tmp);
1546 KKASSERT(bref->type != 0);
1547 } else if (base == NULL || base[i].type == 0) {
1552 scan_beg = bref->key;
1553 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1555 hammer2_chain_drop(tmp);
1556 if (key_beg <= scan_end && key_end >= scan_beg)
1560 if (key_beg == key_end)
1562 return (hammer2_chain_next(parentp, NULL,
1563 key_beg, key_end, flags));
1567 * Acquire the new chain element. If the chain element is an
1568 * indirect block we must search recursively.
1570 * It is possible for the tmp chain above to be removed from
1571 * the RBTREE but the parent lock ensures it would not have been
1572 * destroyed from the media, so the chain_get() code will simply
1573 * reload it from the media in that case.
1575 chain = hammer2_chain_get(parent, i, flags);
1580 * If the chain element is an indirect block it becomes the new
1581 * parent and we loop on it.
1583 * The parent always has to be locked with at least RESOLVE_MAYBE
1584 * so we can access its data. It might need a fixup if the caller
1585 * passed incompatible flags. Be careful not to cause a deadlock
1586 * as a data-load requires an exclusive lock.
1588 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1589 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1590 hammer2_chain_unlock(parent);
1591 *parentp = parent = chain;
1592 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1593 hammer2_chain_lock(chain, how_maybe |
1594 HAMMER2_RESOLVE_NOREF);
1595 } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
1596 chain->data == NULL) {
1597 hammer2_chain_ref(chain);
1598 hammer2_chain_unlock(chain);
1599 hammer2_chain_lock(chain, how_maybe |
1600 HAMMER2_RESOLVE_NOREF);
1606 * All done, return the chain
1612 * After having issued a lookup we can iterate all matching keys.
1614 * If chain is non-NULL we continue the iteration from just after it's index.
1616 * If chain is NULL we assume the parent was exhausted and continue the
1617 * iteration at the next parent.
1619 * parent must be locked on entry and remains locked throughout. chain's
1620 * lock status must match flags. Chain is always at least referenced.
1623 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1624 hammer2_key_t key_beg, hammer2_key_t key_end,
1627 hammer2_mount_t *hmp;
1628 hammer2_chain_t *parent;
1629 hammer2_chain_t *tmp;
1630 hammer2_blockref_t *base;
1631 hammer2_blockref_t *bref;
1632 hammer2_key_t scan_beg;
1633 hammer2_key_t scan_end;
1635 int how_maybe = HAMMER2_RESOLVE_MAYBE;
1638 if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1639 how_maybe |= HAMMER2_RESOLVE_SHARED;
1646 * Calculate the next index and recalculate the parent if necessary.
1650 * Continue iteration within current parent. If not NULL
1651 * the passed-in chain may or may not be locked, based on
1652 * the LOOKUP_NOLOCK flag (passed in as returned from lookup
1655 i = chain->index + 1;
1656 if (flags & HAMMER2_LOOKUP_NOLOCK)
1657 hammer2_chain_drop(chain);
1659 hammer2_chain_unlock(chain);
1662 * Any scan where the lookup returned degenerate data embedded
1663 * in the inode has an invalid index and must terminate.
1665 if (chain == parent)
1668 } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1669 parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1671 * We reached the end of the iteration.
1676 * Continue iteration with next parent unless the current
1677 * parent covers the range.
1679 scan_beg = parent->bref.key;
1680 scan_end = scan_beg +
1681 ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1682 if (key_beg >= scan_beg && key_end <= scan_end)
1685 i = parent->index + 1;
1687 * XXX flush synchronization
1689 tmp = parent->parent;
1690 while (tmp->duplink &&
1691 (tmp->flags & HAMMER2_CHAIN_DELETED)) {
1694 hammer2_chain_ref(tmp); /* ref new parent */
1695 hammer2_chain_unlock(parent); /* unlock old parent */
1696 /* lock new parent */
1697 hammer2_chain_lock(tmp, how_maybe |
1698 HAMMER2_RESOLVE_NOREF);
1699 *parentp = parent = tmp;
1704 * Locate the blockref array. Currently we do a fully associative
1705 * search through the array.
1707 switch(parent->bref.type) {
1708 case HAMMER2_BREF_TYPE_INODE:
1709 base = &parent->data->ipdata.u.blockset.blockref[0];
1710 count = HAMMER2_SET_COUNT;
1712 case HAMMER2_BREF_TYPE_INDIRECT:
1713 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1714 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1715 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1718 KKASSERT(parent->data != NULL);
1719 base = &parent->data->npdata.blockref[0];
1721 count = parent->bytes / sizeof(hammer2_blockref_t);
1723 case HAMMER2_BREF_TYPE_VOLUME:
1724 base = &hmp->voldata.sroot_blockset.blockref[0];
1725 count = HAMMER2_SET_COUNT;
1728 panic("hammer2_chain_next: unrecognized blockref type: %d",
1730 base = NULL; /* safety */
1731 count = 0; /* safety */
1734 KKASSERT(i <= count);
1737 * Look for the key. If we are unable to find a match and an exact
1738 * match was requested we return NULL. If a range was requested we
1739 * run hammer2_chain_next() to iterate.
1741 * NOTE! Deleted elements are effectively invisible. Deletions
1742 * proactively clear the parent bref to the deleted child
1743 * so we do not try to shadow here to avoid parent updates
1744 * (which would be difficult since multiple deleted elements
1745 * might represent different flush synchronization points).
1749 tmp = hammer2_chain_find(parent, i);
1751 if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1752 hammer2_chain_drop(tmp);
1757 } else if (base == NULL || base[i].type == 0) {
1763 scan_beg = bref->key;
1764 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1766 hammer2_chain_drop(tmp);
1767 if (key_beg <= scan_end && key_end >= scan_beg)
1773 * If we couldn't find a match recurse up a parent to continue the
1780 * Acquire the new chain element. If the chain element is an
1781 * indirect block we must search recursively.
1783 chain = hammer2_chain_get(parent, i, flags);
1788 * If the chain element is an indirect block it becomes the new
1789 * parent and we loop on it.
1791 * The parent always has to be locked with at least RESOLVE_MAYBE
1792 * so we can access its data. It might need a fixup if the caller
1793 * passed incompatible flags. Be careful not to cause a deadlock
1794 * as a data-load requires an exclusive lock.
1796 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1797 chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1798 hammer2_chain_unlock(parent);
1799 *parentp = parent = chain;
1801 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1802 hammer2_chain_lock(parent, how_maybe |
1803 HAMMER2_RESOLVE_NOREF);
1804 } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
1805 parent->data == NULL) {
1806 hammer2_chain_ref(parent);
1807 hammer2_chain_unlock(parent);
1808 hammer2_chain_lock(parent, how_maybe |
1809 HAMMER2_RESOLVE_NOREF);
1816 * All done, return chain
1822 * Create and return a new hammer2 system memory structure of the specified
1823 * key, type and size and insert it under (*parentp). This is a full
1824 * insertion, based on the supplied key/keybits, and may involve creating
1825 * indirect blocks and moving other chains around via delete/duplicate.
1827 * (*parentp) must be exclusive locked and may be replaced on return
1828 * depending on how much work the function had to do.
1830 * (*chainp) usually starts out NULL and returns the newly created chain,
1831 * but if the caller desires the caller may allocate a disconnected chain
1832 * and pass it in instead. (It is also possible for the caller to use
1833 * chain_duplicate() to create a disconnected chain, manipulate it, then
1834 * pass it into this function to insert it).
1836 * This function should NOT be used to insert INDIRECT blocks. It is
1837 * typically used to create/insert inodes and data blocks.
1839 * Caller must pass-in an exclusively locked parent the new chain is to
1840 * be inserted under, and optionally pass-in a disconnected, exclusively
1841 * locked chain to insert (else we create a new chain). The function will
1842 * adjust (*parentp) as necessary and return the existing or new chain.
1845 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
1846 hammer2_chain_t **chainp,
1847 hammer2_key_t key, int keybits, int type, size_t bytes)
1849 hammer2_mount_t *hmp;
1850 hammer2_chain_t *chain;
1851 hammer2_chain_t *child;
1852 hammer2_chain_t *parent = *parentp;
1853 hammer2_blockref_t dummy;
1854 hammer2_blockref_t *base;
1860 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
1864 if (chain == NULL) {
1866 * First allocate media space and construct the dummy bref,
1867 * then allocate the in-memory chain structure.
1869 bzero(&dummy, sizeof(dummy));
1872 dummy.keybits = keybits;
1873 dummy.data_off = hammer2_allocsize(bytes);
1874 dummy.methods = parent->bref.methods;
1875 chain = hammer2_chain_alloc(hmp, &dummy);
1876 hammer2_chain_core_alloc(chain, NULL);
1877 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
1881 * We do NOT set INITIAL here (yet). INITIAL is only
1882 * used for indirect blocks.
1884 * Recalculate bytes to reflect the actual media block
1887 bytes = (hammer2_off_t)1 <<
1888 (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
1889 chain->bytes = bytes;
1892 case HAMMER2_BREF_TYPE_VOLUME:
1893 panic("hammer2_chain_create: called with volume type");
1895 case HAMMER2_BREF_TYPE_INODE:
1896 KKASSERT(bytes == HAMMER2_INODE_BYTES);
1897 chain->data = kmalloc(sizeof(chain->data->ipdata),
1898 hmp->minode, M_WAITOK | M_ZERO);
1900 case HAMMER2_BREF_TYPE_INDIRECT:
1901 panic("hammer2_chain_create: cannot be used to"
1902 "create indirect block");
1904 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1905 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1906 panic("hammer2_chain_create: cannot be used to"
1907 "create freemap root or node");
1909 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1910 case HAMMER2_BREF_TYPE_DATA:
1912 /* leave chain->data NULL */
1913 KKASSERT(chain->data == NULL);
1918 * Potentially update the chain's key/keybits.
1920 chain->bref.key = key;
1921 chain->bref.keybits = keybits;
1926 * Locate a free blockref in the parent's array
1928 switch(parent->bref.type) {
1929 case HAMMER2_BREF_TYPE_INODE:
1930 KKASSERT((parent->data->ipdata.op_flags &
1931 HAMMER2_OPFLAG_DIRECTDATA) == 0);
1932 KKASSERT(parent->data != NULL);
1933 base = &parent->data->ipdata.u.blockset.blockref[0];
1934 count = HAMMER2_SET_COUNT;
1936 case HAMMER2_BREF_TYPE_INDIRECT:
1937 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1938 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1939 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1942 KKASSERT(parent->data != NULL);
1943 base = &parent->data->npdata.blockref[0];
1945 count = parent->bytes / sizeof(hammer2_blockref_t);
1947 case HAMMER2_BREF_TYPE_VOLUME:
1948 KKASSERT(parent->data != NULL);
1949 base = &hmp->voldata.sroot_blockset.blockref[0];
1950 count = HAMMER2_SET_COUNT;
1953 panic("hammer2_chain_create: unrecognized blockref type: %d",
1960 * Scan for an unallocated bref, also skipping any slots occupied
1961 * by in-memory chain elements that may not yet have been updated
1962 * in the parent's bref array.
1964 * We don't have to hold the spinlock to save an empty slot as
1965 * new slots can only transition from empty if the parent is
1966 * locked exclusively.
1969 spin_lock(&parent->core->cst.spin);
1970 for (i = 0; i < count; ++i) {
1971 child = hammer2_chain_find_locked(parent, i);
1973 if (child->flags & HAMMER2_CHAIN_DELETED)
1979 if (base[i].type == 0)
1982 spin_unlock(&parent->core->cst.spin);
1985 * If no free blockref could be found we must create an indirect
1986 * block and move a number of blockrefs into it. With the parent
1987 * locked we can safely lock each child in order to move it without
1988 * causing a deadlock.
1990 * This may return the new indirect block or the old parent depending
1991 * on where the key falls. NULL is returned on error.
1994 hammer2_chain_t *nparent;
1996 nparent = hammer2_chain_create_indirect(trans, parent,
1999 if (nparent == NULL) {
2001 hammer2_chain_free(chain);
2005 if (parent != nparent) {
2006 hammer2_chain_unlock(parent);
2007 parent = *parentp = nparent;
2013 * Link the chain into its parent. Later on we will have to set
2014 * the MOVED bit in situations where we don't mark the new chain
2015 * as being modified.
2017 if (chain->parent != NULL)
2018 panic("hammer2: hammer2_chain_create: chain already connected");
2019 KKASSERT(chain->parent == NULL);
2020 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2022 chain->parent = parent;
2024 KKASSERT(parent->refs > 0);
2025 spin_lock(&parent->core->cst.spin);
2026 if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, chain))
2027 panic("hammer2_chain_link: collision");
2028 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2029 hammer2_chain_ref(parent); /* chain->parent ref */
2030 spin_unlock(&parent->core->cst.spin);
2033 * (allocated) indicates that this is a newly-created chain element
2034 * rather than a renamed chain element.
2036 * In this situation we want to place the chain element in
2037 * the MODIFIED state. The caller expects it to NOT be in the
2040 * The data area will be set up as follows:
2042 * VOLUME not allowed here.
2044 * INODE embedded data are will be set-up.
2046 * INDIRECT not allowed here.
2048 * DATA no data area will be set-up (caller is expected
2049 * to have logical buffers, we don't want to alias
2050 * the data onto device buffers!).
2053 switch(chain->bref.type) {
2054 case HAMMER2_BREF_TYPE_DATA:
2055 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2056 hammer2_chain_modify(trans, &chain,
2057 HAMMER2_MODIFY_OPTDATA |
2058 HAMMER2_MODIFY_ASSERTNOCOPY);
2060 case HAMMER2_BREF_TYPE_INDIRECT:
2061 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2062 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2063 /* not supported in this function */
2064 panic("hammer2_chain_create: bad type");
2065 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2066 hammer2_chain_modify(trans, &chain,
2067 HAMMER2_MODIFY_OPTDATA |
2068 HAMMER2_MODIFY_ASSERTNOCOPY);
2071 hammer2_chain_modify(trans, &chain,
2072 HAMMER2_MODIFY_ASSERTNOCOPY);
2077 * When reconnecting a chain we must set MOVED and setsubmod
2078 * so the flush recognizes that it must update the bref in
2081 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2082 hammer2_chain_ref(chain);
2083 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2085 hammer2_chain_parent_setsubmod(trans, chain);
2095 * Replace (*chainp) with a duplicate. The original *chainp is unlocked
2096 * and the replacement will be returned locked. Both the original and the
2097 * new chain will share the same RBTREE (have the same chain->core), with
2098 * the new chain becoming the 'current' chain (meaning it is the first in
2099 * the linked list at core->chain_first).
2101 * If (parent, i) then the new duplicated chain is inserted under the parent
2102 * at the specified index (the parent must not have a ref at that index).
2104 * If (NULL, -1) then the new duplicated chain is not inserted anywhere,
2105 * similar to if it had just been chain_alloc()'d (suitable for passing into
2106 * hammer2_chain_create() after this function returns).
2108 * NOTE! Duplication is used in order to retain the original topology to
2109 * support flush synchronization points. Both the original and the
2110 * new chain will have the same transaction id and thus the operation
2111 * appears atomic on the media.
2114 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t *parent, int i,
2115 hammer2_chain_t **chainp, hammer2_blockref_t *bref)
2117 hammer2_mount_t *hmp = trans->hmp;
2118 hammer2_blockref_t *base;
2119 hammer2_chain_t *ochain;
2120 hammer2_chain_t *nchain;
2121 hammer2_chain_t *scan;
2126 * First create a duplicate of the chain structure, associating
2127 * it with the same core, making it the same size, pointing it
2128 * to the same bref (the same media block), and copying any inline
2133 bref = &ochain->bref;
2134 nchain = hammer2_chain_alloc(hmp, bref);
2135 hammer2_chain_core_alloc(nchain, ochain->core);
2137 bytes = (hammer2_off_t)1 <<
2138 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2139 nchain->bytes = bytes;
2142 * Be sure to copy the INITIAL flag as well or we could end up
2143 * loading garbage from the bref.
2145 if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2146 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2149 * If the old chain is modified the new one must be too,
2150 * but we only want to allocate a new bref.
2152 if (ochain->flags & HAMMER2_CHAIN_MODIFIED) {
2154 * When duplicating chains the MODIFIED state is inherited.
2155 * A new bref typically must be allocated. However, file
2156 * data chains may already have the data offset assigned
2157 * to a logical buffer cache buffer so we absolutely cannot
2158 * allocate a new bref here for TYPE_DATA.
2160 * Basically the flusher core only dumps media topology
2161 * and meta-data, not file data. The VOP_FSYNC code deals
2162 * with the file data. XXX need back-pointer to inode.
2164 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2165 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MODIFIED);
2166 hammer2_chain_ref(nchain);
2168 hammer2_chain_modify(trans, &nchain,
2169 HAMMER2_MODIFY_OPTDATA |
2170 HAMMER2_MODIFY_ASSERTNOCOPY);
2172 } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2174 * When duplicating chains in the INITITAL state we need
2175 * to ensure that the chain is marked modified so a
2176 * block is properly assigned to it, otherwise the MOVED
2177 * bit won't do the right thing.
2179 KKASSERT (nchain->bref.type != HAMMER2_BREF_TYPE_DATA);
2180 hammer2_chain_modify(trans, &nchain,
2181 HAMMER2_MODIFY_OPTDATA |
2182 HAMMER2_MODIFY_ASSERTNOCOPY);
2184 if (parent || (ochain->flags & HAMMER2_CHAIN_MOVED)) {
2185 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2186 hammer2_chain_ref(nchain);
2188 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2190 switch(nchain->bref.type) {
2191 case HAMMER2_BREF_TYPE_VOLUME:
2192 panic("hammer2_chain_duplicate: cannot be called w/volhdr");
2194 case HAMMER2_BREF_TYPE_INODE:
2195 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2197 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2198 hmp->minode, M_WAITOK | M_ZERO);
2199 nchain->data->ipdata = ochain->data->ipdata;
2202 case HAMMER2_BREF_TYPE_INDIRECT:
2203 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2205 bcopy(ochain->data, nchain->data,
2209 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2210 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2211 panic("hammer2_chain_duplicate: cannot be used to"
2212 "create a freemap root or node");
2214 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2215 case HAMMER2_BREF_TYPE_DATA:
2217 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2219 bcopy(ochain->data, nchain->data,
2222 /* leave chain->data NULL */
2223 KKASSERT(nchain->data == NULL);
2228 * Both chains must be locked for us to be able to set the
2229 * duplink. The caller may expect valid data.
2231 * Unmodified duplicated blocks may have the same bref, we
2232 * must be careful to avoid buffer cache deadlocks so we
2233 * unlock the old chain before resolving the new one.
2235 * Insert nchain at the end of the duplication list.
2237 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2238 /* extra ref still present from original allocation */
2240 spin_lock(&ochain->core->cst.spin);
2241 KKASSERT(nchain->duplink == NULL);
2242 nchain->duplink = ochain->duplink;
2243 ochain->duplink = nchain; /* inherits excess ref from alloc */
2244 spin_unlock(&ochain->core->cst.spin);
2246 hammer2_chain_unlock(ochain);
2248 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2249 hammer2_chain_unlock(nchain);
2252 * If parent is not NULL, insert into the parent at the requested
2253 * index. The newly duplicated chain must be marked MOVED and
2254 * SUBMODIFIED set in its parent(s).
2258 * Locate a free blockref in the parent's array
2260 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
2261 switch(parent->bref.type) {
2262 case HAMMER2_BREF_TYPE_INODE:
2263 KKASSERT((parent->data->ipdata.op_flags &
2264 HAMMER2_OPFLAG_DIRECTDATA) == 0);
2265 KKASSERT(parent->data != NULL);
2266 base = &parent->data->ipdata.u.blockset.blockref[0];
2267 count = HAMMER2_SET_COUNT;
2269 case HAMMER2_BREF_TYPE_INDIRECT:
2270 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2271 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2272 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2275 KKASSERT(parent->data != NULL);
2276 base = &parent->data->npdata.blockref[0];
2278 count = parent->bytes / sizeof(hammer2_blockref_t);
2280 case HAMMER2_BREF_TYPE_VOLUME:
2281 KKASSERT(parent->data != NULL);
2282 base = &hmp->voldata.sroot_blockset.blockref[0];
2283 count = HAMMER2_SET_COUNT;
2286 panic("hammer2_chain_create: unrecognized "
2287 "blockref type: %d",
2292 KKASSERT(i >= 0 && i < count);
2294 nchain->parent = parent;
2296 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2297 KKASSERT(parent->refs > 0);
2299 spin_lock(&parent->core->cst.spin);
2300 scan = hammer2_chain_find_locked(parent, i);
2301 KKASSERT(base == NULL || base[i].type == 0 ||
2303 (scan->flags & HAMMER2_CHAIN_DELETED));
2304 if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree,
2306 panic("hammer2_chain_link: collision");
2308 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
2309 hammer2_chain_ref(parent); /* nchain->parent ref */
2310 spin_unlock(&parent->core->cst.spin);
2312 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2313 hammer2_chain_ref(nchain);
2314 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2316 hammer2_chain_parent_setsubmod(trans, nchain);
2321 * Create a snapshot of the specified {parent, chain} with the specified
2324 * (a) We create a duplicate connected to the super-root as the specified
2327 * (b) We issue a restricted flush using the current transaction on the
2330 * (c) We disconnect and reallocate the duplicate's core.
2333 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_inode_t *ip,
2334 hammer2_ioc_pfs_t *pfs)
2336 hammer2_mount_t *hmp = trans->hmp;
2337 hammer2_chain_t *chain;
2338 hammer2_chain_t *nchain;
2339 hammer2_chain_t *parent;
2340 hammer2_inode_data_t *ipdata;
2341 size_t name_len = strlen(pfs->name);
2342 hammer2_key_t lhc = hammer2_dirhash(pfs->name, name_len);
2346 * Create disconnected duplicate
2348 KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2350 hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2351 hammer2_chain_duplicate(trans, NULL, -1, &nchain, NULL);
2352 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_RECYCLE);
2355 * Create named entry in the super-root.
2357 parent = hammer2_chain_lookup_init(hmp->schain, 0);
2359 while (error == 0) {
2360 chain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
2363 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
2365 hammer2_chain_unlock(chain);
2369 hammer2_chain_create(trans, &parent, &nchain, lhc, 0,
2370 HAMMER2_BREF_TYPE_INODE,
2371 HAMMER2_INODE_BYTES);
2372 hammer2_chain_modify(trans, &nchain, HAMMER2_MODIFY_ASSERTNOCOPY);
2373 hammer2_chain_lookup_done(parent);
2374 parent = NULL; /* safety */
2379 ipdata = &nchain->data->ipdata;
2380 ipdata->name_key = lhc;
2381 ipdata->name_len = name_len;
2382 ksnprintf(ipdata->filename, sizeof(ipdata->filename), "%s", pfs->name);
2385 * Set PFS type, generate a unique filesystem id, and generate
2386 * a cluster id. Use the same clid when snapshotting a PFS root,
2387 * which theoretically allows the snapshot to be used as part of
2388 * the same cluster (perhaps as a cache).
2390 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2391 kern_uuidgen(&ipdata->pfs_fsid, 1);
2392 if (ip->chain == ip->pmp->rchain)
2393 ipdata->pfs_clid = ip->chain->data->ipdata.pfs_clid;
2395 kern_uuidgen(&ipdata->pfs_clid, 1);
2398 * Issue a restricted flush of the snapshot. This is a synchronous
2401 trans->flags |= HAMMER2_TRANS_RESTRICTED;
2402 hammer2_chain_flush(trans, nchain);
2403 trans->flags &= ~HAMMER2_TRANS_RESTRICTED;
2406 * Remove the duplication
2409 KKASSERT(chain->duplink == nchain);
2410 KKASSERT(chain->core == nchain->core);
2411 KKASSERT(nchain->refs >= 2);
2412 chain->duplink = nchain->duplink;
2413 hammer2_chain_drop(nchain);
2415 kprintf("snapshot %s nchain->refs %d nchain->flags %08x\n",
2416 pfs->name, nchain->refs, nchain->flags);
2417 hammer2_chain_unlock(nchain);
2423 * Create an indirect block that covers one or more of the elements in the
2424 * current parent. Either returns the existing parent with no locking or
2425 * ref changes or returns the new indirect block locked and referenced
2426 * and leaving the original parent lock/ref intact as well.
2428 * If an error occurs, NULL is returned and *errorp is set to the error.
2430 * The returned chain depends on where the specified key falls.
2432 * The key/keybits for the indirect mode only needs to follow three rules:
2434 * (1) That all elements underneath it fit within its key space and
2436 * (2) That all elements outside it are outside its key space.
2438 * (3) When creating the new indirect block any elements in the current
2439 * parent that fit within the new indirect block's keyspace must be
2440 * moved into the new indirect block.
2442 * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2443 * keyspace the the current parent, but lookup/iteration rules will
2444 * ensure (and must ensure) that rule (2) for all parents leading up
2445 * to the nearest inode or the root volume header is adhered to. This
2446 * is accomplished by always recursing through matching keyspaces in
2447 * the hammer2_chain_lookup() and hammer2_chain_next() API.
2449 * The current implementation calculates the current worst-case keyspace by
2450 * iterating the current parent and then divides it into two halves, choosing
2451 * whichever half has the most elements (not necessarily the half containing
2452 * the requested key).
2454 * We can also opt to use the half with the least number of elements. This
2455 * causes lower-numbered keys (aka logical file offsets) to recurse through
2456 * fewer indirect blocks and higher-numbered keys to recurse through more.
2457 * This also has the risk of not moving enough elements to the new indirect
2458 * block and being forced to create several indirect blocks before the element
2461 * Must be called with an exclusively locked parent.
2465 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2466 hammer2_key_t create_key, int create_bits,
2469 hammer2_mount_t *hmp = trans->hmp;
2470 hammer2_blockref_t *base;
2471 hammer2_blockref_t *bref;
2472 hammer2_chain_t *chain;
2473 hammer2_chain_t *child;
2474 hammer2_chain_t *ichain;
2475 hammer2_chain_t dummy;
2476 hammer2_key_t key = create_key;
2477 int keybits = create_bits;
2485 * Calculate the base blockref pointer or NULL if the chain
2486 * is known to be empty. We need to calculate the array count
2487 * for RB lookups either way.
2489 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
2492 /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2493 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2496 switch(parent->bref.type) {
2497 case HAMMER2_BREF_TYPE_INODE:
2498 count = HAMMER2_SET_COUNT;
2500 case HAMMER2_BREF_TYPE_INDIRECT:
2501 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2502 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2503 count = parent->bytes / sizeof(hammer2_blockref_t);
2505 case HAMMER2_BREF_TYPE_VOLUME:
2506 count = HAMMER2_SET_COUNT;
2509 panic("hammer2_chain_create_indirect: "
2510 "unrecognized blockref type: %d",
2516 switch(parent->bref.type) {
2517 case HAMMER2_BREF_TYPE_INODE:
2518 base = &parent->data->ipdata.u.blockset.blockref[0];
2519 count = HAMMER2_SET_COUNT;
2521 case HAMMER2_BREF_TYPE_INDIRECT:
2522 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2523 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2524 base = &parent->data->npdata.blockref[0];
2525 count = parent->bytes / sizeof(hammer2_blockref_t);
2527 case HAMMER2_BREF_TYPE_VOLUME:
2528 base = &hmp->voldata.sroot_blockset.blockref[0];
2529 count = HAMMER2_SET_COUNT;
2532 panic("hammer2_chain_create_indirect: "
2533 "unrecognized blockref type: %d",
2541 * Scan for an unallocated bref, also skipping any slots occupied
2542 * by in-memory chain elements which may not yet have been updated
2543 * in the parent's bref array.
2545 * Deleted elements are ignored.
2547 bzero(&dummy, sizeof(dummy));
2548 dummy.delete_tid = HAMMER2_MAX_TID;
2550 spin_lock(&parent->core->cst.spin);
2551 for (i = 0; i < count; ++i) {
2554 child = hammer2_chain_find_locked(parent, i);
2556 if (child->flags & HAMMER2_CHAIN_DELETED)
2558 bref = &child->bref;
2559 } else if (base && base[i].type) {
2566 * Expand our calculated key range (key, keybits) to fit
2567 * the scanned key. nkeybits represents the full range
2568 * that we will later cut in half (two halves @ nkeybits - 1).
2571 if (nkeybits < bref->keybits) {
2572 if (bref->keybits > 64) {
2573 kprintf("bad bref index %d chain %p bref %p\n", i, chain, bref);
2576 nkeybits = bref->keybits;
2578 while (nkeybits < 64 &&
2579 (~(((hammer2_key_t)1 << nkeybits) - 1) &
2580 (key ^ bref->key)) != 0) {
2585 * If the new key range is larger we have to determine
2586 * which side of the new key range the existing keys fall
2587 * under by checking the high bit, then collapsing the
2588 * locount into the hicount or vise-versa.
2590 if (keybits != nkeybits) {
2591 if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
2602 * The newly scanned key will be in the lower half or the
2603 * higher half of the (new) key range.
2605 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
2610 spin_unlock(&parent->core->cst.spin);
2611 bref = NULL; /* now invalid (safety) */
2614 * Adjust keybits to represent half of the full range calculated
2615 * above (radix 63 max)
2620 * Select whichever half contains the most elements. Theoretically
2621 * we can select either side as long as it contains at least one
2622 * element (in order to ensure that a free slot is present to hold
2623 * the indirect block).
2625 key &= ~(((hammer2_key_t)1 << keybits) - 1);
2626 if (hammer2_indirect_optimize) {
2628 * Insert node for least number of keys, this will arrange
2629 * the first few blocks of a large file or the first few
2630 * inodes in a directory with fewer indirect blocks when
2633 if (hicount < locount && hicount != 0)
2634 key |= (hammer2_key_t)1 << keybits;
2636 key &= ~(hammer2_key_t)1 << keybits;
2639 * Insert node for most number of keys, best for heavily
2642 if (hicount > locount)
2643 key |= (hammer2_key_t)1 << keybits;
2645 key &= ~(hammer2_key_t)1 << keybits;
2649 * How big should our new indirect block be? It has to be at least
2650 * as large as its parent.
2652 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2653 nbytes = HAMMER2_IND_BYTES_MIN;
2655 nbytes = HAMMER2_IND_BYTES_MAX;
2656 if (nbytes < count * sizeof(hammer2_blockref_t))
2657 nbytes = count * sizeof(hammer2_blockref_t);
2660 * Ok, create our new indirect block
2662 switch(parent->bref.type) {
2663 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2664 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2665 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2668 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2671 dummy.bref.key = key;
2672 dummy.bref.keybits = keybits;
2673 dummy.bref.data_off = hammer2_allocsize(nbytes);
2674 dummy.bref.methods = parent->bref.methods;
2676 ichain = hammer2_chain_alloc(hmp, &dummy.bref);
2677 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2678 hammer2_chain_core_alloc(ichain, NULL);
2679 hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2680 hammer2_chain_drop(ichain); /* excess ref from alloc */
2683 * We have to mark it modified to allocate its block, but use
2684 * OPTDATA to allow it to remain in the INITIAL state. Otherwise
2685 * it won't be acted upon by the flush code.
2687 hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
2690 * Iterate the original parent and move the matching brefs into
2691 * the new indirect block.
2693 * XXX handle flushes.
2695 spin_lock(&parent->core->cst.spin);
2696 for (i = 0; i < count; ++i) {
2698 * For keying purposes access the bref from the media or
2699 * from our in-memory cache. In cases where the in-memory
2700 * cache overrides the media the keyrefs will be the same
2701 * anyway so we can avoid checking the cache when the media
2704 child = hammer2_chain_find_locked(parent, i);
2706 if (child->flags & HAMMER2_CHAIN_DELETED) {
2707 if (ichain->index < 0)
2711 bref = &child->bref;
2712 } else if (base && base[i].type) {
2715 if (ichain->index < 0)
2721 * Skip keys not in the chosen half (low or high), only bit
2722 * (keybits - 1) needs to be compared but for safety we
2723 * will compare all msb bits plus that bit again.
2725 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2726 (key ^ bref->key)) != 0) {
2731 * This element is being moved from the parent, its slot
2732 * is available for our new indirect block.
2734 if (ichain->index < 0)
2738 * Load the new indirect block by acquiring or allocating
2739 * the related chain entries, then move them to the new
2740 * parent (ichain) by deleting them from their old location
2741 * and inserting a duplicate of the chain and any modified
2742 * sub-chain in the new location.
2744 * We must set MOVED in the chain being duplicated and
2745 * SUBMODIFIED in the parent(s) so the flush code knows
2746 * what is going on. The latter is done after the loop.
2748 * WARNING! chain->cst.spin must be held when chain->parent is
2749 * modified, even though we own the full blown lock,
2750 * to deal with setsubmod and rename races.
2751 * (XXX remove this req).
2753 spin_unlock(&parent->core->cst.spin);
2754 chain = hammer2_chain_get(parent, i, HAMMER2_LOOKUP_NODATA);
2755 hammer2_chain_delete(trans, parent, chain);
2756 hammer2_chain_duplicate(trans, ichain, i, &chain, NULL);
2758 hammer2_chain_unlock(chain);
2759 KKASSERT(parent->refs > 0);
2761 spin_lock(&parent->core->cst.spin);
2763 spin_unlock(&parent->core->cst.spin);
2766 * Insert the new indirect block into the parent now that we've
2767 * cleared out some entries in the parent. We calculated a good
2768 * insertion index in the loop above (ichain->index).
2770 * We don't have to set MOVED here because we mark ichain modified
2771 * down below (so the normal modified -> flush -> set-moved sequence
2774 * The insertion shouldn't race as this is a completely new block
2775 * and the parent is locked.
2777 if (ichain->index < 0)
2778 kprintf("indirect parent %p count %d key %016jx/%d\n",
2779 parent, count, (intmax_t)key, keybits);
2780 KKASSERT(ichain->index >= 0);
2781 KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2782 spin_lock(&parent->core->cst.spin);
2783 if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, ichain))
2784 panic("hammer2_chain_create_indirect: ichain insertion");
2785 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_ONRBTREE);
2786 ichain->parent = parent;
2787 hammer2_chain_ref(parent); /* ichain->parent ref */
2788 spin_unlock(&parent->core->cst.spin);
2789 KKASSERT(parent->duplink == NULL); /* XXX mus be inside spin */
2792 * Mark the new indirect block modified after insertion, which
2793 * will propagate up through parent all the way to the root and
2794 * also allocate the physical block in ichain for our caller,
2795 * and assign ichain->data to a pre-zero'd space (because there
2796 * is not prior data to copy into it).
2798 * We have to set SUBMODIFIED in ichain's flags manually so the
2799 * flusher knows it has to recurse through it to get to all of
2800 * our moved blocks, then call setsubmod() to set the bit
2803 /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
2804 hammer2_chain_parent_setsubmod(trans, ichain);
2805 atomic_set_int(&ichain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2808 * Figure out what to return.
2810 if (create_bits > keybits) {
2812 * Key being created is way outside the key range,
2813 * return the original parent.
2815 hammer2_chain_unlock(ichain);
2816 } else if (~(((hammer2_key_t)1 << keybits) - 1) &
2817 (create_key ^ key)) {
2819 * Key being created is outside the key range,
2820 * return the original parent.
2822 hammer2_chain_unlock(ichain);
2825 * Otherwise its in the range, return the new parent.
2826 * (leave both the new and old parent locked).
2835 * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
2836 * set chain->delete_tid.
2838 * This function does NOT generate a modification to the parent. It
2839 * would be nearly impossible to figure out which parent to modify anyway.
2840 * Such modifications are handled by the flush code and are properly merged
2841 * using the flush synchronization point.
2843 * The find/get code will properly overload the RBTREE check on top of
2844 * the bref check to detect deleted entries.
2846 * This function is NOT recursive. Any entity already pushed into the
2847 * chain (such as an inode) may still need visibility into its contents,
2848 * as well as the ability to read and modify the contents. For example,
2849 * for an unlinked file which is still open.
2851 * NOTE: This function does NOT set chain->modify_tid, allowing future
2852 * code to distinguish between live and deleted chains by testing
2855 * NOTE: Deletions normally do not occur in the middle of a duplication
2856 * chain but we use a trick for hardlink migration that refactors
2857 * the originating inode without deleting it, so we make no assumptions
2861 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
2862 hammer2_chain_t *chain)
2864 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
2867 * Nothing to do if already marked.
2869 if (chain->flags & HAMMER2_CHAIN_DELETED)
2873 * We must set MOVED along with DELETED for the flush code to
2874 * recognize the operation and properly disconnect the chain
2877 * The setting of DELETED causes finds, lookups, and _next iterations
2878 * to no longer recognize the chain. RB_SCAN()s will still have
2879 * visibility (needed for flush serialization points).
2881 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2882 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2883 hammer2_chain_ref(chain);
2884 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2886 chain->delete_tid = trans->sync_tid;
2887 hammer2_chain_parent_setsubmod(trans, chain);
2891 hammer2_chain_wait(hammer2_chain_t *chain)
2893 tsleep(chain, 0, "chnflw", 1);