merge
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2012 The DragonFly Project.  All rights reserved.
3  *
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>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
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
17  *    distribution.
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.
21  *
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
33  * SUCH DAMAGE.
34  */
35 /*
36  * This subsystem handles direct and indirect block searches, recursions,
37  * creation, and deletion.  Chains of blockrefs are tracked and modifications
38  * are flagged for propagation... eventually all the way back to the volume
39  * header.  Any chain except the volume header can be flushed to disk at
40  * any time... none of it matters until the volume header is dealt with
41  * (which is not here, see hammer2_vfsops.c for the volume header disk
42  * sequencing).
43  *
44  * Serialized flushes are not handled here, see hammer2_flush.c.  This module
45  * can essentially work on the current version of data, which can be in memory
46  * as well as on-disk due to the above.  However, we are responsible for
47  * making a copy of the state when a modified chain is part of a flush
48  * and we attempt to modify it again before the flush gets to it.  In that
49  * situation we create an allocated copy of the state that the flush can
50  * deal with.  If a chain undergoing deletion is part of a flush it is
51  * marked DELETED and its bref index is kept intact for the flush, but the
52  * chain is thereafter ignored by this module's because it is no longer
53  * current.
54  */
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
59 #include <sys/lock.h>
60 #include <sys/uuid.h>
61
62 #include "hammer2.h"
63
64 static int hammer2_indirect_optimize;   /* XXX SYSCTL */
65
66 static hammer2_chain_t *hammer2_chain_create_indirect(
67                         hammer2_mount_t *hmp, hammer2_chain_t *parent,
68                         hammer2_key_t key, int keybits,
69                         int *errorp);
70
71 /*
72  * We use a red-black tree to guarantee safe lookups under shared locks.
73  */
74 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
75
76 int
77 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
78 {
79         return(chain2->index - chain1->index);
80 }
81
82 /*
83  * Recursively mark the parent chain elements so flushes can find
84  * modified elements.  Stop when we hit a chain already flagged
85  * SUBMODIFIED, but ignore the SUBMODIFIED bit that might be set
86  * in chain itself.
87  *
88  * SUBMODIFIED is not set on the chain passed in.
89  *
90  * The chain->cst.spin lock can be held to stabilize the chain->parent
91  * pointer.  The first parent is stabilized by virtue of chain being
92  * fully locked.
93  */
94 void
95 hammer2_chain_parent_setsubmod(hammer2_mount_t *hmp, hammer2_chain_t *chain)
96 {
97         hammer2_chain_t *parent;
98
99         parent = chain->parent;
100         if (parent && (parent->flags & HAMMER2_CHAIN_SUBMODIFIED) == 0) {
101                 spin_lock(&parent->cst.spin);
102                 for (;;) {
103                         atomic_set_int(&parent->flags,
104                                        HAMMER2_CHAIN_SUBMODIFIED);
105                         if ((chain = parent->parent) == NULL)
106                                 break;
107                         spin_lock(&chain->cst.spin);    /* upward interlock */
108                         spin_unlock(&parent->cst.spin);
109                         parent = chain;
110                 }
111                 spin_unlock(&parent->cst.spin);
112         }
113 }
114
115 /*
116  * Allocate a new disconnected chain element representing the specified
117  * bref.  The chain element is locked exclusively and refs is set to 1.
118  *
119  * This essentially allocates a system memory structure representing one
120  * of the media structure types, including inodes.
121  */
122 hammer2_chain_t *
123 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_blockref_t *bref)
124 {
125         hammer2_chain_t *chain;
126         hammer2_inode_t *ip;
127         hammer2_indblock_t *np;
128         hammer2_data_t *dp;
129         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
130
131         /*
132          * Construct the appropriate system structure.
133          */
134         switch(bref->type) {
135         case HAMMER2_BREF_TYPE_INODE:
136                 ip = kmalloc(sizeof(*ip), hmp->minode, M_WAITOK | M_ZERO);
137                 chain = &ip->chain;
138                 chain->u.ip = ip;
139                 ip->hmp = hmp;
140                 break;
141         case HAMMER2_BREF_TYPE_INDIRECT:
142                 np = kmalloc(sizeof(*np), hmp->mchain, M_WAITOK | M_ZERO);
143                 chain = &np->chain;
144                 chain->u.np = np;
145                 break;
146         case HAMMER2_BREF_TYPE_DATA:
147                 dp = kmalloc(sizeof(*dp), hmp->mchain, M_WAITOK | M_ZERO);
148                 chain = &dp->chain;
149                 chain->u.dp = dp;
150                 break;
151         case HAMMER2_BREF_TYPE_VOLUME:
152                 chain = NULL;
153                 panic("hammer2_chain_alloc volume type illegal for op");
154         default:
155                 chain = NULL;
156                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
157                       bref->type);
158         }
159
160         /*
161          * Only set bref_flush if the bref has a real media offset, otherwise
162          * the caller has to wait for the chain to be modified/block-allocated
163          * before a blockref can be synchronized with its (future) parent.
164          */
165         chain->bref = *bref;
166         if (bref->data_off & ~HAMMER2_OFF_MASK_RADIX)
167                 chain->bref_flush = *bref;
168         chain->index = -1;              /* not yet assigned */
169         chain->refs = 1;
170         chain->bytes = bytes;
171         ccms_cst_init(&chain->cst, chain);
172         ccms_thread_lock(&chain->cst, CCMS_STATE_EXCLUSIVE);
173
174         return (chain);
175 }
176
177 /*
178  * Deallocate a chain (the step before freeing it).  Remove the chain from
179  * its parent's tree.
180  *
181  * Caller must hold the parent and the chain exclusively locked, and
182  * chain->refs must be 0.
183  *
184  * This function unlocks, removes, and destroys chain, and will recursively
185  * destroy any sub-chains under chain (whos refs must also be 0 at this
186  * point).
187  *
188  * parent can be NULL.
189  */
190 static void
191 hammer2_chain_dealloc(hammer2_mount_t *hmp, hammer2_chain_t *chain)
192 {
193         hammer2_inode_t *ip;
194         hammer2_chain_t *parent;
195         hammer2_chain_t *child;
196
197         KKASSERT(chain->refs == 0);
198         KKASSERT(chain->flushing == 0);
199         KKASSERT((chain->flags &
200                   (HAMMER2_CHAIN_MOVED | HAMMER2_CHAIN_MODIFIED)) == 0);
201
202         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
203                 ip = chain->u.ip;
204         else
205                 ip = NULL;
206
207         /*
208          * If the sub-tree is not empty all the elements on it must have
209          * 0 refs and be deallocatable.
210          */
211         while ((child = RB_ROOT(&chain->rbhead)) != NULL) {
212                 ccms_thread_lock(&child->cst, CCMS_STATE_EXCLUSIVE);
213                 hammer2_chain_dealloc(hmp, child);
214         }
215
216         /*
217          * If the DELETED flag is not set the chain must be removed from
218          * its parent's tree.
219          *
220          * WARNING! chain->cst.spin must be held when chain->parent is
221          *          modified, even though we own the full blown lock,
222          *          to deal with setsubmod and rename races.
223          */
224         if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
225                 spin_lock(&chain->cst.spin);    /* shouldn't be needed */
226                 parent = chain->parent;
227                 RB_REMOVE(hammer2_chain_tree, &parent->rbhead, chain);
228                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
229                 if (ip)
230                         ip->pip = NULL;
231                 chain->parent = NULL;
232                 spin_unlock(&chain->cst.spin);
233         }
234
235         /*
236          * When cleaning out a hammer2_inode we must
237          * also clean out the related ccms_inode.
238          */
239         if (ip)
240                 ccms_cst_uninit(&ip->topo_cst);
241         hammer2_chain_free(hmp, chain);
242 }
243
244 /*
245  * Free a disconnected chain element
246  */
247 void
248 hammer2_chain_free(hammer2_mount_t *hmp, hammer2_chain_t *chain)
249 {
250         void *mem;
251
252         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
253             chain->bref.type == HAMMER2_BREF_TYPE_VOLUME) {
254                 chain->data = NULL;
255         }
256
257         KKASSERT(chain->bp == NULL);
258         KKASSERT(chain->data == NULL);
259         KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_INODE ||
260                  chain->u.ip->vp == NULL);
261         ccms_thread_unlock(&chain->cst);
262         KKASSERT(chain->cst.count == 0);
263         KKASSERT(chain->cst.upgrade == 0);
264
265         if ((mem = chain->u.mem) != NULL) {
266                 chain->u.mem = NULL;
267                 if (chain->bref.type == HAMMER2_BREF_TYPE_INODE)
268                         kfree(mem, hmp->minode);
269                 else
270                         kfree(mem, hmp->mchain);
271         }
272 }
273
274 /*
275  * Add a reference to a chain element, preventing its destruction.
276  *
277  * The parent chain must be locked shared or exclusive or otherwise be
278  * stable and already have a reference.
279  */
280 void
281 hammer2_chain_ref(hammer2_mount_t *hmp, hammer2_chain_t *chain)
282 {
283         u_int refs;
284
285         while (chain) {
286                 refs = chain->refs;
287                 KKASSERT(chain->refs >= 0);
288                 cpu_ccfence();
289                 if (refs == 0) {
290                         /*
291                          * 0 -> 1 transition must bump the refs on the parent
292                          * too.  The caller has stabilized the parent.
293                          */
294                         if (atomic_cmpset_int(&chain->refs, 0, 1)) {
295                                 chain = chain->parent;
296                                 KKASSERT(chain == NULL || chain->refs > 0);
297                         }
298                         /* retry or continue along the parent chain */
299                 } else {
300                         /*
301                          * N -> N+1
302                          */
303                         if (atomic_cmpset_int(&chain->refs, refs, refs + 1))
304                                 break;
305                         /* retry */
306                 }
307         }
308 }
309
310 /*
311  * Drop the callers reference to the chain element.  If the ref count
312  * reaches zero we attempt to recursively drop the parent.
313  *
314  * MOVED and MODIFIED elements hold additional references so it should not
315  * be possible for the count on a modified element to drop to 0.
316  *
317  * The chain element must NOT be locked by the caller on the 1->0 transition.
318  *
319  * The parent might or might not be locked by the caller.  If we are unable
320  * to lock the parent on the 1->0 transition the destruction of the chain
321  * will be deferred but we still recurse upward and drop the ref on the
322  * parent (see the lastdrop() function)
323  */
324 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_mount_t *hmp,
325                                                 hammer2_chain_t *chain);
326
327 void
328 hammer2_chain_drop(hammer2_mount_t *hmp, hammer2_chain_t *chain)
329 {
330         u_int refs;
331
332         while (chain) {
333                 refs = chain->refs;
334                 cpu_ccfence();
335                 KKASSERT(refs > 0);
336                 if (refs == 1) {
337                         /*
338                          * (1) lastdrop successfully drops the chain to 0
339                          *     refs and may may not have destroyed it.
340                          *     lastdrop will return the parent so we can
341                          *     recursively drop the implied ref from the
342                          *     1->0 transition.
343                          *
344                          * (2) lastdrop fails to transition refs from 1 to 0
345                          *     and returns the same chain, we retry.
346                          */
347                         chain = hammer2_chain_lastdrop(hmp, chain);
348                 } else {
349                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1)) {
350                                 /*
351                                  * Succeeded, count did not reach zero so
352                                  * cut out of the loop.
353                                  */
354                                 break;
355                         }
356                         /* retry the same chain */
357                 }
358         }
359 }
360
361 /*
362  * Handle SMP races during the last drop.  We must obtain a lock on
363  * chain->parent to stabilize the last pointer reference to chain
364  * (if applicable).  This reference does not have a parallel ref count,
365  * that is idle chains in the topology can have a ref count of 0.
366  *
367  * The 1->0 transition implies a ref on the parent.
368  */
369 static
370 hammer2_chain_t *
371 hammer2_chain_lastdrop(hammer2_mount_t *hmp, hammer2_chain_t *chain)
372 {
373         hammer2_chain_t *parent;
374
375         /*
376          * Stablize chain->parent with the chain cst's spinlock.
377          * (parent can be NULL here).
378          *
379          * cst.spin locks are allowed to be nested bottom-up (the reverse
380          * of the normal top-down for full-blown cst locks), so this also
381          * allows us to attempt to obtain the parent's cst lock non-blocking
382          * (which must acquire the parent's spinlock unconditionally) while
383          * we are still holding the chain's spinlock.
384          */
385         spin_lock(&chain->cst.spin);
386         parent = chain->parent;
387
388         /*
389          * If chain->flushing is non-zero we cannot deallocate the chain
390          * here.  The flushing field will be serialized for the inline
391          * unlock made by the flusher itself and we don't care about races
392          * in any other situation because the thread lock on the parent
393          * will fail in other situations.
394          *
395          * If we have a non-NULL parent but cannot acquire its thread
396          * lock, we also cannot deallocate the chain.
397          */
398         if (chain->flushing ||
399             (parent && ccms_thread_lock_nonblock(&parent->cst,
400                                                  CCMS_STATE_EXCLUSIVE))) {
401                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
402                         spin_unlock(&chain->cst.spin);  /* success */
403                         return(parent);
404                 } else {
405                         spin_unlock(&chain->cst.spin);  /* failure */
406                         return(chain);
407                 }
408         }
409         spin_unlock(&chain->cst.spin);
410
411         /*
412          * With the parent now held we control the last pointer reference
413          * to chain ONLY IF this is the 1->0 drop.  If we fail to transition
414          * from 1->0 we raced a refs change and must retry at chain.
415          */
416         if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
417                 /* failure */
418                 if (parent)
419                         ccms_thread_unlock(&parent->cst);
420                 return(chain);
421         }
422
423         /*
424          * Ok, we succeeded.  We now own the implied ref on the parent
425          * associated with the 1->0 transition of the child.  It should not
426          * be possible for ANYTHING to access the child now, as we own the
427          * lock on the parent, so we should be able to safely lock the
428          * child and destroy it.
429          */
430         ccms_thread_lock(&chain->cst, CCMS_STATE_EXCLUSIVE);
431         hammer2_chain_dealloc(hmp, chain);
432
433         /*
434          * We want to return parent with its implied ref to the caller
435          * to recurse and drop the parent.
436          */
437         if (parent)
438                 ccms_thread_unlock(&parent->cst);
439         return (parent);
440 }
441
442 /*
443  * Ref and lock a chain element, acquiring its data with I/O if necessary,
444  * and specify how you would like the data to be resolved.
445  *
446  * Returns 0 on success or an error code if the data could not be acquired.
447  * The chain element is locked either way.
448  *
449  * The lock is allowed to recurse, multiple locking ops will aggregate
450  * the requested resolve types.  Once data is assigned it will not be
451  * removed until the last unlock.
452  *
453  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
454  *                         (typically used to avoid device/logical buffer
455  *                          aliasing for data)
456  *
457  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
458  *                         the INITIAL-create state (indirect blocks only).
459  *
460  *                         Do not resolve data elements for DATA chains.
461  *                         (typically used to avoid device/logical buffer
462  *                          aliasing for data)
463  *
464  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
465  *
466  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
467  *                         it will be locked exclusive.
468  *
469  * NOTE: Embedded elements (volume header, inodes) are always resolved
470  *       regardless.
471  *
472  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
473  *       element will instantiate and zero its buffer, and flush it on
474  *       release.
475  *
476  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
477  *       so as not to instantiate a device buffer, which could alias against
478  *       a logical file buffer.  However, if ALWAYS is specified the
479  *       device buffer will be instantiated anyway.
480  */
481 int
482 hammer2_chain_lock(hammer2_mount_t *hmp, hammer2_chain_t *chain, int how)
483 {
484         hammer2_blockref_t *bref;
485         hammer2_off_t pbase;
486         hammer2_off_t peof;
487         ccms_state_t ostate;
488         size_t boff;
489         size_t bbytes;
490         int error;
491         char *bdata;
492
493         /*
494          * Ref and lock the element.  Recursive locks are allowed.
495          */
496         hammer2_chain_ref(hmp, chain);
497         if (how & HAMMER2_RESOLVE_SHARED)
498                 ccms_thread_lock(&chain->cst, CCMS_STATE_SHARED);
499         else
500                 ccms_thread_lock(&chain->cst, CCMS_STATE_EXCLUSIVE);
501
502         /*
503          * If we already have a valid data pointer no further action is
504          * necessary.
505          */
506         if (chain->data)
507                 return (0);
508
509         /*
510          * Do we have to resolve the data?
511          */
512         switch(how & HAMMER2_RESOLVE_MASK) {
513         case HAMMER2_RESOLVE_NEVER:
514                 return(0);
515         case HAMMER2_RESOLVE_MAYBE:
516                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
517                         return(0);
518                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
519                         return(0);
520                 /* fall through */
521         case HAMMER2_RESOLVE_ALWAYS:
522                 break;
523         }
524
525         /*
526          * Upgrade to an exclusive lock so we can safely manipulate the
527          * buffer cache.  If another thread got to it before us we
528          * can just return.
529          */
530         ostate = ccms_thread_lock_upgrade(&chain->cst);
531         if (chain->data) {
532                 ccms_thread_lock_restore(&chain->cst, ostate);
533                 return (0);
534         }
535
536         /*
537          * We must resolve to a device buffer, either by issuing I/O or
538          * by creating a zero-fill element.  We do not mark the buffer
539          * dirty when creating a zero-fill element (the hammer2_chain_modify()
540          * API must still be used to do that).
541          *
542          * The device buffer is variable-sized in powers of 2 down
543          * to HAMMER2_MINALLOCSIZE (typically 1K).  A 64K physical storage
544          * chunk always contains buffers of the same size. (XXX)
545          *
546          * The minimum physical IO size may be larger than the variable
547          * block size.
548          */
549         bref = &chain->bref;
550
551         if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
552                 bbytes = HAMMER2_MINIOSIZE;
553         pbase = bref->data_off & ~(hammer2_off_t)(bbytes - 1);
554         peof = (pbase + HAMMER2_PBUFSIZE64) & ~HAMMER2_PBUFMASK64;
555         boff = bref->data_off & HAMMER2_OFF_MASK & (bbytes - 1);
556         KKASSERT(pbase != 0);
557
558         /*
559          * The getblk() optimization can only be used on newly created
560          * elements if the physical block size matches the request.
561          */
562         if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
563             chain->bytes == bbytes) {
564                 chain->bp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
565                 error = 0;
566         } else if (hammer2_cluster_enable) {
567                 error = cluster_read(hmp->devvp, peof, pbase, bbytes,
568                                      HAMMER2_PBUFSIZE, HAMMER2_PBUFSIZE,
569                                      &chain->bp);
570         } else {
571                 error = bread(hmp->devvp, pbase, bbytes, &chain->bp);
572         }
573
574         if (error) {
575                 kprintf("hammer2_chain_get: I/O error %016jx: %d\n",
576                         (intmax_t)pbase, error);
577                 bqrelse(chain->bp);
578                 chain->bp = NULL;
579                 ccms_thread_lock_restore(&chain->cst, ostate);
580                 return (error);
581         }
582
583         /*
584          * Zero the data area if the chain is in the INITIAL-create state.
585          * Mark the buffer for bdwrite().
586          */
587         bdata = (char *)chain->bp->b_data + boff;
588         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
589                 bzero(bdata, chain->bytes);
590                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
591         }
592
593         /*
594          * Setup the data pointer, either pointing it to an embedded data
595          * structure and copying the data from the buffer, or pointing it
596          * into the buffer.
597          *
598          * The buffer is not retained when copying to an embedded data
599          * structure in order to avoid potential deadlocks or recursions
600          * on the same physical buffer.
601          */
602         switch (bref->type) {
603         case HAMMER2_BREF_TYPE_VOLUME:
604                 /*
605                  * Copy data from bp to embedded buffer
606                  */
607                 panic("hammer2_chain_lock: called on unresolved volume header");
608 #if 0
609                 /* NOT YET */
610                 KKASSERT(pbase == 0);
611                 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
612                 bcopy(bdata, &hmp->voldata, chain->bytes);
613                 chain->data = (void *)&hmp->voldata;
614                 bqrelse(chain->bp);
615                 chain->bp = NULL;
616 #endif
617                 break;
618         case HAMMER2_BREF_TYPE_INODE:
619                 /*
620                  * Copy data from bp to embedded buffer, do not retain the
621                  * device buffer.
622                  */
623                 bcopy(bdata, &chain->u.ip->ip_data, chain->bytes);
624                 chain->data = (void *)&chain->u.ip->ip_data;
625                 bqrelse(chain->bp);
626                 chain->bp = NULL;
627                 break;
628         case HAMMER2_BREF_TYPE_INDIRECT:
629         case HAMMER2_BREF_TYPE_DATA:
630         default:
631                 /*
632                  * Point data at the device buffer and leave bp intact.
633                  */
634                 chain->data = (void *)bdata;
635                 break;
636         }
637
638         /*
639          * Make sure the bp is not specifically owned by this thread before
640          * restoring to a possibly shared lock, so another hammer2 thread
641          * can release it.
642          */
643         if (chain->bp)
644                 BUF_KERNPROC(chain->bp);
645         ccms_thread_lock_restore(&chain->cst, ostate);
646         return (0);
647 }
648
649 /*
650  * Unlock and deref a chain element.
651  *
652  * On the last lock release any non-embedded data (chain->bp) will be
653  * retired.
654  */
655 void
656 hammer2_chain_unlock(hammer2_mount_t *hmp, hammer2_chain_t *chain)
657 {
658         long *counterp;
659
660         /*
661          * Release the CST lock but with a special 1->0 transition case.
662          *
663          * Returns non-zero if lock references remain.  When zero is
664          * returned the last lock reference is retained and any shared
665          * lock is upgraded to an exclusive lock for final disposition.
666          */
667         if (ccms_thread_unlock_zero(&chain->cst)) {
668                 KKASSERT(chain->refs > 1);
669                 atomic_add_int(&chain->refs, -1);
670                 return;
671         }
672
673         /*
674          * Shortcut the case if the data is embedded or not resolved.
675          *
676          * Do NOT null-out pointers to embedded data (e.g. inode).
677          *
678          * The DIRTYBP flag is non-applicable in this situation and can
679          * be cleared to keep the flags state clean.
680          */
681         if (chain->bp == NULL) {
682                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
683                 ccms_thread_unlock(&chain->cst);
684                 hammer2_chain_drop(hmp, chain);
685                 return;
686         }
687
688         /*
689          * Statistics
690          */
691         if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
692                 ;
693         } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
694                 switch(chain->bref.type) {
695                 case HAMMER2_BREF_TYPE_DATA:
696                         counterp = &hammer2_ioa_file_write;
697                         break;
698                 case HAMMER2_BREF_TYPE_INODE:
699                         counterp = &hammer2_ioa_meta_write;
700                         break;
701                 case HAMMER2_BREF_TYPE_INDIRECT:
702                         counterp = &hammer2_ioa_indr_write;
703                         break;
704                 default:
705                         counterp = &hammer2_ioa_volu_write;
706                         break;
707                 }
708                 ++*counterp;
709         } else {
710                 switch(chain->bref.type) {
711                 case HAMMER2_BREF_TYPE_DATA:
712                         counterp = &hammer2_iod_file_write;
713                         break;
714                 case HAMMER2_BREF_TYPE_INODE:
715                         counterp = &hammer2_iod_meta_write;
716                         break;
717                 case HAMMER2_BREF_TYPE_INDIRECT:
718                         counterp = &hammer2_iod_indr_write;
719                         break;
720                 default:
721                         counterp = &hammer2_iod_volu_write;
722                         break;
723                 }
724                 ++*counterp;
725         }
726
727         /*
728          * Clean out the bp.
729          *
730          * If a device buffer was used for data be sure to destroy the
731          * buffer when we are done to avoid aliases (XXX what about the
732          * underlying VM pages?).
733          */
734         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
735                 chain->bp->b_flags |= B_RELBUF;
736
737         /*
738          * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
739          * or not.  The flag will get re-set when chain_modify() is called,
740          * even if MODIFIED is already set, allowing the OS to retire the
741          * buffer independent of a hammer2 flus.
742          */
743         chain->data = NULL;
744         if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
745                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
746                 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
747                         atomic_clear_int(&chain->flags,
748                                          HAMMER2_CHAIN_IOFLUSH);
749                         chain->bp->b_flags |= B_RELBUF;
750                         cluster_awrite(chain->bp);
751                 } else {
752                         chain->bp->b_flags |= B_CLUSTEROK;
753                         bdwrite(chain->bp);
754                 }
755         } else {
756                 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
757                         atomic_clear_int(&chain->flags,
758                                          HAMMER2_CHAIN_IOFLUSH);
759                         chain->bp->b_flags |= B_RELBUF;
760                         brelse(chain->bp);
761                 } else {
762                         /* bp might still be dirty */
763                         bqrelse(chain->bp);
764                 }
765         }
766         chain->bp = NULL;
767         ccms_thread_unlock(&chain->cst);
768         hammer2_chain_drop(hmp, chain);
769 }
770
771 /*
772  * Resize the chain's physical storage allocation.  Chains can be resized
773  * smaller without reallocating the storage.  Resizing larger will reallocate
774  * the storage.
775  *
776  * Must be passed a locked chain.
777  *
778  * If you want the resize code to copy the data to the new block then the
779  * caller should lock the chain RESOLVE_MAYBE or RESOLVE_ALWAYS.
780  *
781  * If the caller already holds a logical buffer containing the data and
782  * intends to bdwrite() that buffer resolve with RESOLVE_NEVER.  The resize
783  * operation will then not copy the data.
784  *
785  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
786  * to avoid instantiating a device buffer that conflicts with the vnode
787  * data buffer.
788  *
789  * XXX flags currently ignored, uses chain->bp to detect data/no-data.
790  */
791 void
792 hammer2_chain_resize(hammer2_inode_t *ip, hammer2_chain_t *chain,
793                      int nradix, int flags)
794 {
795         hammer2_mount_t *hmp = ip->hmp;
796         struct buf *nbp;
797         hammer2_off_t pbase;
798         size_t obytes;
799         size_t nbytes;
800         size_t bbytes;
801         int boff;
802         char *bdata;
803         int error;
804
805         /*
806          * Only data and indirect blocks can be resized for now
807          */
808         KKASSERT(chain != &hmp->vchain);
809         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
810                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
811
812         /*
813          * Nothing to do if the element is already the proper size
814          */
815         obytes = chain->bytes;
816         nbytes = 1U << nradix;
817         if (obytes == nbytes)
818                 return;
819
820         /*
821          * Set MODIFIED and add a chain ref to prevent destruction.  Both
822          * modified flags share the same ref.
823          *
824          * If the chain is already marked MODIFIED then we can safely
825          * return the previous allocation to the pool without having to
826          * worry about snapshots.
827          */
828         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
829                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED |
830                                               HAMMER2_CHAIN_MODIFY_TID);
831                 hammer2_chain_ref(hmp, chain);
832         } else {
833                 hammer2_freemap_free(hmp, chain->bref.data_off,
834                                      chain->bref.type);
835         }
836
837         /*
838          * Relocate the block, even if making it smaller (because different
839          * block sizes may be in different regions).
840          */
841         chain->bref.data_off = hammer2_freemap_alloc(hmp, chain->bref.type,
842                                                      nbytes);
843         chain->bytes = nbytes;
844         ip->delta_dcount += (ssize_t)(nbytes - obytes); /* XXX atomic */
845
846         /*
847          * The device buffer may be larger than the allocation size.
848          */
849         if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
850                 bbytes = HAMMER2_MINIOSIZE;
851         pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
852         boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
853
854         /*
855          * Only copy the data if resolved, otherwise the caller is
856          * responsible.
857          */
858         if (chain->bp) {
859                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
860                          chain->bref.type == HAMMER2_BREF_TYPE_DATA);
861                 KKASSERT(chain != &hmp->vchain);        /* safety */
862
863                 /*
864                  * The getblk() optimization can only be used if the
865                  * physical block size matches the request.
866                  */
867                 if (nbytes == bbytes) {
868                         nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
869                         error = 0;
870                 } else {
871                         error = bread(hmp->devvp, pbase, bbytes, &nbp);
872                         KKASSERT(error == 0);
873                 }
874                 bdata = (char *)nbp->b_data + boff;
875
876                 if (nbytes < obytes) {
877                         bcopy(chain->data, bdata, nbytes);
878                 } else {
879                         bcopy(chain->data, bdata, obytes);
880                         bzero(bdata + obytes, nbytes - obytes);
881                 }
882
883                 /*
884                  * NOTE: The INITIAL state of the chain is left intact.
885                  *       We depend on hammer2_chain_modify() to do the
886                  *       right thing.
887                  *
888                  * NOTE: We set B_NOCACHE to throw away the previous bp and
889                  *       any VM backing store, even if it was dirty.
890                  *       Otherwise we run the risk of a logical/device
891                  *       conflict on reallocation.
892                  */
893                 chain->bp->b_flags |= B_RELBUF | B_NOCACHE;
894                 brelse(chain->bp);
895                 chain->bp = nbp;
896                 chain->data = (void *)bdata;
897                 hammer2_chain_modify(hmp, chain, 0);
898         }
899
900         /*
901          * Make sure the chain is marked MOVED and SUBMOD is set in the
902          * parent(s) so the adjustments are picked up by flush.
903          */
904         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
905                 hammer2_chain_ref(hmp, chain);
906                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
907         }
908         hammer2_chain_parent_setsubmod(hmp, chain);
909 }
910
911 /*
912  * Convert a locked chain that was retrieved read-only to read-write.
913  *
914  * If not already marked modified a new physical block will be allocated
915  * and assigned to the bref.
916  *
917  * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
918  *                   level or the COW operation will not work.
919  *
920  * Data blocks     - The chain is usually locked RESOLVE_NEVER so as not to
921  *                   run the data through the device buffers.
922  */
923 void
924 hammer2_chain_modify(hammer2_mount_t *hmp, hammer2_chain_t *chain, int flags)
925 {
926         struct buf *nbp;
927         int error;
928         hammer2_off_t pbase;
929         size_t bbytes;
930         size_t boff;
931         void *bdata;
932
933         /*
934          * Tells flush that modify_tid must be updated, otherwise only
935          * mirror_tid is updated.  This is the default.
936          */
937         if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
938                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFY_TID);
939
940         /*
941          * If the chain is already marked MODIFIED we can just return.
942          *
943          * However, it is possible that a prior lock/modify sequence
944          * retired the buffer.  During this lock/modify sequence MODIFIED
945          * may still be set but the buffer could wind up clean.  Since
946          * the caller is going to modify the buffer further we have to
947          * be sure that DIRTYBP is set again.
948          */
949         if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
950                 if ((flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
951                     chain->bp == NULL) {
952                         goto skip1;
953                 }
954                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
955                 return;
956         }
957
958         /*
959          * Set MODIFIED and add a chain ref to prevent destruction.  Both
960          * modified flags share the same ref.
961          */
962         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
963         hammer2_chain_ref(hmp, chain);
964
965         /*
966          * We must allocate the copy-on-write block.
967          *
968          * If the data is embedded no other action is required.
969          *
970          * If the data is not embedded we acquire and clear the
971          * new block.  If chain->data is not NULL we then do the
972          * copy-on-write.  chain->data will then be repointed to the new
973          * buffer and the old buffer will be released.
974          *
975          * For newly created elements with no prior allocation we go
976          * through the copy-on-write steps except without the copying part.
977          */
978         if (chain != &hmp->vchain) {
979                 if ((hammer2_debug & 0x0001) &&
980                     (chain->bref.data_off & HAMMER2_OFF_MASK)) {
981                         kprintf("Replace %d\n", chain->bytes);
982                 }
983                 chain->bref.data_off =
984                         hammer2_freemap_alloc(hmp, chain->bref.type,
985                                               chain->bytes);
986                 /* XXX failed allocation */
987         }
988
989         /*
990          * If data instantiation is optional and the chain has no current
991          * data association (typical for DATA and newly-created INDIRECT
992          * elements), don't instantiate the buffer now.
993          */
994         if ((flags & HAMMER2_MODIFY_OPTDATA) && chain->bp == NULL)
995                 goto skip2;
996
997 skip1:
998         /*
999          * Setting the DIRTYBP flag will cause the buffer to be dirtied or
1000          * written-out on unlock.  This bit is independent of the MODIFIED
1001          * bit because the chain may still need meta-data adjustments done
1002          * by virtue of MODIFIED for its parent, and the buffer can be
1003          * flushed out (possibly multiple times) by the OS before that.
1004          *
1005          * Clearing the INITIAL flag (for indirect blocks) indicates that
1006          * a zero-fill buffer has been instantiated.
1007          */
1008         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1009         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1010
1011         /*
1012          * We currently should never instantiate a device buffer for a
1013          * data chain.
1014          */
1015         KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_DATA);
1016
1017         /*
1018          * Execute COW operation
1019          */
1020         switch(chain->bref.type) {
1021         case HAMMER2_BREF_TYPE_VOLUME:
1022         case HAMMER2_BREF_TYPE_INODE:
1023                 /*
1024                  * The data is embedded, no copy-on-write operation is
1025                  * needed.
1026                  */
1027                 KKASSERT(chain->bp == NULL);
1028                 break;
1029         case HAMMER2_BREF_TYPE_DATA:
1030         case HAMMER2_BREF_TYPE_INDIRECT:
1031                 /*
1032                  * Perform the copy-on-write operation
1033                  */
1034                 KKASSERT(chain != &hmp->vchain);        /* safety */
1035                 /*
1036                  * The device buffer may be larger than the allocation size.
1037                  */
1038                 if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
1039                         bbytes = HAMMER2_MINIOSIZE;
1040                 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1041                 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1042
1043                 /*
1044                  * The getblk() optimization can only be used if the
1045                  * physical block size matches the request.
1046                  */
1047                 if (chain->bytes == bbytes) {
1048                         nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
1049                         error = 0;
1050                 } else {
1051                         error = bread(hmp->devvp, pbase, bbytes, &nbp);
1052                         KKASSERT(error == 0);
1053                 }
1054                 bdata = (char *)nbp->b_data + boff;
1055
1056                 /*
1057                  * Copy or zero-fill on write depending on whether
1058                  * chain->data exists or not.
1059                  */
1060                 if (chain->data) {
1061                         bcopy(chain->data, bdata, chain->bytes);
1062                         KKASSERT(chain->bp != NULL);
1063                 } else {
1064                         bzero(bdata, chain->bytes);
1065                 }
1066                 if (chain->bp) {
1067                         chain->bp->b_flags |= B_RELBUF;
1068                         brelse(chain->bp);
1069                 }
1070                 chain->bp = nbp;
1071                 chain->data = bdata;
1072                 break;
1073         default:
1074                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1075                       chain->bref.type);
1076                 break;
1077
1078         }
1079 skip2:
1080         if ((flags & HAMMER2_MODIFY_NOSUB) == 0)
1081                 hammer2_chain_parent_setsubmod(hmp, chain);
1082 }
1083
1084 /*
1085  * Mark the volume as having been modified.  This short-cut version
1086  * does not have to lock the volume's chain, which allows the ioctl
1087  * code to make adjustments to connections without deadlocking.
1088  */
1089 void
1090 hammer2_modify_volume(hammer2_mount_t *hmp)
1091 {
1092         hammer2_voldata_lock(hmp);
1093         atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED_AUX);
1094         hammer2_voldata_unlock(hmp);
1095 }
1096
1097 /*
1098  * Locate an in-memory chain.  The parent must be locked.  The in-memory
1099  * chain is returned or NULL if no in-memory chain is present.
1100  *
1101  * NOTE: A chain on-media might exist for this index when NULL is returned.
1102  */
1103 hammer2_chain_t *
1104 hammer2_chain_find(hammer2_mount_t *hmp, hammer2_chain_t *parent, int index)
1105 {
1106         hammer2_chain_t dummy;
1107         hammer2_chain_t *chain;
1108
1109         dummy.index = index;
1110         chain = RB_FIND(hammer2_chain_tree, &parent->rbhead, &dummy);
1111         return (chain);
1112 }
1113
1114 /*
1115  * Return a locked chain structure with all associated data acquired.
1116  *
1117  * Caller must lock the parent on call, the returned child will be locked.
1118  */
1119 hammer2_chain_t *
1120 hammer2_chain_get(hammer2_mount_t *hmp, hammer2_chain_t *parent,
1121                   int index, int flags)
1122 {
1123         hammer2_blockref_t *bref;
1124         hammer2_inode_t *ip;
1125         hammer2_chain_t *chain;
1126         hammer2_chain_t dummy;
1127         int how;
1128         ccms_state_t ostate;
1129
1130         /*
1131          * Figure out how to lock.  MAYBE can be used to optimized
1132          * the initial-create state for indirect blocks.
1133          */
1134         if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK))
1135                 how = HAMMER2_RESOLVE_NEVER;
1136         else
1137                 how = HAMMER2_RESOLVE_MAYBE;
1138         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1139                 how |= HAMMER2_RESOLVE_SHARED;
1140
1141         /*
1142          * First see if we have a (possibly modified) chain element cached
1143          * for this (parent, index).  Acquire the data if necessary.
1144          *
1145          * If chain->data is non-NULL the chain should already be marked
1146          * modified.
1147          */
1148         dummy.index = index;
1149         chain = RB_FIND(hammer2_chain_tree, &parent->rbhead, &dummy);
1150         if (chain) {
1151                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1152                         hammer2_chain_ref(hmp, chain);
1153                 else
1154                         hammer2_chain_lock(hmp, chain, how);
1155                 return(chain);
1156         }
1157
1158         /*
1159          * Upgrade our thread lock and handle any race that may have
1160          * occurred.  Leave the lock upgraded for the rest of the get.
1161          * We have to do this because we will be modifying the chain
1162          * structure.
1163          */
1164         ostate = ccms_thread_lock_upgrade(&parent->cst);
1165         chain = RB_FIND(hammer2_chain_tree, &parent->rbhead, &dummy);
1166         if (chain) {
1167                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1168                         hammer2_chain_ref(hmp, chain);
1169                 else
1170                         hammer2_chain_lock(hmp, chain, how);
1171                 ccms_thread_lock_restore(&parent->cst, ostate);
1172                 return(chain);
1173         }
1174
1175         /*
1176          * The get function must always succeed, panic if there's no
1177          * data to index.
1178          */
1179         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1180                 ccms_thread_lock_restore(&parent->cst, ostate);
1181                 panic("hammer2_chain_get: Missing bref(1)");
1182                 /* NOT REACHED */
1183         }
1184
1185         /*
1186          * Otherwise lookup the bref and issue I/O (switch on the parent)
1187          */
1188         switch(parent->bref.type) {
1189         case HAMMER2_BREF_TYPE_INODE:
1190                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1191                 bref = &parent->data->ipdata.u.blockset.blockref[index];
1192                 break;
1193         case HAMMER2_BREF_TYPE_INDIRECT:
1194                 KKASSERT(parent->data != NULL);
1195                 KKASSERT(index >= 0 &&
1196                          index < parent->bytes / sizeof(hammer2_blockref_t));
1197                 bref = &parent->data->npdata.blockref[index];
1198                 break;
1199         case HAMMER2_BREF_TYPE_VOLUME:
1200                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1201                 bref = &hmp->voldata.sroot_blockset.blockref[index];
1202                 break;
1203         default:
1204                 bref = NULL;
1205                 panic("hammer2_chain_get: unrecognized blockref type: %d",
1206                       parent->bref.type);
1207         }
1208         if (bref->type == 0) {
1209                 panic("hammer2_chain_get: Missing bref(2)");
1210                 /* NOT REACHED */
1211         }
1212
1213         /*
1214          * Allocate a chain structure representing the existing media
1215          * entry.
1216          *
1217          * The locking operation we do later will issue I/O to read it.
1218          */
1219         chain = hammer2_chain_alloc(hmp, bref);
1220
1221         /*
1222          * Link the chain into its parent.  Caller is expected to hold an
1223          * exclusive lock on the parent.
1224          */
1225         chain->parent = parent;
1226         chain->index = index;
1227         if (RB_INSERT(hammer2_chain_tree, &parent->rbhead, chain))
1228                 panic("hammer2_chain_link: collision");
1229         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
1230         KKASSERT(parent->refs > 0);
1231         atomic_add_int(&parent->refs, 1);       /* for red-black entry */
1232         ccms_thread_lock_restore(&parent->cst, ostate);
1233
1234         /*
1235          * Additional linkage for inodes.  Reuse the parent pointer to
1236          * find the parent directory.
1237          *
1238          * The ccms_inode is initialized from its parent directory.  The
1239          * chain of ccms_inode's is seeded by the mount code.
1240          */
1241         if (bref->type == HAMMER2_BREF_TYPE_INODE) {
1242                 ip = chain->u.ip;
1243                 while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT)
1244                         parent = parent->parent;
1245                 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
1246                         ip->pip = parent->u.ip;
1247                         ip->pmp = parent->u.ip->pmp;
1248                         ccms_cst_init(&ip->topo_cst, &ip->chain);
1249                 }
1250         }
1251
1252         /*
1253          * Our new chain structure has already been referenced and locked
1254          * but the lock code handles the I/O so call it to resolve the data.
1255          * Then release one of our two exclusive locks.
1256          *
1257          * If NOLOCK is set the release will release the one-and-only lock.
1258          */
1259         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0) {
1260                 hammer2_chain_lock(hmp, chain, how);    /* recusive lock */
1261                 hammer2_chain_drop(hmp, chain);         /* excess ref */
1262         }
1263         ccms_thread_unlock(&chain->cst);                        /* from alloc */
1264
1265         return (chain);
1266 }
1267
1268 /*
1269  * Locate any key between key_beg and key_end inclusive.  (*parentp)
1270  * typically points to an inode but can also point to a related indirect
1271  * block and this function will recurse upwards and find the inode again.
1272  *
1273  * WARNING!  THIS DOES NOT RETURN KEYS IN LOGICAL KEY ORDER!  ANY KEY
1274  *           WITHIN THE RANGE CAN BE RETURNED.  HOWEVER, AN ITERATION
1275  *           WHICH PICKS UP WHERE WE LEFT OFF WILL CONTINUE THE SCAN.
1276  *
1277  * (*parentp) must be exclusively locked and referenced and can be an inode
1278  * or an existing indirect block within the inode.
1279  *
1280  * On return (*parentp) will be modified to point at the deepest parent chain
1281  * element encountered during the search, as a helper for an insertion or
1282  * deletion.   The new (*parentp) will be locked and referenced and the old
1283  * will be unlocked and dereferenced (no change if they are both the same).
1284  *
1285  * The matching chain will be returned exclusively locked and referenced.
1286  *
1287  * NULL is returned if no match was found, but (*parentp) will still
1288  * potentially be adjusted.
1289  *
1290  * This function will also recurse up the chain if the key is not within the
1291  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1292  * can simply allow (*parentp) to float inside the loop.
1293  */
1294 hammer2_chain_t *
1295 hammer2_chain_lookup(hammer2_mount_t *hmp, hammer2_chain_t **parentp,
1296                      hammer2_key_t key_beg, hammer2_key_t key_end,
1297                      int flags)
1298 {
1299         hammer2_chain_t *parent;
1300         hammer2_chain_t *chain;
1301         hammer2_chain_t *tmp;
1302         hammer2_blockref_t *base;
1303         hammer2_blockref_t *bref;
1304         hammer2_key_t scan_beg;
1305         hammer2_key_t scan_end;
1306         int count = 0;
1307         int i;
1308         int how_always = HAMMER2_RESOLVE_ALWAYS;
1309         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1310
1311         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1312                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1313                 how_always |= HAMMER2_RESOLVE_SHARED;
1314         }
1315
1316         /*
1317          * Recurse (*parentp) upward if necessary until the parent completely
1318          * encloses the key range or we hit the inode.
1319          */
1320         parent = *parentp;
1321         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT) {
1322                 scan_beg = parent->bref.key;
1323                 scan_end = scan_beg +
1324                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1325                 if (key_beg >= scan_beg && key_end <= scan_end)
1326                         break;
1327                 hammer2_chain_ref(hmp, parent);         /* ref old parent */
1328                 hammer2_chain_unlock(hmp, parent);      /* unlock old parent */
1329                 parent = parent->parent;
1330                                                         /* lock new parent */
1331                 hammer2_chain_lock(hmp, parent, how_maybe);
1332                 hammer2_chain_drop(hmp, *parentp);      /* drop old parent */
1333                 *parentp = parent;                      /* new parent */
1334         }
1335
1336 again:
1337         /*
1338          * Locate the blockref array.  Currently we do a fully associative
1339          * search through the array.
1340          */
1341         switch(parent->bref.type) {
1342         case HAMMER2_BREF_TYPE_INODE:
1343                 /*
1344                  * Special shortcut for embedded data returns the inode
1345                  * itself.  Callers must detect this condition and access
1346                  * the embedded data (the strategy code does this for us).
1347                  *
1348                  * This is only applicable to regular files and softlinks.
1349                  */
1350                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1351                         if (flags & HAMMER2_LOOKUP_NOLOCK)
1352                                 hammer2_chain_ref(hmp, parent);
1353                         else
1354                                 hammer2_chain_lock(hmp, parent, how_always);
1355                         return (parent);
1356                 }
1357                 base = &parent->data->ipdata.u.blockset.blockref[0];
1358                 count = HAMMER2_SET_COUNT;
1359                 break;
1360         case HAMMER2_BREF_TYPE_INDIRECT:
1361                 /*
1362                  * Optimize indirect blocks in the INITIAL state to avoid
1363                  * I/O.
1364                  */
1365                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1366                         base = NULL;
1367                 } else {
1368                         if (parent->data == NULL)
1369                                 panic("parent->data is NULL");
1370                         base = &parent->data->npdata.blockref[0];
1371                 }
1372                 count = parent->bytes / sizeof(hammer2_blockref_t);
1373                 break;
1374         case HAMMER2_BREF_TYPE_VOLUME:
1375                 base = &hmp->voldata.sroot_blockset.blockref[0];
1376                 count = HAMMER2_SET_COUNT;
1377                 break;
1378         default:
1379                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1380                       parent->bref.type);
1381                 base = NULL;    /* safety */
1382                 count = 0;      /* safety */
1383         }
1384
1385         /*
1386          * If the element and key overlap we use the element.
1387          *
1388          * NOTE!  Deleted elements are effectively invisible.  A Deleted
1389          *        elements covers (makes invisible) any original media
1390          *        data.
1391          */
1392         bref = NULL;
1393         for (i = 0; i < count; ++i) {
1394                 tmp = hammer2_chain_find(hmp, parent, i);
1395                 if (tmp) {
1396                         if (tmp->flags & HAMMER2_CHAIN_DELETED)
1397                                 continue;
1398                         bref = &tmp->bref;
1399                         KKASSERT(bref->type != 0);
1400                 } else if (base == NULL || base[i].type == 0) {
1401                         continue;
1402                 } else {
1403                         bref = &base[i];
1404                 }
1405                 scan_beg = bref->key;
1406                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1407                 if (key_beg <= scan_end && key_end >= scan_beg)
1408                         break;
1409         }
1410         if (i == count) {
1411                 if (key_beg == key_end)
1412                         return (NULL);
1413                 return (hammer2_chain_next(hmp, parentp, NULL,
1414                                            key_beg, key_end, flags));
1415         }
1416
1417         /*
1418          * Acquire the new chain element.  If the chain element is an
1419          * indirect block we must search recursively.
1420          */
1421         chain = hammer2_chain_get(hmp, parent, i, flags);
1422         if (chain == NULL)
1423                 return (NULL);
1424
1425         /*
1426          * If the chain element is an indirect block it becomes the new
1427          * parent and we loop on it.
1428          *
1429          * The parent always has to be locked with at least RESOLVE_MAYBE,
1430          * so it might need a fixup if the caller passed incompatible flags.
1431          */
1432         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT) {
1433                 hammer2_chain_unlock(hmp, parent);
1434                 *parentp = parent = chain;
1435                 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1436                         hammer2_chain_lock(hmp, chain, how_maybe);
1437                         hammer2_chain_drop(hmp, chain); /* excess ref */
1438                 } else if (flags & HAMMER2_LOOKUP_NODATA) {
1439                         hammer2_chain_lock(hmp, chain, how_maybe);
1440                         hammer2_chain_unlock(hmp, chain);
1441                 }
1442                 goto again;
1443         }
1444
1445         /*
1446          * All done, return chain
1447          */
1448         return (chain);
1449 }
1450
1451 /*
1452  * After having issued a lookup we can iterate all matching keys.
1453  *
1454  * If chain is non-NULL we continue the iteration from just after it's index.
1455  *
1456  * If chain is NULL we assume the parent was exhausted and continue the
1457  * iteration at the next parent.
1458  *
1459  * parent must be locked on entry and remains locked throughout.  chain's
1460  * lock status must match flags.
1461  */
1462 hammer2_chain_t *
1463 hammer2_chain_next(hammer2_mount_t *hmp, hammer2_chain_t **parentp,
1464                    hammer2_chain_t *chain,
1465                    hammer2_key_t key_beg, hammer2_key_t key_end,
1466                    int flags)
1467 {
1468         hammer2_chain_t *parent;
1469         hammer2_chain_t *tmp;
1470         hammer2_blockref_t *base;
1471         hammer2_blockref_t *bref;
1472         hammer2_key_t scan_beg;
1473         hammer2_key_t scan_end;
1474         int i;
1475         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1476         int count;
1477
1478         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1479                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1480
1481         parent = *parentp;
1482
1483 again:
1484         /*
1485          * Calculate the next index and recalculate the parent if necessary.
1486          */
1487         if (chain) {
1488                 /*
1489                  * Continue iteration within current parent.  If not NULL
1490                  * the passed-in chain may or may not be locked, based on
1491                  * the LOOKUP_NOLOCK flag (passed in as returned from lookup
1492                  * or a prior next).
1493                  */
1494                 i = chain->index + 1;
1495                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1496                         hammer2_chain_drop(hmp, chain);
1497                 else
1498                         hammer2_chain_unlock(hmp, chain);
1499
1500                 /*
1501                  * Any scan where the lookup returned degenerate data embedded
1502                  * in the inode has an invalid index and must terminate.
1503                  */
1504                 if (chain == parent)
1505                         return(NULL);
1506                 chain = NULL;
1507         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT) {
1508                 /*
1509                  * We reached the end of the iteration.
1510                  */
1511                 return (NULL);
1512         } else {
1513                 /*
1514                  * Continue iteration with next parent unless the current
1515                  * parent covers the range.
1516                  */
1517                 hammer2_chain_t *nparent;
1518
1519                 scan_beg = parent->bref.key;
1520                 scan_end = scan_beg +
1521                             ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1522                 if (key_beg >= scan_beg && key_end <= scan_end)
1523                         return (NULL);
1524
1525                 i = parent->index + 1;
1526                 nparent = parent->parent;
1527                 hammer2_chain_ref(hmp, nparent);        /* ref new parent */
1528                 hammer2_chain_unlock(hmp, parent);      /* unlock old parent */
1529                                                         /* lock new parent */
1530                 hammer2_chain_lock(hmp, nparent, how_maybe);
1531                 hammer2_chain_drop(hmp, nparent);       /* drop excess ref */
1532                 *parentp = parent = nparent;
1533         }
1534
1535 again2:
1536         /*
1537          * Locate the blockref array.  Currently we do a fully associative
1538          * search through the array.
1539          */
1540         switch(parent->bref.type) {
1541         case HAMMER2_BREF_TYPE_INODE:
1542                 base = &parent->data->ipdata.u.blockset.blockref[0];
1543                 count = HAMMER2_SET_COUNT;
1544                 break;
1545         case HAMMER2_BREF_TYPE_INDIRECT:
1546                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1547                         base = NULL;
1548                 } else {
1549                         KKASSERT(parent->data != NULL);
1550                         base = &parent->data->npdata.blockref[0];
1551                 }
1552                 count = parent->bytes / sizeof(hammer2_blockref_t);
1553                 break;
1554         case HAMMER2_BREF_TYPE_VOLUME:
1555                 base = &hmp->voldata.sroot_blockset.blockref[0];
1556                 count = HAMMER2_SET_COUNT;
1557                 break;
1558         default:
1559                 panic("hammer2_chain_next: unrecognized blockref type: %d",
1560                       parent->bref.type);
1561                 base = NULL;    /* safety */
1562                 count = 0;      /* safety */
1563                 break;
1564         }
1565         KKASSERT(i <= count);
1566
1567         /*
1568          * Look for the key.  If we are unable to find a match and an exact
1569          * match was requested we return NULL.  If a range was requested we
1570          * run hammer2_chain_next() to iterate.
1571          *
1572          * NOTE!  Deleted elements are effectively invisible.  A Deleted
1573          *        elements covers (makes invisible) any original media
1574          *        data.
1575          */
1576         bref = NULL;
1577         while (i < count) {
1578                 tmp = hammer2_chain_find(hmp, parent, i);
1579                 if (tmp) {
1580                         if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1581                                 ++i;
1582                                 continue;
1583                         }
1584                         bref = &tmp->bref;
1585                 } else if (base == NULL || base[i].type == 0) {
1586                         ++i;
1587                         continue;
1588                 } else {
1589                         bref = &base[i];
1590                 }
1591                 scan_beg = bref->key;
1592                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1593                 if (key_beg <= scan_end && key_end >= scan_beg)
1594                         break;
1595                 ++i;
1596         }
1597
1598         /*
1599          * If we couldn't find a match recurse up a parent to continue the
1600          * search.
1601          */
1602         if (i == count)
1603                 goto again;
1604
1605         /*
1606          * Acquire the new chain element.  If the chain element is an
1607          * indirect block we must search recursively.
1608          */
1609         chain = hammer2_chain_get(hmp, parent, i, flags);
1610         if (chain == NULL)
1611                 return (NULL);
1612
1613         /*
1614          * If the chain element is an indirect block it becomes the new
1615          * parent and we loop on it.
1616          *
1617          * The parent always has to be locked with at least RESOLVE_MAYBE,
1618          * so it might need a fixup if the caller passed incompatible flags.
1619          */
1620         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT) {
1621                 hammer2_chain_unlock(hmp, parent);
1622                 *parentp = parent = chain;
1623                 chain = NULL;
1624                 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1625                         hammer2_chain_lock(hmp, parent, how_maybe);
1626                         hammer2_chain_drop(hmp, parent);        /* excess ref */
1627                 } else if (flags & HAMMER2_LOOKUP_NODATA) {
1628                         hammer2_chain_lock(hmp, parent, how_maybe);
1629                         hammer2_chain_unlock(hmp, parent);
1630                 }
1631                 i = 0;
1632                 goto again2;
1633         }
1634
1635         /*
1636          * All done, return chain
1637          */
1638         return (chain);
1639 }
1640
1641 /*
1642  * Create and return a new hammer2 system memory structure of the specified
1643  * key, type and size and insert it RELATIVE TO (PARENT).
1644  *
1645  * (parent) is typically either an inode or an indirect block, acquired
1646  * acquired as a side effect of issuing a prior failed lookup.  parent
1647  * must be locked and held.  Do not pass the inode chain to this function
1648  * unless that is the chain returned by the failed lookup.
1649  *
1650  * Non-indirect types will automatically allocate indirect blocks as required
1651  * if the new item does not fit in the current (parent).
1652  *
1653  * Indirect types will move a portion of the existing blockref array in
1654  * (parent) into the new indirect type and then use one of the free slots
1655  * to emplace the new indirect type.
1656  *
1657  * A new locked, referenced chain element is returned of the specified type.
1658  * The element may or may not have a data area associated with it:
1659  *
1660  *      VOLUME          not allowed here
1661  *      INODE           embedded data are will be set-up
1662  *      INDIRECT        not allowed here
1663  *      DATA            no data area will be set-up (caller is expected
1664  *                      to have logical buffers, we don't want to alias
1665  *                      the data onto device buffers!).
1666  *
1667  * Requires an exclusively locked parent.
1668  */
1669 hammer2_chain_t *
1670 hammer2_chain_create(hammer2_mount_t *hmp, hammer2_chain_t *parent,
1671                      hammer2_chain_t *chain,
1672                      hammer2_key_t key, int keybits, int type, size_t bytes,
1673                      int *errorp)
1674 {
1675         hammer2_blockref_t dummy;
1676         hammer2_blockref_t *base;
1677         hammer2_chain_t dummy_chain;
1678         int unlock_parent = 0;
1679         int allocated = 0;
1680         int count;
1681         int i;
1682
1683         KKASSERT(ccms_thread_lock_owned(&parent->cst));
1684         *errorp = 0;
1685
1686         if (chain == NULL) {
1687                 /*
1688                  * First allocate media space and construct the dummy bref,
1689                  * then allocate the in-memory chain structure.
1690                  */
1691                 bzero(&dummy, sizeof(dummy));
1692                 dummy.type = type;
1693                 dummy.key = key;
1694                 dummy.keybits = keybits;
1695                 dummy.data_off = hammer2_bytes_to_radix(bytes);
1696                 chain = hammer2_chain_alloc(hmp, &dummy);
1697                 allocated = 1;
1698
1699                 /*
1700                  * We do NOT set INITIAL here (yet).  INITIAL is only
1701                  * used for indirect blocks.
1702                  *
1703                  * Recalculate bytes to reflect the actual media block
1704                  * allocation.
1705                  */
1706                 bytes = (hammer2_off_t)1 <<
1707                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
1708                 chain->bytes = bytes;
1709
1710                 switch(type) {
1711                 case HAMMER2_BREF_TYPE_VOLUME:
1712                         panic("hammer2_chain_create: called with volume type");
1713                         break;
1714                 case HAMMER2_BREF_TYPE_INODE:
1715                         KKASSERT(bytes == HAMMER2_INODE_BYTES);
1716                         chain->data = (void *)&chain->u.ip->ip_data;
1717                         break;
1718                 case HAMMER2_BREF_TYPE_INDIRECT:
1719                         panic("hammer2_chain_create: cannot be used to"
1720                               "create indirect block");
1721                         break;
1722                 case HAMMER2_BREF_TYPE_DATA:
1723                 default:
1724                         /* leave chain->data NULL */
1725                         KKASSERT(chain->data == NULL);
1726                         break;
1727                 }
1728         } else {
1729                 /*
1730                  * Potentially update the chain's key/keybits.
1731                  */
1732                 chain->bref.key = key;
1733                 chain->bref.keybits = keybits;
1734         }
1735
1736 again:
1737         /*
1738          * Locate a free blockref in the parent's array
1739          */
1740         switch(parent->bref.type) {
1741         case HAMMER2_BREF_TYPE_INODE:
1742                 KKASSERT((parent->u.ip->ip_data.op_flags &
1743                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
1744                 KKASSERT(parent->data != NULL);
1745                 base = &parent->data->ipdata.u.blockset.blockref[0];
1746                 count = HAMMER2_SET_COUNT;
1747                 break;
1748         case HAMMER2_BREF_TYPE_INDIRECT:
1749                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1750                         base = NULL;
1751                 } else {
1752                         KKASSERT(parent->data != NULL);
1753                         base = &parent->data->npdata.blockref[0];
1754                 }
1755                 count = parent->bytes / sizeof(hammer2_blockref_t);
1756                 break;
1757         case HAMMER2_BREF_TYPE_VOLUME:
1758                 KKASSERT(parent->data != NULL);
1759                 base = &hmp->voldata.sroot_blockset.blockref[0];
1760                 count = HAMMER2_SET_COUNT;
1761                 break;
1762         default:
1763                 panic("hammer2_chain_create: unrecognized blockref type: %d",
1764                       parent->bref.type);
1765                 count = 0;
1766                 break;
1767         }
1768
1769         /*
1770          * Scan for an unallocated bref, also skipping any slots occupied
1771          * by in-memory chain elements that may not yet have been updated
1772          * in the parent's bref array.
1773          */
1774         bzero(&dummy_chain, sizeof(dummy_chain));
1775         for (i = 0; i < count; ++i) {
1776                 if (base == NULL) {
1777                         dummy_chain.index = i;
1778                         if (RB_FIND(hammer2_chain_tree,
1779                                     &parent->rbhead, &dummy_chain) == NULL) {
1780                                 break;
1781                         }
1782                 } else if (base[i].type == 0) {
1783                         dummy_chain.index = i;
1784                         if (RB_FIND(hammer2_chain_tree,
1785                                     &parent->rbhead, &dummy_chain) == NULL) {
1786                                 break;
1787                         }
1788                 }
1789         }
1790
1791         /*
1792          * If no free blockref could be found we must create an indirect
1793          * block and move a number of blockrefs into it.  With the parent
1794          * locked we can safely lock each child in order to move it without
1795          * causing a deadlock.
1796          *
1797          * This may return the new indirect block or the old parent depending
1798          * on where the key falls.  NULL is returned on error.  The most
1799          * typical error is EAGAIN (flush conflict during chain move).
1800          */
1801         if (i == count) {
1802                 hammer2_chain_t *nparent;
1803
1804                 nparent = hammer2_chain_create_indirect(hmp, parent,
1805                                                         key, keybits,
1806                                                         errorp);
1807                 if (nparent == NULL) {
1808                         if (allocated)
1809                                 hammer2_chain_free(hmp, chain);
1810                         chain = NULL;
1811                         goto done;
1812                 }
1813                 if (parent != nparent) {
1814                         if (unlock_parent)
1815                                 hammer2_chain_unlock(hmp, parent);
1816                         parent = nparent;
1817                         unlock_parent = 1;
1818                 }
1819                 goto again;
1820         }
1821
1822         /*
1823          * Link the chain into its parent.  Later on we will have to set
1824          * the MOVED bit in situations where we don't mark the new chain
1825          * as being modified.
1826          */
1827         if (chain->parent != NULL)
1828                 panic("hammer2: hammer2_chain_create: chain already connected");
1829         KKASSERT(chain->parent == NULL);
1830         chain->parent = parent;
1831         chain->index = i;
1832         if (RB_INSERT(hammer2_chain_tree, &parent->rbhead, chain))
1833                 panic("hammer2_chain_link: collision");
1834         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
1835         KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
1836         KKASSERT(parent->refs > 0);
1837         atomic_add_int(&parent->refs, 1);
1838
1839         /*
1840          * Additional linkage for inodes.  Reuse the parent pointer to
1841          * find the parent directory.
1842          *
1843          * Cumulative adjustments are inherited on [re]attach and will
1844          * propagate up the tree on the next flush.
1845          *
1846          * The ccms_inode is initialized from its parent directory.  The
1847          * chain of ccms_inode's is seeded by the mount code.
1848          */
1849         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
1850                 hammer2_chain_t *scan = parent;
1851                 hammer2_inode_t *ip = chain->u.ip;
1852
1853                 while (scan->bref.type == HAMMER2_BREF_TYPE_INDIRECT)
1854                         scan = scan->parent;
1855                 if (scan->bref.type == HAMMER2_BREF_TYPE_INODE) {
1856                         ip->pip = scan->u.ip;
1857                         ip->pmp = scan->u.ip->pmp;
1858                         ip->pip->delta_icount += ip->ip_data.inode_count;
1859                         ip->pip->delta_dcount += ip->ip_data.data_count;
1860                         ++ip->pip->delta_icount;
1861                         ccms_cst_init(&ip->topo_cst, &ip->chain);
1862                 }
1863         }
1864
1865         /*
1866          * (allocated) indicates that this is a newly-created chain element
1867          * rather than a renamed chain element.  In this situation we want
1868          * to place the chain element in the MODIFIED state.
1869          *
1870          * The data area will be set up as follows:
1871          *
1872          *      VOLUME          not allowed here.
1873          *
1874          *      INODE           embedded data are will be set-up.
1875          *
1876          *      INDIRECT        not allowed here.
1877          *
1878          *      DATA            no data area will be set-up (caller is expected
1879          *                      to have logical buffers, we don't want to alias
1880          *                      the data onto device buffers!).
1881          */
1882         if (allocated) {
1883                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
1884                         hammer2_chain_modify(hmp, chain,
1885                                              HAMMER2_MODIFY_OPTDATA);
1886                 } else if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT) {
1887                         /* not supported in this function */
1888                         panic("hammer2_chain_create: bad type");
1889                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1890                         hammer2_chain_modify(hmp, chain,
1891                                              HAMMER2_MODIFY_OPTDATA);
1892                 } else {
1893                         hammer2_chain_modify(hmp, chain, 0);
1894                 }
1895         } else {
1896                 /*
1897                  * When reconnecting inodes we have to call setsubmod()
1898                  * to ensure that its state propagates up the newly
1899                  * connected parent.
1900                  *
1901                  * Make sure MOVED is set but do not update bref_flush.  If
1902                  * the chain is undergoing modification bref_flush will be
1903                  * updated when it gets flushed.  If it is not then the
1904                  * bref may not have been flushed yet and we do not want to
1905                  * set MODIFIED here as this could result in unnecessary
1906                  * reallocations.
1907                  */
1908                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1909                         hammer2_chain_ref(hmp, chain);
1910                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1911                 }
1912                 hammer2_chain_parent_setsubmod(hmp, chain);
1913         }
1914
1915 done:
1916         if (unlock_parent)
1917                 hammer2_chain_unlock(hmp, parent);
1918         return (chain);
1919 }
1920
1921 /*
1922  * Create an indirect block that covers one or more of the elements in the
1923  * current parent.  Either returns the existing parent with no locking or
1924  * ref changes or returns the new indirect block locked and referenced
1925  * and leaving the original parent lock/ref intact as well.
1926  *
1927  * If an error occurs, NULL is returned and *errorp is set to the error.
1928  * EAGAIN can be returned to indicate a flush collision which requires the
1929  * caller to retry.
1930  *
1931  * The returned chain depends on where the specified key falls.
1932  *
1933  * The key/keybits for the indirect mode only needs to follow three rules:
1934  *
1935  * (1) That all elements underneath it fit within its key space and
1936  *
1937  * (2) That all elements outside it are outside its key space.
1938  *
1939  * (3) When creating the new indirect block any elements in the current
1940  *     parent that fit within the new indirect block's keyspace must be
1941  *     moved into the new indirect block.
1942  *
1943  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
1944  *     keyspace the the current parent, but lookup/iteration rules will
1945  *     ensure (and must ensure) that rule (2) for all parents leading up
1946  *     to the nearest inode or the root volume header is adhered to.  This
1947  *     is accomplished by always recursing through matching keyspaces in
1948  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
1949  *
1950  * The current implementation calculates the current worst-case keyspace by
1951  * iterating the current parent and then divides it into two halves, choosing
1952  * whichever half has the most elements (not necessarily the half containing
1953  * the requested key).
1954  *
1955  * We can also opt to use the half with the least number of elements.  This
1956  * causes lower-numbered keys (aka logical file offsets) to recurse through
1957  * fewer indirect blocks and higher-numbered keys to recurse through more.
1958  * This also has the risk of not moving enough elements to the new indirect
1959  * block and being forced to create several indirect blocks before the element
1960  * can be inserted.
1961  *
1962  * Must be called with an exclusively locked parent.
1963  */
1964 static
1965 hammer2_chain_t *
1966 hammer2_chain_create_indirect(hammer2_mount_t *hmp, hammer2_chain_t *parent,
1967                               hammer2_key_t create_key, int create_bits,
1968                               int *errorp)
1969 {
1970         hammer2_blockref_t *base;
1971         hammer2_blockref_t *bref;
1972         hammer2_chain_t *chain;
1973         hammer2_chain_t *ichain;
1974         hammer2_chain_t dummy;
1975         hammer2_key_t key = create_key;
1976         int keybits = create_bits;
1977         int locount = 0;
1978         int hicount = 0;
1979         int count;
1980         int nbytes;
1981         int i;
1982
1983         /*
1984          * Calculate the base blockref pointer or NULL if the chain
1985          * is known to be empty.  We need to calculate the array count
1986          * for RB lookups either way.
1987          */
1988         KKASSERT(ccms_thread_lock_owned(&parent->cst));
1989         *errorp = 0;
1990
1991         hammer2_chain_modify(hmp, parent, HAMMER2_MODIFY_OPTDATA);
1992         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1993                 base = NULL;
1994
1995                 switch(parent->bref.type) {
1996                 case HAMMER2_BREF_TYPE_INODE:
1997                         count = HAMMER2_SET_COUNT;
1998                         break;
1999                 case HAMMER2_BREF_TYPE_INDIRECT:
2000                         count = parent->bytes / sizeof(hammer2_blockref_t);
2001                         break;
2002                 case HAMMER2_BREF_TYPE_VOLUME:
2003                         count = HAMMER2_SET_COUNT;
2004                         break;
2005                 default:
2006                         panic("hammer2_chain_create_indirect: "
2007                               "unrecognized blockref type: %d",
2008                               parent->bref.type);
2009                         count = 0;
2010                         break;
2011                 }
2012         } else {
2013                 switch(parent->bref.type) {
2014                 case HAMMER2_BREF_TYPE_INODE:
2015                         base = &parent->data->ipdata.u.blockset.blockref[0];
2016                         count = HAMMER2_SET_COUNT;
2017                         break;
2018                 case HAMMER2_BREF_TYPE_INDIRECT:
2019                         base = &parent->data->npdata.blockref[0];
2020                         count = parent->bytes / sizeof(hammer2_blockref_t);
2021                         break;
2022                 case HAMMER2_BREF_TYPE_VOLUME:
2023                         base = &hmp->voldata.sroot_blockset.blockref[0];
2024                         count = HAMMER2_SET_COUNT;
2025                         break;
2026                 default:
2027                         panic("hammer2_chain_create_indirect: "
2028                               "unrecognized blockref type: %d",
2029                               parent->bref.type);
2030                         count = 0;
2031                         break;
2032                 }
2033         }
2034
2035         /*
2036          * Scan for an unallocated bref, also skipping any slots occupied
2037          * by in-memory chain elements which may not yet have been updated
2038          * in the parent's bref array.
2039          */
2040         bzero(&dummy, sizeof(dummy));
2041         for (i = 0; i < count; ++i) {
2042                 int nkeybits;
2043
2044                 dummy.index = i;
2045                 chain = RB_FIND(hammer2_chain_tree, &parent->rbhead, &dummy);
2046                 if (chain) {
2047                         /*
2048                          * NOTE! CHAIN_DELETED elements have to be adjusted
2049                          *       too, they cannot be ignored.
2050                          */
2051                         bref = &chain->bref;
2052                 } else if (base && base[i].type) {
2053                         bref = &base[i];
2054                 } else {
2055                         continue;
2056                 }
2057
2058                 /*
2059                  * Expand our calculated key range (key, keybits) to fit
2060                  * the scanned key.  nkeybits represents the full range
2061                  * that we will later cut in half (two halves @ nkeybits - 1).
2062                  */
2063                 nkeybits = keybits;
2064                 if (nkeybits < bref->keybits)
2065                         nkeybits = bref->keybits;
2066                 while (nkeybits < 64 &&
2067                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
2068                         (key ^ bref->key)) != 0) {
2069                         ++nkeybits;
2070                 }
2071
2072                 /*
2073                  * If the new key range is larger we have to determine
2074                  * which side of the new key range the existing keys fall
2075                  * under by checking the high bit, then collapsing the
2076                  * locount into the hicount or vise-versa.
2077                  */
2078                 if (keybits != nkeybits) {
2079                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
2080                                 hicount += locount;
2081                                 locount = 0;
2082                         } else {
2083                                 locount += hicount;
2084                                 hicount = 0;
2085                         }
2086                         keybits = nkeybits;
2087                 }
2088
2089                 /*
2090                  * The newly scanned key will be in the lower half or the
2091                  * higher half of the (new) key range.
2092                  */
2093                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
2094                         ++hicount;
2095                 else
2096                         ++locount;
2097         }
2098
2099         /*
2100          * Adjust keybits to represent half of the full range calculated
2101          * above (radix 63 max)
2102          */
2103         --keybits;
2104
2105         /*
2106          * Select whichever half contains the most elements.  Theoretically
2107          * we can select either side as long as it contains at least one
2108          * element (in order to ensure that a free slot is present to hold
2109          * the indirect block).
2110          */
2111         key &= ~(((hammer2_key_t)1 << keybits) - 1);
2112         if (hammer2_indirect_optimize) {
2113                 /*
2114                  * Insert node for least number of keys, this will arrange
2115                  * the first few blocks of a large file or the first few
2116                  * inodes in a directory with fewer indirect blocks when
2117                  * created linearly.
2118                  */
2119                 if (hicount < locount && hicount != 0)
2120                         key |= (hammer2_key_t)1 << keybits;
2121                 else
2122                         key &= ~(hammer2_key_t)1 << keybits;
2123         } else {
2124                 /*
2125                  * Insert node for most number of keys, best for heavily
2126                  * fragmented files.
2127                  */
2128                 if (hicount > locount)
2129                         key |= (hammer2_key_t)1 << keybits;
2130                 else
2131                         key &= ~(hammer2_key_t)1 << keybits;
2132         }
2133
2134         /*
2135          * How big should our new indirect block be?  It has to be at least
2136          * as large as its parent.
2137          */
2138         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2139                 nbytes = HAMMER2_IND_BYTES_MIN;
2140         else
2141                 nbytes = HAMMER2_IND_BYTES_MAX;
2142         if (nbytes < count * sizeof(hammer2_blockref_t))
2143                 nbytes = count * sizeof(hammer2_blockref_t);
2144
2145         /*
2146          * Ok, create our new indirect block
2147          */
2148         dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2149         dummy.bref.key = key;
2150         dummy.bref.keybits = keybits;
2151         dummy.bref.data_off = hammer2_bytes_to_radix(nbytes);
2152         ichain = hammer2_chain_alloc(hmp, &dummy.bref);
2153         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2154
2155         /*
2156          * Iterate the original parent and move the matching brefs into
2157          * the new indirect block.
2158          */
2159         for (i = 0; i < count; ++i) {
2160                 /*
2161                  * For keying purposes access the bref from the media or
2162                  * from our in-memory cache.  In cases where the in-memory
2163                  * cache overrides the media the keyrefs will be the same
2164                  * anyway so we can avoid checking the cache when the media
2165                  * has a key.
2166                  */
2167                 dummy.index = i;
2168                 chain = RB_FIND(hammer2_chain_tree, &parent->rbhead, &dummy);
2169                 if (chain) {
2170                         /*
2171                          * NOTE! CHAIN_DELETED elements have to be adjusted
2172                          *       too, they cannot be ignored.
2173                          */
2174                         bref = &chain->bref;
2175                 } else if (base && base[i].type) {
2176                         bref = &base[i];
2177                 } else {
2178                         if (ichain->index < 0)
2179                                 ichain->index = i;
2180                         continue;
2181                 }
2182
2183                 /*
2184                  * Skip keys not in the chosen half (low or high), only bit
2185                  * (keybits - 1) needs to be compared but for safety we
2186                  * will compare all msb bits plus that bit again.
2187                  */
2188                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2189                     (key ^ bref->key)) != 0) {
2190                         continue;
2191                 }
2192
2193                 /*
2194                  * This element is being moved from the parent, its slot
2195                  * is available for our new indirect block.
2196                  */
2197                 if (ichain->index < 0)
2198                         ichain->index = i;
2199
2200                 /*
2201                  * Load the new indirect block by acquiring or allocating
2202                  * the related chain entries, then simply move them to the
2203                  * new parent (ichain).  We cannot move chains which are
2204                  * undergoing flushing and will break out of the loop in
2205                  * that case.
2206                  *
2207                  * When adjusting the parent/child relationship we must
2208                  * set the MOVED bit but we do NOT update bref_flush
2209                  * because otherwise we might synchronize a bref that has
2210                  * not yet been flushed.  We depend on chain's bref_flush
2211                  * either being correct or the chain being in a MODIFIED
2212                  * state.
2213                  *
2214                  * We do not want to set MODIFIED here as this would result
2215                  * in unnecessary reallocations.
2216                  *
2217                  * We must still set SUBMODIFIED in the parent but we do
2218                  * that after the loop.
2219                  *
2220                  * WARNING! chain->cst.spin must be held when chain->parent is
2221                  *          modified, even though we own the full blown lock,
2222                  *          to deal with setsubmod and rename races.
2223                  */
2224                 chain = hammer2_chain_get(hmp, parent, i,
2225                                           HAMMER2_LOOKUP_NODATA);
2226                 if (chain->flushing) {
2227                         hammer2_chain_unlock(hmp, chain);
2228                         break;
2229                 }
2230
2231                 spin_lock(&chain->cst.spin);
2232                 RB_REMOVE(hammer2_chain_tree, &parent->rbhead, chain);
2233                 if (RB_INSERT(hammer2_chain_tree, &ichain->rbhead, chain))
2234                         panic("hammer2_chain_create_indirect: collision");
2235                 chain->parent = ichain;
2236                 spin_unlock(&chain->cst.spin);
2237
2238                 if (base)
2239                         bzero(&base[i], sizeof(base[i]));
2240                 atomic_add_int(&parent->refs, -1);
2241                 atomic_add_int(&ichain->refs, 1);
2242                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2243                         hammer2_chain_ref(hmp, chain);
2244                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2245                 }
2246                 hammer2_chain_unlock(hmp, chain);
2247                 KKASSERT(parent->refs > 0);
2248                 chain = NULL;
2249         }
2250
2251         /*
2252          * If we hit a chain that is undergoing flushing we're screwed and
2253          * we have to duno the whole mess.  Since ichain has not been linked
2254          * in yet, the moved chains are not reachable and will not have been
2255          * disposed of.
2256          *
2257          * WARNING! This code is pretty hairy because the flusher is sitting
2258          *          on the parent processing one of the children that we
2259          *          haven't yet moved, and will do a RB_NEXT loop on that
2260          *          child.  So the children we're moving back have to be
2261          *          returned to the same place in the iteration that they
2262          *          were removed from.
2263          */
2264         if (i != count) {
2265                 kprintf("hammer2_chain_create_indirect: EAGAIN\n");
2266                 *errorp = EAGAIN;
2267                 while ((chain = RB_ROOT(&ichain->rbhead)) != NULL) {
2268                         hammer2_chain_lock(hmp, chain, HAMMER2_RESOLVE_NEVER);
2269                         KKASSERT(chain->flushing == 0);
2270                         RB_REMOVE(hammer2_chain_tree, &ichain->rbhead, chain);
2271                         if (RB_INSERT(hammer2_chain_tree, &parent->rbhead, chain))
2272                                 panic("hammer2_chain_create_indirect: collision");
2273                         chain->parent = parent;
2274                         atomic_add_int(&parent->refs, 1);
2275                         atomic_add_int(&ichain->refs, -1);
2276                         /* MOVED bit might have been inherited, cannot undo */
2277                         hammer2_chain_unlock(hmp, chain);
2278                 }
2279                 hammer2_chain_free(hmp, ichain);
2280                 return(NULL);
2281         }
2282
2283         /*
2284          * Insert the new indirect block into the parent now that we've
2285          * cleared out some entries in the parent.  We calculated a good
2286          * insertion index in the loop above (ichain->index).
2287          *
2288          * We don't have to set MOVED here because we mark ichain modified
2289          * down below (so the normal modified -> flush -> set-moved sequence
2290          * applies).
2291          */
2292         KKASSERT(ichain->index >= 0);
2293         if (RB_INSERT(hammer2_chain_tree, &parent->rbhead, ichain))
2294                 panic("hammer2_chain_create_indirect: ichain insertion");
2295         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_ONRBTREE);
2296         ichain->parent = parent;
2297         atomic_add_int(&parent->refs, 1);
2298
2299         /*
2300          * Mark the new indirect block modified after insertion, which
2301          * will propagate up through parent all the way to the root and
2302          * also allocate the physical block in ichain for our caller,
2303          * and assign ichain->data to a pre-zero'd space (because there
2304          * is not prior data to copy into it).
2305          *
2306          * We have to set SUBMODIFIED in ichain's flags manually so the
2307          * flusher knows it has to recurse through it to get to all of
2308          * our moved blocks, then call setsubmod() to set the bit
2309          * recursively.
2310          */
2311         hammer2_chain_modify(hmp, ichain, HAMMER2_MODIFY_OPTDATA);
2312         hammer2_chain_parent_setsubmod(hmp, ichain);
2313         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2314
2315         /*
2316          * Figure out what to return.
2317          */
2318         if (create_bits > keybits) {
2319                 /*
2320                  * Key being created is way outside the key range,
2321                  * return the original parent.
2322                  */
2323                 hammer2_chain_unlock(hmp, ichain);
2324         } else if (~(((hammer2_key_t)1 << keybits) - 1) &
2325                    (create_key ^ key)) {
2326                 /*
2327                  * Key being created is outside the key range,
2328                  * return the original parent.
2329                  */
2330                 hammer2_chain_unlock(hmp, ichain);
2331         } else {
2332                 /*
2333                  * Otherwise its in the range, return the new parent.
2334                  * (leave both the new and old parent locked).
2335                  */
2336                 parent = ichain;
2337         }
2338
2339         return(parent);
2340 }
2341
2342 /*
2343  * Physically delete the specified chain element.  Note that inodes with
2344  * open descriptors should not be deleted (as with other filesystems) until
2345  * the last open descriptor is closed.
2346  *
2347  * This routine will remove the chain element from its parent and potentially
2348  * also recurse upward and delete indirect blocks which become empty as a
2349  * side effect.
2350  *
2351  * The caller must pass a pointer to the chain's parent, also locked and
2352  * referenced.  (*parentp) will be modified in a manner similar to a lookup
2353  * or iteration when indirect blocks are also deleted as a side effect.
2354  *
2355  * XXX This currently does not adhere to the MOVED flag protocol in that
2356  *     the removal is immediately indicated in the parent's blockref[]
2357  *     array.
2358  *
2359  * Must be called with an exclusively locked parent and chain.
2360  */
2361 void
2362 hammer2_chain_delete(hammer2_mount_t *hmp, hammer2_chain_t *parent,
2363                      hammer2_chain_t *chain, int retain)
2364 {
2365         hammer2_blockref_t *base;
2366         hammer2_inode_t *ip;
2367         int count;
2368
2369         if (chain->parent != parent)
2370                 panic("hammer2_chain_delete: parent mismatch");
2371         KKASSERT(ccms_thread_lock_owned(&parent->cst));
2372
2373         /*
2374          * Mark the parent modified so our base[] pointer remains valid
2375          * while we move entries.  For the optimized indirect block
2376          * case mark the parent moved instead.
2377          *
2378          * Calculate the blockref reference in the parent
2379          */
2380         switch(parent->bref.type) {
2381         case HAMMER2_BREF_TYPE_INODE:
2382                 hammer2_chain_modify(hmp, parent, HAMMER2_MODIFY_NO_MODIFY_TID);
2383                 base = &parent->data->ipdata.u.blockset.blockref[0];
2384                 count = HAMMER2_SET_COUNT;
2385                 break;
2386         case HAMMER2_BREF_TYPE_INDIRECT:
2387                 hammer2_chain_modify(hmp, parent, HAMMER2_MODIFY_OPTDATA |
2388                                                   HAMMER2_MODIFY_NO_MODIFY_TID);
2389                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2390                         base = NULL;
2391                 else
2392                         base = &parent->data->npdata.blockref[0];
2393                 count = parent->bytes / sizeof(hammer2_blockref_t);
2394                 break;
2395         case HAMMER2_BREF_TYPE_VOLUME:
2396                 hammer2_chain_modify(hmp, parent, HAMMER2_MODIFY_NO_MODIFY_TID);
2397                 base = &hmp->voldata.sroot_blockset.blockref[0];
2398                 count = HAMMER2_SET_COUNT;
2399                 break;
2400         default:
2401                 panic("hammer2_chain_delete: unrecognized blockref type: %d",
2402                       parent->bref.type);
2403                 count = 0;
2404                 break;
2405         }
2406         KKASSERT(chain->index >= 0 && chain->index < count);
2407
2408         /*
2409          * We may not be able to immediately disconnect the chain if a
2410          * flush is in progress.  If retain is non-zero we MUST disconnect
2411          * the chain now and callers are responsible for making sure that
2412          * flushing is zero.
2413          */
2414         spin_lock(&chain->cst.spin);
2415         if ((retain || chain->flushing == 0) &&
2416             (chain->flags & HAMMER2_CHAIN_ONRBTREE)) {
2417                 if (base)
2418                         bzero(&base[chain->index], sizeof(*base));
2419                 KKASSERT(chain->flushing == 0);
2420                 RB_REMOVE(hammer2_chain_tree, &parent->rbhead, chain);
2421                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2422                 atomic_add_int(&parent->refs, -1);   /* for red-black entry */
2423                 chain->index = -1;
2424                 chain->parent = NULL;
2425         }
2426         spin_unlock(&chain->cst.spin);
2427
2428         /*
2429          * Cumulative adjustments must be propagated to the parent inode
2430          * when deleting and synchronized to ip.  This occurs even if we
2431          * cannot detach the chain from its parent.
2432          *
2433          * NOTE:  We do not propagate ip->delta_*count to the parent because
2434          *        these represent adjustments that have not yet been
2435          *        propagated upward, so we don't need to remove them from
2436          *        the parent.
2437          *
2438          * Clear the pointer to the parent inode.
2439          */
2440         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
2441             chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2442                 ip = chain->u.ip;
2443                 if (ip->pip) {
2444                         /* XXX SMP, pip chain not necessarily parent chain */
2445                         ip->pip->delta_icount -= ip->ip_data.inode_count;
2446                         ip->pip->delta_dcount -= ip->ip_data.data_count;
2447                         ip->ip_data.inode_count += ip->delta_icount;
2448                         ip->ip_data.data_count += ip->delta_dcount;
2449                         ip->delta_icount = 0;
2450                         ip->delta_dcount = 0;
2451                         --ip->pip->delta_icount;
2452                         spin_lock(&chain->cst.spin); /* XXX */
2453                         ip->pip = NULL;
2454                         spin_unlock(&chain->cst.spin);
2455                 }
2456         }
2457
2458         /*
2459          * If retain is 0 the deletion is permanent.  Because the chain is
2460          * no longer connected to the topology a flush will have no
2461          * visibility into it.  We must dispose of the references related
2462          * to the MODIFIED and MOVED flags, otherwise the ref count will
2463          * never transition to 0.
2464          *
2465          * If retain is non-zero the deleted element is likely an inode
2466          * which the vnops frontend will mark DESTROYED and flush.  In that
2467          * situation we must retain the flags for any open file descriptors
2468          * on the (removed) inode.  The final close will destroy the
2469          * disconnected chain.
2470          */
2471         if (retain == 0) {
2472                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2473                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
2474                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
2475                         hammer2_chain_drop(hmp, chain);
2476                 }
2477                 if (chain->flags & HAMMER2_CHAIN_MOVED) {
2478                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2479                         hammer2_chain_drop(hmp, chain);
2480                 }
2481         }
2482
2483         /*
2484          * The chain is still likely referenced, possibly even by a vnode
2485          * (if an inode), so defer further action until the chain gets
2486          * dropped.
2487          */
2488 }
2489
2490 void
2491 hammer2_chain_wait(hammer2_mount_t *hmp, hammer2_chain_t *chain)
2492 {
2493         tsleep(chain, 0, "chnflw", 1);
2494 }