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