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