hammer2 - flush sequencing part 4 - stabilization and cleanup, flush sep
[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          * The parent does not have to be locked for the delete/duplicate call,
823          * but is in this particular code path.
824          *
825          * NOTE: If we are not crossing a synchronization point the
826          *       duplication code will simply reuse the existing chain
827          *       structure.
828          */
829         hammer2_chain_delete_duplicate(trans, &chain);
830
831         /*
832          * Set MODIFIED and add a chain ref to prevent destruction.  Both
833          * modified flags share the same ref.  (duplicated chains do not
834          * start out MODIFIED unless possibly if the duplication code
835          * decided to reuse the existing chain as-is).
836          *
837          * If the chain is already marked MODIFIED then we can safely
838          * return the previous allocation to the pool without having to
839          * worry about snapshots.  XXX check flush synchronization.
840          */
841         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
842                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
843                 hammer2_chain_ref(chain);
844         } else {
845 #if 0
846                 hammer2_freemap_free(hmp, chain->bref.data_off,
847                                      chain->bref.type);
848 #endif
849         }
850
851         /*
852          * Relocate the block, even if making it smaller (because different
853          * block sizes may be in different regions).
854          */
855         chain->bref.data_off = hammer2_freemap_alloc(hmp, chain->bref.type,
856                                                      nbytes);
857         chain->bytes = nbytes;
858         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
859
860         /*
861          * The device buffer may be larger than the allocation size.
862          */
863         if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
864                 bbytes = HAMMER2_MINIOSIZE;
865         pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
866         boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
867
868         KKASSERT(chain->bp == NULL);
869 #if 0
870         /*
871          * Only copy the data if resolved, otherwise the caller is
872          * responsible.
873          *
874          * XXX handle device-buffer resizing case too.  Right now we
875          *     only handle logical buffer resizing.
876          */
877         if (chain->bp) {
878                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
879                          chain->bref.type == HAMMER2_BREF_TYPE_DATA);
880                 KKASSERT(chain != &hmp->vchain);        /* safety */
881
882                 /*
883                  * The getblk() optimization can only be used if the
884                  * physical block size matches the request.
885                  */
886                 if (nbytes == bbytes) {
887                         nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
888                         error = 0;
889                 } else {
890                         error = bread(hmp->devvp, pbase, bbytes, &nbp);
891                         KKASSERT(error == 0);
892                 }
893                 bdata = (char *)nbp->b_data + boff;
894
895                 /*
896                  * chain->bp and chain->data represent the on-disk version
897                  * of the data, where as the passed-in bp is usually a
898                  * more up-to-date logical buffer.  However, there is no
899                  * need to synchronize the more up-to-date data in (bp)
900                  * as it will do that on its own when it flushes.
901                  */
902                 if (nbytes < obytes) {
903                         bcopy(chain->data, bdata, nbytes);
904                 } else {
905                         bcopy(chain->data, bdata, obytes);
906                         bzero(bdata + obytes, nbytes - obytes);
907                 }
908
909                 /*
910                  * NOTE: The INITIAL state of the chain is left intact.
911                  *       We depend on hammer2_chain_modify() to do the
912                  *       right thing.
913                  *
914                  * NOTE: We set B_NOCACHE to throw away the previous bp and
915                  *       any VM backing store, even if it was dirty.
916                  *       Otherwise we run the risk of a logical/device
917                  *       conflict on reallocation.
918                  */
919                 chain->bp->b_flags |= B_RELBUF | B_NOCACHE;
920                 brelse(chain->bp);
921                 chain->bp = nbp;
922                 chain->data = (void *)bdata;
923                 hammer2_chain_modify(trans, &chain, 0);
924         }
925 #endif
926
927         /*
928          * Make sure the chain is marked MOVED and SUBMOD is set in the
929          * parent(s) so the adjustments are picked up by flush.
930          */
931         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
932                 hammer2_chain_ref(chain);
933                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
934         }
935         hammer2_chain_parent_setsubmod(trans, chain);
936         *chainp = chain;
937 }
938
939 /*
940  * Set a chain modified, making it read-write and duplicating it if necessary.
941  * This function will assign a new physical block to the chain if necessary
942  *
943  * Duplication of already-modified chains is possible when the modification
944  * crosses a flush synchronization boundary.
945  *
946  * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
947  *                   level or the COW operation will not work.
948  *
949  * Data blocks     - The chain is usually locked RESOLVE_NEVER so as not to
950  *                   run the data through the device buffers.
951  *
952  * This function may return a different chain than was passed, in which case
953  * the old chain will be unlocked and the new chain will be locked.
954  *
955  * ip->chain may be adjusted by hammer2_chain_modify_ip().
956  */
957 hammer2_inode_data_t *
958 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
959                         hammer2_chain_t **parentp, int flags)
960 {
961         hammer2_chain_t *chain;
962
963         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
964         hammer2_chain_modify(trans, parentp, flags);
965         if ((chain = ip->chain) != NULL) {
966                 while (chain->duplink && (chain->flags & HAMMER2_CHAIN_DELETED))
967                         chain = chain->duplink;
968                 if (ip->chain != chain) {
969                         hammer2_chain_ref(chain);
970                         hammer2_chain_drop(ip->chain);
971                         ip->chain = chain;
972                 }
973         }
974         return(&ip->chain->data->ipdata);
975 }
976
977 void
978 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
979                      int flags)
980 {
981         hammer2_mount_t *hmp = trans->hmp;
982         hammer2_chain_t *chain;
983         hammer2_off_t pbase;
984         struct buf *nbp;
985         int error;
986         size_t bbytes;
987         size_t boff;
988         void *bdata;
989
990         /*
991          * modify_tid is only update for primary modifications, not for
992          * propagated brefs.  mirror_tid will be updated regardless during
993          * the flush, no need to set it here.
994          */
995         chain = *chainp;
996
997         /*
998          * If the chain is already marked MODIFIED we can usually just
999          * return.  However, if a modified chain is modified again in
1000          * a synchronization-point-crossing manner we have to
1001          * delete/duplicate the chain so as not to interfere with the
1002          * atomicy of the flush.
1003          */
1004         if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1005                 if (chain->modify_tid <= hmp->flush_tid &&
1006                     trans->sync_tid > hmp->flush_tid) {
1007                         /*
1008                          * Modifications cross synchronization point,
1009                          * requires delete-duplicate.
1010                          */
1011                         hammer2_chain_delete_duplicate(trans, chainp);
1012                         chain = *chainp;
1013                         /* fall through using duplicate */
1014                 } else {
1015                         /*
1016                          * It is possible that a prior lock/modify sequence
1017                          * retired the buffer.  During this lock/modify
1018                          * sequence MODIFIED may still be set but the buffer
1019                          * could wind up clean.  Since the caller is going
1020                          * to modify the buffer further we have to be sure
1021                          * that DIRTYBP is set so our chain code knows to
1022                          * bwrite/bdwrite the bp.
1023                          */
1024                         if ((flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1025                             chain->bp == NULL) {
1026                                 goto skip1;
1027                         }
1028                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1029                         if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1030                                 chain->bref.modify_tid = trans->sync_tid;
1031                         return;
1032                 }
1033         }
1034
1035         if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1036                 chain->bref.modify_tid = trans->sync_tid;
1037
1038         /*
1039          * Set MODIFIED and add a chain ref to prevent destruction.  Both
1040          * modified flags share the same ref.
1041          */
1042         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1043                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1044                 hammer2_chain_ref(chain);
1045         }
1046
1047         /*
1048          * Adjust chain->modify_tid so the flusher knows when the
1049          * modification occurred.
1050          */
1051         chain->modify_tid = trans->sync_tid;
1052
1053         /*
1054          * We must allocate the copy-on-write block.
1055          *
1056          * If the data is embedded no other action is required.
1057          *
1058          * If the data is not embedded we acquire and clear the
1059          * new block.  If chain->data is not NULL we then do the
1060          * copy-on-write.  chain->data will then be repointed to the new
1061          * buffer and the old buffer will be released.
1062          *
1063          * For newly created elements with no prior allocation we go
1064          * through the copy-on-write steps except without the copying part.
1065          */
1066         if (chain != &hmp->vchain) {
1067                 if ((hammer2_debug & 0x0001) &&
1068                     (chain->bref.data_off & HAMMER2_OFF_MASK)) {
1069                         kprintf("Replace %d\n", chain->bytes);
1070                 }
1071                 chain->bref.data_off =
1072                         hammer2_freemap_alloc(hmp, chain->bref.type,
1073                                               chain->bytes);
1074                 /* XXX failed allocation */
1075         }
1076
1077         /*
1078          * If data instantiation is optional and the chain has no current
1079          * data association (typical for DATA and newly-created INDIRECT
1080          * elements), don't instantiate the buffer now.
1081          */
1082         if ((flags & HAMMER2_MODIFY_OPTDATA) && chain->bp == NULL)
1083                 goto skip2;
1084
1085 skip1:
1086         /*
1087          * Setting the DIRTYBP flag will cause the buffer to be dirtied or
1088          * written-out on unlock.  This bit is independent of the MODIFIED
1089          * bit because the chain may still need meta-data adjustments done
1090          * by virtue of MODIFIED for its parent, and the buffer can be
1091          * flushed out (possibly multiple times) by the OS before that.
1092          *
1093          * Clearing the INITIAL flag (for indirect blocks) indicates that
1094          * a zero-fill buffer has been instantiated.
1095          */
1096         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1097         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1098
1099         /*
1100          * We currently should never instantiate a device buffer for a
1101          * file data chain.  (We definitely can for a freemap chain).
1102          */
1103         KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_DATA);
1104
1105         /*
1106          * Execute COW operation
1107          */
1108         switch(chain->bref.type) {
1109         case HAMMER2_BREF_TYPE_VOLUME:
1110         case HAMMER2_BREF_TYPE_INODE:
1111                 /*
1112                  * The data is embedded, no copy-on-write operation is
1113                  * needed.
1114                  */
1115                 KKASSERT(chain->bp == NULL);
1116                 break;
1117         case HAMMER2_BREF_TYPE_DATA:
1118         case HAMMER2_BREF_TYPE_INDIRECT:
1119         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1120         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1121         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1122                 /*
1123                  * Perform the copy-on-write operation
1124                  */
1125                 KKASSERT(chain != &hmp->vchain);        /* safety */
1126                 /*
1127                  * The device buffer may be larger than the allocation size.
1128                  */
1129                 if ((bbytes = chain->bytes) < HAMMER2_MINIOSIZE)
1130                         bbytes = HAMMER2_MINIOSIZE;
1131                 pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1132                 boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1133
1134                 /*
1135                  * The getblk() optimization can only be used if the
1136                  * physical block size matches the request.
1137                  */
1138                 if (chain->bytes == bbytes) {
1139                         nbp = getblk(hmp->devvp, pbase, bbytes, 0, 0);
1140                         error = 0;
1141                 } else {
1142                         error = bread(hmp->devvp, pbase, bbytes, &nbp);
1143                         KKASSERT(error == 0);
1144                 }
1145                 bdata = (char *)nbp->b_data + boff;
1146
1147                 /*
1148                  * Copy or zero-fill on write depending on whether
1149                  * chain->data exists or not.
1150                  */
1151                 if (chain->data) {
1152                         bcopy(chain->data, bdata, chain->bytes);
1153                         KKASSERT(chain->bp != NULL);
1154                 } else {
1155                         bzero(bdata, chain->bytes);
1156                 }
1157                 if (chain->bp) {
1158                         chain->bp->b_flags |= B_RELBUF;
1159                         brelse(chain->bp);
1160                 }
1161                 chain->bp = nbp;
1162                 chain->data = bdata;
1163                 break;
1164         default:
1165                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1166                       chain->bref.type);
1167                 break;
1168
1169         }
1170 skip2:
1171         if ((flags & HAMMER2_MODIFY_NOSUB) == 0)
1172                 hammer2_chain_parent_setsubmod(trans, chain);
1173 }
1174
1175 /*
1176  * Mark the volume as having been modified.  This short-cut version
1177  * does not have to lock the volume's chain, which allows the ioctl
1178  * code to make adjustments to connections without deadlocking.  XXX
1179  *
1180  * No ref is made on vchain when flagging it MODIFIED.
1181  */
1182 void
1183 hammer2_modify_volume(hammer2_mount_t *hmp)
1184 {
1185         hammer2_voldata_lock(hmp);
1186         hammer2_voldata_unlock(hmp, 1);
1187 }
1188
1189 /*
1190  * Locate an in-memory chain.  The parent must be locked.  The in-memory
1191  * chain is returned with a reference and without a lock, or NULL
1192  * if not found.
1193  *
1194  * This function returns the chain at the specified index with the highest
1195  * delete_tid.  The caller must check whether the chain is flagged
1196  * CHAIN_DELETED or not.
1197  *
1198  * NOTE: If no chain is found the caller usually must check the on-media
1199  *       array to determine if a blockref exists at the index.
1200  */
1201 struct hammer2_chain_find_info {
1202         hammer2_chain_t *best;
1203         hammer2_tid_t   delete_tid;
1204         int index;
1205 };
1206
1207 static
1208 int
1209 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1210 {
1211         struct hammer2_chain_find_info *info = data;
1212
1213         if (child->index < info->index)
1214                 return(-1);
1215         if (child->index > info->index)
1216                 return(1);
1217         return(0);
1218 }
1219
1220 static
1221 int
1222 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1223 {
1224         struct hammer2_chain_find_info *info = data;
1225
1226         if (info->delete_tid < child->delete_tid) {
1227                 info->delete_tid = child->delete_tid;
1228                 info->best = child;
1229         }
1230         return(0);
1231 }
1232
1233 static
1234 hammer2_chain_t *
1235 hammer2_chain_find_locked(hammer2_chain_t *parent, int index)
1236 {
1237         struct hammer2_chain_find_info info;
1238
1239         info.index = index;
1240         info.delete_tid = 0;
1241         info.best = NULL;
1242
1243         RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1244                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1245                 &info);
1246
1247         return (info.best);
1248 }
1249
1250 hammer2_chain_t *
1251 hammer2_chain_find(hammer2_chain_t *parent, int index)
1252 {
1253         hammer2_chain_t *chain;
1254
1255         spin_lock(&parent->core->cst.spin);
1256         chain = hammer2_chain_find_locked(parent, index);
1257         if (chain)
1258                 hammer2_chain_ref(chain);
1259         spin_unlock(&parent->core->cst.spin);
1260
1261         return (chain);
1262 }
1263
1264 /*
1265  * Return a locked chain structure with all associated data acquired.
1266  * (if LOOKUP_NOLOCK is requested the returned chain is only referenced).
1267  *
1268  * Caller must hold the parent locked shared or exclusive since we may
1269  * need the parent's bref array to find our block.
1270  *
1271  * The returned child is locked as requested.  If NOLOCK, the returned
1272  * child is still at least referenced.
1273  */
1274 hammer2_chain_t *
1275 hammer2_chain_get(hammer2_chain_t *parent, int index, int flags)
1276 {
1277         hammer2_blockref_t *bref;
1278         hammer2_mount_t *hmp = parent->hmp;
1279         hammer2_chain_t *chain;
1280         hammer2_chain_t dummy;
1281         int how;
1282
1283         /*
1284          * Figure out how to lock.  MAYBE can be used to optimized
1285          * the initial-create state for indirect blocks.
1286          */
1287         if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK))
1288                 how = HAMMER2_RESOLVE_NEVER;
1289         else
1290                 how = HAMMER2_RESOLVE_MAYBE;
1291         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1292                 how |= HAMMER2_RESOLVE_SHARED;
1293
1294 retry:
1295         /*
1296          * First see if we have a (possibly modified) chain element cached
1297          * for this (parent, index).  Acquire the data if necessary.
1298          *
1299          * If chain->data is non-NULL the chain should already be marked
1300          * modified.
1301          */
1302         dummy.flags = 0;
1303         dummy.index = index;
1304         dummy.delete_tid = HAMMER2_MAX_TID;
1305         spin_lock(&parent->core->cst.spin);
1306         chain = RB_FIND(hammer2_chain_tree, &parent->core->rbtree, &dummy);
1307         if (chain) {
1308                 hammer2_chain_ref(chain);
1309                 spin_unlock(&parent->core->cst.spin);
1310                 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1311                         hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1312                 return(chain);
1313         }
1314         spin_unlock(&parent->core->cst.spin);
1315
1316         /*
1317          * The parent chain must not be in the INITIAL state.
1318          */
1319         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1320                 panic("hammer2_chain_get: Missing bref(1)");
1321                 /* NOT REACHED */
1322         }
1323
1324         /*
1325          * No RBTREE entry found, lookup the bref and issue I/O (switch on
1326          * the parent's bref to determine where and how big the array is).
1327          */
1328         switch(parent->bref.type) {
1329         case HAMMER2_BREF_TYPE_INODE:
1330                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1331                 bref = &parent->data->ipdata.u.blockset.blockref[index];
1332                 break;
1333         case HAMMER2_BREF_TYPE_INDIRECT:
1334         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1335         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1336                 KKASSERT(parent->data != NULL);
1337                 KKASSERT(index >= 0 &&
1338                          index < parent->bytes / sizeof(hammer2_blockref_t));
1339                 bref = &parent->data->npdata.blockref[index];
1340                 break;
1341         case HAMMER2_BREF_TYPE_VOLUME:
1342                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1343                 bref = &hmp->voldata.sroot_blockset.blockref[index];
1344                 break;
1345         default:
1346                 bref = NULL;
1347                 panic("hammer2_chain_get: unrecognized blockref type: %d",
1348                       parent->bref.type);
1349         }
1350         if (bref->type == 0) {
1351                 panic("hammer2_chain_get: Missing bref(2)");
1352                 /* NOT REACHED */
1353         }
1354
1355         /*
1356          * Allocate a chain structure representing the existing media
1357          * entry.  Resulting chain has one ref and is not locked.
1358          *
1359          * The locking operation we do later will issue I/O to read it.
1360          */
1361         chain = hammer2_chain_alloc(hmp, bref);
1362         hammer2_chain_core_alloc(chain, NULL);  /* ref'd chain returned */
1363
1364         /*
1365          * Link the chain into its parent.  A spinlock is required to safely
1366          * access the RBTREE, and it is possible to collide with another
1367          * hammer2_chain_get() operation because the caller might only hold
1368          * a shared lock on the parent.
1369          */
1370         KKASSERT(parent->refs > 0);
1371         spin_lock(&parent->core->cst.spin);
1372         chain->parent = parent;
1373         chain->index = index;
1374         if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, chain)) {
1375                 chain->parent = NULL;
1376                 chain->index = -1;
1377                 spin_unlock(&parent->core->cst.spin);
1378                 hammer2_chain_drop(chain);
1379                 goto retry;
1380         }
1381         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
1382         hammer2_chain_ref(parent);              /* chain->parent ref */
1383         spin_unlock(&parent->core->cst.spin);
1384
1385         /*
1386          * Our new chain is referenced but NOT locked.  Lock the chain
1387          * below.  The locking operation also resolves its data.
1388          *
1389          * If NOLOCK is set the release will release the one-and-only lock.
1390          */
1391         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0) {
1392                 hammer2_chain_lock(chain, how); /* recusive lock */
1393                 hammer2_chain_drop(chain);      /* excess ref */
1394         }
1395         return (chain);
1396 }
1397
1398 /*
1399  * Lookup initialization/completion API
1400  */
1401 hammer2_chain_t *
1402 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1403 {
1404         if (flags & HAMMER2_LOOKUP_SHARED) {
1405                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1406                                            HAMMER2_RESOLVE_SHARED);
1407         } else {
1408                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1409         }
1410         return (parent);
1411 }
1412
1413 void
1414 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1415 {
1416         if (parent)
1417                 hammer2_chain_unlock(parent);
1418 }
1419
1420
1421 /*
1422  * Locate any key between key_beg and key_end inclusive.  (*parentp)
1423  * typically points to an inode but can also point to a related indirect
1424  * block and this function will recurse upwards and find the inode again.
1425  *
1426  * WARNING!  THIS DOES NOT RETURN KEYS IN LOGICAL KEY ORDER!  ANY KEY
1427  *           WITHIN THE RANGE CAN BE RETURNED.  HOWEVER, AN ITERATION
1428  *           WHICH PICKS UP WHERE WE LEFT OFF WILL CONTINUE THE SCAN.
1429  *
1430  * (*parentp) must be exclusively locked and referenced and can be an inode
1431  * or an existing indirect block within the inode.
1432  *
1433  * On return (*parentp) will be modified to point at the deepest parent chain
1434  * element encountered during the search, as a helper for an insertion or
1435  * deletion.   The new (*parentp) will be locked and referenced and the old
1436  * will be unlocked and dereferenced (no change if they are both the same).
1437  *
1438  * The matching chain will be returned exclusively locked.  If NOLOCK is
1439  * requested the chain will be returned only referenced.
1440  *
1441  * NULL is returned if no match was found, but (*parentp) will still
1442  * potentially be adjusted.
1443  *
1444  * This function will also recurse up the chain if the key is not within the
1445  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1446  * can simply allow (*parentp) to float inside the loop.
1447  */
1448 hammer2_chain_t *
1449 hammer2_chain_lookup(hammer2_chain_t **parentp,
1450                      hammer2_key_t key_beg, hammer2_key_t key_end,
1451                      int flags)
1452 {
1453         hammer2_mount_t *hmp;
1454         hammer2_chain_t *parent;
1455         hammer2_chain_t *chain;
1456         hammer2_chain_t *tmp;
1457         hammer2_blockref_t *base;
1458         hammer2_blockref_t *bref;
1459         hammer2_key_t scan_beg;
1460         hammer2_key_t scan_end;
1461         int count = 0;
1462         int i;
1463         int how_always = HAMMER2_RESOLVE_ALWAYS;
1464         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1465
1466         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1467                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1468                 how_always |= HAMMER2_RESOLVE_SHARED;
1469         }
1470
1471         /*
1472          * Recurse (*parentp) upward if necessary until the parent completely
1473          * encloses the key range or we hit the inode.
1474          */
1475         parent = *parentp;
1476         hmp = parent->hmp;
1477
1478         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1479                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1480                 scan_beg = parent->bref.key;
1481                 scan_end = scan_beg +
1482                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1483                 if (key_beg >= scan_beg && key_end <= scan_end)
1484                         break;
1485                 /*
1486                  * XXX flush synchronization
1487                  */
1488                 tmp = parent->parent;
1489                 while (tmp->duplink &&
1490                        (tmp->flags & HAMMER2_CHAIN_DELETED)) {
1491                         tmp = tmp->duplink;
1492                 }
1493                 hammer2_chain_ref(tmp);         /* ref new parent */
1494                 hammer2_chain_unlock(parent);   /* unlock old parent */
1495                                                 /* lock new parent */
1496                 hammer2_chain_lock(tmp, how_maybe |
1497                                         HAMMER2_RESOLVE_NOREF);
1498                 *parentp = parent = tmp;                /* new parent */
1499         }
1500
1501 again:
1502         /*
1503          * Locate the blockref array.  Currently we do a fully associative
1504          * search through the array.
1505          */
1506         switch(parent->bref.type) {
1507         case HAMMER2_BREF_TYPE_INODE:
1508                 /*
1509                  * Special shortcut for embedded data returns the inode
1510                  * itself.  Callers must detect this condition and access
1511                  * the embedded data (the strategy code does this for us).
1512                  *
1513                  * This is only applicable to regular files and softlinks.
1514                  */
1515                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1516                         if (flags & HAMMER2_LOOKUP_NOLOCK)
1517                                 hammer2_chain_ref(parent);
1518                         else
1519                                 hammer2_chain_lock(parent, how_always);
1520                         return (parent);
1521                 }
1522                 base = &parent->data->ipdata.u.blockset.blockref[0];
1523                 count = HAMMER2_SET_COUNT;
1524                 break;
1525         case HAMMER2_BREF_TYPE_INDIRECT:
1526         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1527         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1528                 /*
1529                  * Optimize indirect blocks in the INITIAL state to avoid
1530                  * I/O.
1531                  */
1532                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1533                         base = NULL;
1534                 } else {
1535                         if (parent->data == NULL)
1536                                 panic("parent->data is NULL");
1537                         base = &parent->data->npdata.blockref[0];
1538                 }
1539                 count = parent->bytes / sizeof(hammer2_blockref_t);
1540                 break;
1541         case HAMMER2_BREF_TYPE_VOLUME:
1542                 base = &hmp->voldata.sroot_blockset.blockref[0];
1543                 count = HAMMER2_SET_COUNT;
1544                 break;
1545         default:
1546                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1547                       parent->bref.type);
1548                 base = NULL;    /* safety */
1549                 count = 0;      /* safety */
1550         }
1551
1552         /*
1553          * If the element and key overlap we use the element.
1554          *
1555          * NOTE! Deleted elements are effectively invisible.  Deletions
1556          *       proactively clear the parent bref to the deleted child
1557          *       so we do not try to shadow here to avoid parent updates
1558          *       (which would be difficult since multiple deleted elements
1559          *       might represent different flush synchronization points).
1560          */
1561         bref = NULL;
1562         for (i = 0; i < count; ++i) {
1563                 tmp = hammer2_chain_find(parent, i);
1564                 if (tmp) {
1565                         if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1566                                 hammer2_chain_drop(tmp);
1567                                 continue;
1568                         }
1569                         bref = &tmp->bref;
1570                         KKASSERT(bref->type != 0);
1571                 } else if (base == NULL || base[i].type == 0) {
1572                         continue;
1573                 } else {
1574                         bref = &base[i];
1575                 }
1576                 scan_beg = bref->key;
1577                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1578                 if (tmp)
1579                         hammer2_chain_drop(tmp);
1580                 if (key_beg <= scan_end && key_end >= scan_beg)
1581                         break;
1582         }
1583         if (i == count) {
1584                 if (key_beg == key_end)
1585                         return (NULL);
1586                 return (hammer2_chain_next(parentp, NULL,
1587                                            key_beg, key_end, flags));
1588         }
1589
1590         /*
1591          * Acquire the new chain element.  If the chain element is an
1592          * indirect block we must search recursively.
1593          *
1594          * It is possible for the tmp chain above to be removed from
1595          * the RBTREE but the parent lock ensures it would not have been
1596          * destroyed from the media, so the chain_get() code will simply
1597          * reload it from the media in that case.
1598          */
1599         chain = hammer2_chain_get(parent, i, flags);
1600         if (chain == NULL)
1601                 return (NULL);
1602
1603         /*
1604          * If the chain element is an indirect block it becomes the new
1605          * parent and we loop on it.
1606          *
1607          * The parent always has to be locked with at least RESOLVE_MAYBE
1608          * so we can access its data.  It might need a fixup if the caller
1609          * passed incompatible flags.  Be careful not to cause a deadlock
1610          * as a data-load requires an exclusive lock.
1611          */
1612         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1613             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1614                 hammer2_chain_unlock(parent);
1615                 *parentp = parent = chain;
1616                 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1617                         hammer2_chain_lock(chain, how_maybe |
1618                                                   HAMMER2_RESOLVE_NOREF);
1619                 } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
1620                            chain->data == NULL) {
1621                         hammer2_chain_ref(chain);
1622                         hammer2_chain_unlock(chain);
1623                         hammer2_chain_lock(chain, how_maybe |
1624                                                   HAMMER2_RESOLVE_NOREF);
1625                 }
1626                 goto again;
1627         }
1628
1629         /*
1630          * All done, return the chain
1631          */
1632         return (chain);
1633 }
1634
1635 /*
1636  * After having issued a lookup we can iterate all matching keys.
1637  *
1638  * If chain is non-NULL we continue the iteration from just after it's index.
1639  *
1640  * If chain is NULL we assume the parent was exhausted and continue the
1641  * iteration at the next parent.
1642  *
1643  * parent must be locked on entry and remains locked throughout.  chain's
1644  * lock status must match flags.  Chain is always at least referenced.
1645  */
1646 hammer2_chain_t *
1647 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1648                    hammer2_key_t key_beg, hammer2_key_t key_end,
1649                    int flags)
1650 {
1651         hammer2_mount_t *hmp;
1652         hammer2_chain_t *parent;
1653         hammer2_chain_t *tmp;
1654         hammer2_blockref_t *base;
1655         hammer2_blockref_t *bref;
1656         hammer2_key_t scan_beg;
1657         hammer2_key_t scan_end;
1658         int i;
1659         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1660         int count;
1661
1662         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1663                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1664
1665         parent = *parentp;
1666         hmp = parent->hmp;
1667
1668 again:
1669         /*
1670          * Calculate the next index and recalculate the parent if necessary.
1671          */
1672         if (chain) {
1673                 /*
1674                  * Continue iteration within current parent.  If not NULL
1675                  * the passed-in chain may or may not be locked, based on
1676                  * the LOOKUP_NOLOCK flag (passed in as returned from lookup
1677                  * or a prior next).
1678                  */
1679                 i = chain->index + 1;
1680                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1681                         hammer2_chain_drop(chain);
1682                 else
1683                         hammer2_chain_unlock(chain);
1684
1685                 /*
1686                  * Any scan where the lookup returned degenerate data embedded
1687                  * in the inode has an invalid index and must terminate.
1688                  */
1689                 if (chain == parent)
1690                         return(NULL);
1691                 chain = NULL;
1692         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1693                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1694                 /*
1695                  * We reached the end of the iteration.
1696                  */
1697                 return (NULL);
1698         } else {
1699                 /*
1700                  * Continue iteration with next parent unless the current
1701                  * parent covers the range.
1702                  */
1703                 scan_beg = parent->bref.key;
1704                 scan_end = scan_beg +
1705                             ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1706                 if (key_beg >= scan_beg && key_end <= scan_end)
1707                         return (NULL);
1708
1709                 i = parent->index + 1;
1710                 /*
1711                  * XXX flush synchronization
1712                  */
1713                 tmp = parent->parent;
1714                 while (tmp->duplink &&
1715                        (tmp->flags & HAMMER2_CHAIN_DELETED)) {
1716                         tmp = tmp->duplink;
1717                 }
1718                 hammer2_chain_ref(tmp);         /* ref new parent */
1719                 hammer2_chain_unlock(parent);   /* unlock old parent */
1720                                                 /* lock new parent */
1721                 hammer2_chain_lock(tmp, how_maybe |
1722                                         HAMMER2_RESOLVE_NOREF);
1723                 *parentp = parent = tmp;
1724         }
1725
1726 again2:
1727         /*
1728          * Locate the blockref array.  Currently we do a fully associative
1729          * search through the array.
1730          */
1731         switch(parent->bref.type) {
1732         case HAMMER2_BREF_TYPE_INODE:
1733                 base = &parent->data->ipdata.u.blockset.blockref[0];
1734                 count = HAMMER2_SET_COUNT;
1735                 break;
1736         case HAMMER2_BREF_TYPE_INDIRECT:
1737         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1738         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1739                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1740                         base = NULL;
1741                 } else {
1742                         KKASSERT(parent->data != NULL);
1743                         base = &parent->data->npdata.blockref[0];
1744                 }
1745                 count = parent->bytes / sizeof(hammer2_blockref_t);
1746                 break;
1747         case HAMMER2_BREF_TYPE_VOLUME:
1748                 base = &hmp->voldata.sroot_blockset.blockref[0];
1749                 count = HAMMER2_SET_COUNT;
1750                 break;
1751         default:
1752                 panic("hammer2_chain_next: unrecognized blockref type: %d",
1753                       parent->bref.type);
1754                 base = NULL;    /* safety */
1755                 count = 0;      /* safety */
1756                 break;
1757         }
1758         KKASSERT(i <= count);
1759
1760         /*
1761          * Look for the key.  If we are unable to find a match and an exact
1762          * match was requested we return NULL.  If a range was requested we
1763          * run hammer2_chain_next() to iterate.
1764          *
1765          * NOTE! Deleted elements are effectively invisible.  Deletions
1766          *       proactively clear the parent bref to the deleted child
1767          *       so we do not try to shadow here to avoid parent updates
1768          *       (which would be difficult since multiple deleted elements
1769          *       might represent different flush synchronization points).
1770          */
1771         bref = NULL;
1772         while (i < count) {
1773                 tmp = hammer2_chain_find(parent, i);
1774                 if (tmp) {
1775                         if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1776                                 hammer2_chain_drop(tmp);
1777                                 ++i;
1778                                 continue;
1779                         }
1780                         bref = &tmp->bref;
1781                 } else if (base == NULL || base[i].type == 0) {
1782                         ++i;
1783                         continue;
1784                 } else {
1785                         bref = &base[i];
1786                 }
1787                 scan_beg = bref->key;
1788                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1789                 if (tmp)
1790                         hammer2_chain_drop(tmp);
1791                 if (key_beg <= scan_end && key_end >= scan_beg)
1792                         break;
1793                 ++i;
1794         }
1795
1796         /*
1797          * If we couldn't find a match recurse up a parent to continue the
1798          * search.
1799          */
1800         if (i == count)
1801                 goto again;
1802
1803         /*
1804          * Acquire the new chain element.  If the chain element is an
1805          * indirect block we must search recursively.
1806          */
1807         chain = hammer2_chain_get(parent, i, flags);
1808         if (chain == NULL)
1809                 return (NULL);
1810
1811         /*
1812          * If the chain element is an indirect block it becomes the new
1813          * parent and we loop on it.
1814          *
1815          * The parent always has to be locked with at least RESOLVE_MAYBE
1816          * so we can access its data.  It might need a fixup if the caller
1817          * passed incompatible flags.  Be careful not to cause a deadlock
1818          * as a data-load requires an exclusive lock.
1819          */
1820         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1821             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1822                 hammer2_chain_unlock(parent);
1823                 *parentp = parent = chain;
1824                 chain = NULL;
1825                 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1826                         hammer2_chain_lock(parent, how_maybe |
1827                                                    HAMMER2_RESOLVE_NOREF);
1828                 } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
1829                            parent->data == NULL) {
1830                         hammer2_chain_ref(parent);
1831                         hammer2_chain_unlock(parent);
1832                         hammer2_chain_lock(parent, how_maybe |
1833                                                    HAMMER2_RESOLVE_NOREF);
1834                 }
1835                 i = 0;
1836                 goto again2;
1837         }
1838
1839         /*
1840          * All done, return chain
1841          */
1842         return (chain);
1843 }
1844
1845 /*
1846  * Create and return a new hammer2 system memory structure of the specified
1847  * key, type and size and insert it under (*parentp).  This is a full
1848  * insertion, based on the supplied key/keybits, and may involve creating
1849  * indirect blocks and moving other chains around via delete/duplicate.
1850  *
1851  * (*parentp) must be exclusive locked and may be replaced on return
1852  * depending on how much work the function had to do.
1853  *
1854  * (*chainp) usually starts out NULL and returns the newly created chain,
1855  * but if the caller desires the caller may allocate a disconnected chain
1856  * and pass it in instead.  (It is also possible for the caller to use
1857  * chain_duplicate() to create a disconnected chain, manipulate it, then
1858  * pass it into this function to insert it).
1859  *
1860  * This function should NOT be used to insert INDIRECT blocks.  It is
1861  * typically used to create/insert inodes and data blocks.
1862  *
1863  * Caller must pass-in an exclusively locked parent the new chain is to
1864  * be inserted under, and optionally pass-in a disconnected, exclusively
1865  * locked chain to insert (else we create a new chain).  The function will
1866  * adjust (*parentp) as necessary and return the existing or new chain.
1867  */
1868 int
1869 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
1870                      hammer2_chain_t **chainp,
1871                      hammer2_key_t key, int keybits, int type, size_t bytes)
1872 {
1873         hammer2_mount_t *hmp;
1874         hammer2_chain_t *chain;
1875         hammer2_chain_t *child;
1876         hammer2_chain_t *parent = *parentp;
1877         hammer2_blockref_t dummy;
1878         hammer2_blockref_t *base;
1879         int allocated = 0;
1880         int error = 0;
1881         int count;
1882         int i;
1883
1884         KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
1885         hmp = parent->hmp;
1886         chain = *chainp;
1887
1888         if (chain == NULL) {
1889                 /*
1890                  * First allocate media space and construct the dummy bref,
1891                  * then allocate the in-memory chain structure.
1892                  */
1893                 bzero(&dummy, sizeof(dummy));
1894                 dummy.type = type;
1895                 dummy.key = key;
1896                 dummy.keybits = keybits;
1897                 dummy.data_off = hammer2_allocsize(bytes);
1898                 dummy.methods = parent->bref.methods;
1899                 chain = hammer2_chain_alloc(hmp, &dummy);
1900                 hammer2_chain_core_alloc(chain, NULL);
1901                 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
1902                 allocated = 1;
1903
1904                 /*
1905                  * We do NOT set INITIAL here (yet).  INITIAL is only
1906                  * used for indirect blocks.
1907                  *
1908                  * Recalculate bytes to reflect the actual media block
1909                  * allocation.
1910                  */
1911                 bytes = (hammer2_off_t)1 <<
1912                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
1913                 chain->bytes = bytes;
1914
1915                 switch(type) {
1916                 case HAMMER2_BREF_TYPE_VOLUME:
1917                         panic("hammer2_chain_create: called with volume type");
1918                         break;
1919                 case HAMMER2_BREF_TYPE_INODE:
1920                         KKASSERT(bytes == HAMMER2_INODE_BYTES);
1921                         chain->data = kmalloc(sizeof(chain->data->ipdata),
1922                                               hmp->minode, M_WAITOK | M_ZERO);
1923                         break;
1924                 case HAMMER2_BREF_TYPE_INDIRECT:
1925                         panic("hammer2_chain_create: cannot be used to"
1926                               "create indirect block");
1927                         break;
1928                 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1929                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1930                         panic("hammer2_chain_create: cannot be used to"
1931                               "create freemap root or node");
1932                         break;
1933                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1934                 case HAMMER2_BREF_TYPE_DATA:
1935                 default:
1936                         /* leave chain->data NULL */
1937                         KKASSERT(chain->data == NULL);
1938                         break;
1939                 }
1940         } else {
1941                 /*
1942                  * Potentially update the chain's key/keybits.
1943                  */
1944                 chain->bref.key = key;
1945                 chain->bref.keybits = keybits;
1946         }
1947
1948 again:
1949         /*
1950          * Locate a free blockref in the parent's array
1951          */
1952         switch(parent->bref.type) {
1953         case HAMMER2_BREF_TYPE_INODE:
1954                 KKASSERT((parent->data->ipdata.op_flags &
1955                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
1956                 KKASSERT(parent->data != NULL);
1957                 base = &parent->data->ipdata.u.blockset.blockref[0];
1958                 count = HAMMER2_SET_COUNT;
1959                 break;
1960         case HAMMER2_BREF_TYPE_INDIRECT:
1961         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
1962         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1963                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1964                         base = NULL;
1965                 } else {
1966                         KKASSERT(parent->data != NULL);
1967                         base = &parent->data->npdata.blockref[0];
1968                 }
1969                 count = parent->bytes / sizeof(hammer2_blockref_t);
1970                 break;
1971         case HAMMER2_BREF_TYPE_VOLUME:
1972                 KKASSERT(parent->data != NULL);
1973                 base = &hmp->voldata.sroot_blockset.blockref[0];
1974                 count = HAMMER2_SET_COUNT;
1975                 break;
1976         default:
1977                 panic("hammer2_chain_create: unrecognized blockref type: %d",
1978                       parent->bref.type);
1979                 count = 0;
1980                 break;
1981         }
1982
1983         /*
1984          * Scan for an unallocated bref, also skipping any slots occupied
1985          * by in-memory chain elements that may not yet have been updated
1986          * in the parent's bref array.
1987          *
1988          * We don't have to hold the spinlock to save an empty slot as
1989          * new slots can only transition from empty if the parent is
1990          * locked exclusively.
1991          */
1992
1993         spin_lock(&parent->core->cst.spin);
1994         for (i = 0; i < count; ++i) {
1995                 child = hammer2_chain_find_locked(parent, i);
1996                 if (child) {
1997                         if (child->flags & HAMMER2_CHAIN_DELETED)
1998                                 break;
1999                         continue;
2000                 }
2001                 if (base == NULL)
2002                         break;
2003                 if (base[i].type == 0)
2004                         break;
2005         }
2006         spin_unlock(&parent->core->cst.spin);
2007
2008         /*
2009          * If no free blockref could be found we must create an indirect
2010          * block and move a number of blockrefs into it.  With the parent
2011          * locked we can safely lock each child in order to move it without
2012          * causing a deadlock.
2013          *
2014          * This may return the new indirect block or the old parent depending
2015          * on where the key falls.  NULL is returned on error.
2016          */
2017         if (i == count) {
2018                 hammer2_chain_t *nparent;
2019
2020                 nparent = hammer2_chain_create_indirect(trans, parent,
2021                                                         key, keybits,
2022                                                         &error);
2023                 if (nparent == NULL) {
2024                         if (allocated)
2025                                 hammer2_chain_free(chain);
2026                         chain = NULL;
2027                         goto done;
2028                 }
2029                 if (parent != nparent) {
2030                         hammer2_chain_unlock(parent);
2031                         parent = *parentp = nparent;
2032                 }
2033                 goto again;
2034         }
2035
2036         /*
2037          * Link the chain into its parent.  Later on we will have to set
2038          * the MOVED bit in situations where we don't mark the new chain
2039          * as being modified.
2040          */
2041         if (chain->parent != NULL)
2042                 panic("hammer2: hammer2_chain_create: chain already connected");
2043         KKASSERT(chain->parent == NULL);
2044         KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2045
2046         chain->parent = parent;
2047         chain->index = i;
2048         KKASSERT(parent->refs > 0);
2049         spin_lock(&parent->core->cst.spin);
2050         if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, chain))
2051                 panic("hammer2_chain_link: collision");
2052         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2053         hammer2_chain_ref(parent);              /* chain->parent ref */
2054         spin_unlock(&parent->core->cst.spin);
2055
2056         /*
2057          * (allocated) indicates that this is a newly-created chain element
2058          * rather than a renamed chain element.
2059          *
2060          * In this situation we want to place the chain element in
2061          * the MODIFIED state.  The caller expects it to NOT be in the
2062          * INITIAL state.
2063          *
2064          * The data area will be set up as follows:
2065          *
2066          *      VOLUME          not allowed here.
2067          *
2068          *      INODE           embedded data are will be set-up.
2069          *
2070          *      INDIRECT        not allowed here.
2071          *
2072          *      DATA            no data area will be set-up (caller is expected
2073          *                      to have logical buffers, we don't want to alias
2074          *                      the data onto device buffers!).
2075          */
2076         if (allocated) {
2077                 switch(chain->bref.type) {
2078                 case HAMMER2_BREF_TYPE_DATA:
2079                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2080                         hammer2_chain_modify(trans, &chain,
2081                                              HAMMER2_MODIFY_OPTDATA |
2082                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2083                         break;
2084                 case HAMMER2_BREF_TYPE_INDIRECT:
2085                 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2086                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2087                         /* not supported in this function */
2088                         panic("hammer2_chain_create: bad type");
2089                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2090                         hammer2_chain_modify(trans, &chain,
2091                                              HAMMER2_MODIFY_OPTDATA |
2092                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2093                         break;
2094                 default:
2095                         hammer2_chain_modify(trans, &chain,
2096                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2097                         break;
2098                 }
2099         } else {
2100                 /*
2101                  * When reconnecting a chain we must set MOVED and setsubmod
2102                  * so the flush recognizes that it must update the bref in
2103                  * the parent.
2104                  */
2105                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2106                         hammer2_chain_ref(chain);
2107                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2108                 }
2109                 hammer2_chain_parent_setsubmod(trans, chain);
2110         }
2111
2112 done:
2113         *chainp = chain;
2114
2115         return (error);
2116 }
2117
2118 /*
2119  * Replace (*chainp) with a duplicate.  The original *chainp is unlocked
2120  * and the replacement will be returned locked.  Both the original and the
2121  * new chain will share the same RBTREE (have the same chain->core), with
2122  * the new chain becoming the 'current' chain (meaning it is the first in
2123  * the linked list at core->chain_first).
2124  *
2125  * If (parent, i) then the new duplicated chain is inserted under the parent
2126  * at the specified index (the parent must not have a ref at that index).
2127  *
2128  * If (NULL, -1) then the new duplicated chain is not inserted anywhere,
2129  * similar to if it had just been chain_alloc()'d (suitable for passing into
2130  * hammer2_chain_create() after this function returns).
2131  *
2132  * NOTE! Duplication is used in order to retain the original topology to
2133  *       support flush synchronization points.  Both the original and the
2134  *       new chain will have the same transaction id and thus the operation
2135  *       appears atomic on the media.
2136  */
2137 void
2138 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t *parent, int i,
2139                         hammer2_chain_t **chainp, hammer2_blockref_t *bref)
2140 {
2141         hammer2_mount_t *hmp = trans->hmp;
2142         hammer2_blockref_t *base;
2143         hammer2_chain_t *ochain;
2144         hammer2_chain_t *nchain;
2145         hammer2_chain_t *scan;
2146         size_t bytes;
2147         int count;
2148
2149         /*
2150          * First create a duplicate of the chain structure, associating
2151          * it with the same core, making it the same size, pointing it
2152          * to the same bref (the same media block), and copying any inline
2153          * data.
2154          */
2155         ochain = *chainp;
2156         if (bref == NULL)
2157                 bref = &ochain->bref;
2158         nchain = hammer2_chain_alloc(hmp, bref);
2159         hammer2_chain_core_alloc(nchain, ochain->core);
2160
2161         bytes = (hammer2_off_t)1 <<
2162                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2163         nchain->bytes = bytes;
2164
2165         /*
2166          * Be sure to copy the INITIAL flag as well or we could end up
2167          * loading garbage from the bref.
2168          */
2169         if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2170                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2171         if (ochain->flags & HAMMER2_CHAIN_DIRTYBP)
2172                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DIRTYBP);
2173
2174         /*
2175          * If the old chain is modified the new one must be too,
2176          * but we only want to allocate a new bref.
2177          */
2178         if (ochain->flags & HAMMER2_CHAIN_MODIFIED) {
2179                 /*
2180                  * When duplicating chains the MODIFIED state is inherited.
2181                  * A new bref typically must be allocated.  However, file
2182                  * data chains may already have the data offset assigned
2183                  * to a logical buffer cache buffer so we absolutely cannot
2184                  * allocate a new bref here for TYPE_DATA.
2185                  *
2186                  * Basically the flusher core only dumps media topology
2187                  * and meta-data, not file data.  The VOP_FSYNC code deals
2188                  * with the file data.  XXX need back-pointer to inode.
2189                  */
2190                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2191                         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MODIFIED);
2192                         hammer2_chain_ref(nchain);
2193                 } else {
2194                         hammer2_chain_modify(trans, &nchain,
2195                                              HAMMER2_MODIFY_OPTDATA |
2196                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2197                 }
2198         } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2199                 /*
2200                  * When duplicating chains in the INITITAL state we need
2201                  * to ensure that the chain is marked modified so a
2202                  * block is properly assigned to it, otherwise the MOVED
2203                  * bit won't do the right thing.
2204                  */
2205                 KKASSERT (nchain->bref.type != HAMMER2_BREF_TYPE_DATA);
2206                 hammer2_chain_modify(trans, &nchain,
2207                                      HAMMER2_MODIFY_OPTDATA |
2208                                      HAMMER2_MODIFY_ASSERTNOCOPY);
2209         }
2210         if (parent || (ochain->flags & HAMMER2_CHAIN_MOVED)) {
2211                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2212                 hammer2_chain_ref(nchain);
2213         }
2214         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2215
2216         switch(nchain->bref.type) {
2217         case HAMMER2_BREF_TYPE_VOLUME:
2218                 panic("hammer2_chain_duplicate: cannot be called w/volhdr");
2219                 break;
2220         case HAMMER2_BREF_TYPE_INODE:
2221                 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2222                 if (ochain->data) {
2223                         nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2224                                               hmp->minode, M_WAITOK | M_ZERO);
2225                         nchain->data->ipdata = ochain->data->ipdata;
2226                 }
2227                 break;
2228         case HAMMER2_BREF_TYPE_INDIRECT:
2229                 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2230                     nchain->data) {
2231                         bcopy(ochain->data, nchain->data,
2232                               nchain->bytes);
2233                 }
2234                 break;
2235         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2236         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2237                 panic("hammer2_chain_duplicate: cannot be used to"
2238                       "create a freemap root or node");
2239                 break;
2240         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2241         case HAMMER2_BREF_TYPE_DATA:
2242         default:
2243                 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2244                     nchain->data) {
2245                         bcopy(ochain->data, nchain->data,
2246                               nchain->bytes);
2247                 }
2248                 /* leave chain->data NULL */
2249                 KKASSERT(nchain->data == NULL);
2250                 break;
2251         }
2252
2253         /*
2254          * Both chains must be locked for us to be able to set the
2255          * duplink.  The caller may expect valid data.
2256          *
2257          * Unmodified duplicated blocks may have the same bref, we
2258          * must be careful to avoid buffer cache deadlocks so we
2259          * unlock the old chain before resolving the new one.
2260          *
2261          * Insert nchain at the end of the duplication list.
2262          */
2263         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2264         /* extra ref still present from original allocation */
2265
2266         spin_lock(&ochain->core->cst.spin);
2267         KKASSERT(nchain->duplink == NULL);
2268         nchain->duplink = ochain->duplink;
2269         ochain->duplink = nchain;       /* inherits excess ref from alloc */
2270         spin_unlock(&ochain->core->cst.spin);
2271
2272         hammer2_chain_unlock(ochain);
2273         *chainp = nchain;
2274         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2275         hammer2_chain_unlock(nchain);
2276
2277         /*
2278          * If parent is not NULL, insert into the parent at the requested
2279          * index.  The newly duplicated chain must be marked MOVED and
2280          * SUBMODIFIED set in its parent(s).
2281          */
2282         if (parent) {
2283                 /*
2284                  * Locate a free blockref in the parent's array
2285                  */
2286                 KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
2287                 switch(parent->bref.type) {
2288                 case HAMMER2_BREF_TYPE_INODE:
2289                         KKASSERT((parent->data->ipdata.op_flags &
2290                                   HAMMER2_OPFLAG_DIRECTDATA) == 0);
2291                         KKASSERT(parent->data != NULL);
2292                         base = &parent->data->ipdata.u.blockset.blockref[0];
2293                         count = HAMMER2_SET_COUNT;
2294                         break;
2295                 case HAMMER2_BREF_TYPE_INDIRECT:
2296                 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2297                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2298                         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2299                                 base = NULL;
2300                         } else {
2301                                 KKASSERT(parent->data != NULL);
2302                                 base = &parent->data->npdata.blockref[0];
2303                         }
2304                         count = parent->bytes / sizeof(hammer2_blockref_t);
2305                         break;
2306                 case HAMMER2_BREF_TYPE_VOLUME:
2307                         KKASSERT(parent->data != NULL);
2308                         base = &hmp->voldata.sroot_blockset.blockref[0];
2309                         count = HAMMER2_SET_COUNT;
2310                         break;
2311                 default:
2312                         panic("hammer2_chain_create: unrecognized "
2313                               "blockref type: %d",
2314                               parent->bref.type);
2315                         count = 0;
2316                         break;
2317                 }
2318                 KKASSERT(i >= 0 && i < count);
2319
2320                 nchain->parent = parent;
2321                 nchain->index = i;
2322                 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2323                 KKASSERT(parent->refs > 0);
2324
2325                 spin_lock(&parent->core->cst.spin);
2326                 scan = hammer2_chain_find_locked(parent, i);
2327                 KKASSERT(base == NULL || base[i].type == 0 ||
2328                          scan == NULL ||
2329                          (scan->flags & HAMMER2_CHAIN_DELETED));
2330                 if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree,
2331                               nchain)) {
2332                         panic("hammer2_chain_link: collision");
2333                 }
2334                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
2335                 hammer2_chain_ref(parent);      /* nchain->parent ref */
2336                 spin_unlock(&parent->core->cst.spin);
2337
2338                 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2339                         hammer2_chain_ref(nchain);
2340                         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2341                 }
2342                 hammer2_chain_parent_setsubmod(trans, nchain);
2343         }
2344 }
2345
2346 /*
2347  * Special in-place delete-duplicate sequence which does not require a
2348  * locked parent.  (*chainp) is marked DELETED and atomically replaced
2349  * with a duplicate.  Atomicy is at the very-fine spin-lock level in
2350  * order to ensure that lookups do not race us.
2351  */
2352 void
2353 hammer2_chain_delete_duplicate(hammer2_trans_t *trans,
2354                                hammer2_chain_t **chainp)
2355 {
2356         hammer2_mount_t *hmp = trans->hmp;
2357         hammer2_chain_t *ochain;
2358         hammer2_chain_t *nchain;
2359         hammer2_chain_t *parent;
2360         size_t bytes;
2361
2362         /*
2363          * First create a duplicate of the chain structure, associating
2364          * it with the same core, making it the same size, pointing it
2365          * to the same bref (the same media block), and copying any inline
2366          * data.
2367          */
2368         ochain = *chainp;
2369         nchain = hammer2_chain_alloc(hmp, &ochain->bref);    /* 1 ref */
2370         hammer2_chain_core_alloc(nchain, ochain->core);
2371
2372         kprintf("delete_duplicate %p.%d(%d)\n", ochain, ochain->bref.type, ochain->refs);
2373
2374         bytes = (hammer2_off_t)1 <<
2375                 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2376         nchain->bytes = bytes;
2377
2378         /*
2379          * Be sure to copy the INITIAL flag as well or we could end up
2380          * loading garbage from the bref.
2381          */
2382         if (ochain->flags & HAMMER2_CHAIN_INITIAL)
2383                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2384         if (ochain->flags & HAMMER2_CHAIN_DIRTYBP)
2385                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DIRTYBP);
2386
2387         /*
2388          * If the old chain is modified the new one must be too,
2389          * but we only want to allocate a new bref.
2390          */
2391         if (ochain->flags & HAMMER2_CHAIN_MODIFIED) {
2392                 /*
2393                  * When duplicating chains the MODIFIED state is inherited.
2394                  * A new bref typically must be allocated.  However, file
2395                  * data chains may already have the data offset assigned
2396                  * to a logical buffer cache buffer so we absolutely cannot
2397                  * allocate a new bref here for TYPE_DATA.
2398                  *
2399                  * Basically the flusher core only dumps media topology
2400                  * and meta-data, not file data.  The VOP_FSYNC code deals
2401                  * with the file data.  XXX need back-pointer to inode.
2402                  */
2403                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2404                         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MODIFIED);
2405                         hammer2_chain_ref(nchain);
2406                 } else {
2407                         hammer2_chain_modify(trans, &nchain,
2408                                              HAMMER2_MODIFY_OPTDATA |
2409                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2410                 }
2411         } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2412                 /*
2413                  * When duplicating chains in the INITITAL state we need
2414                  * to ensure that the chain is marked modified so a
2415                  * block is properly assigned to it, otherwise the MOVED
2416                  * bit won't do the right thing.
2417                  */
2418                 KKASSERT (nchain->bref.type != HAMMER2_BREF_TYPE_DATA);
2419                 hammer2_chain_modify(trans, &nchain,
2420                                      HAMMER2_MODIFY_OPTDATA |
2421                                      HAMMER2_MODIFY_ASSERTNOCOPY);
2422         }
2423
2424         /*
2425          * Unconditionally set the MOVED and SUBMODIFIED bit to force
2426          * update of parent bref and indirect blockrefs during flush.
2427          */
2428         if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2429                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2430                 hammer2_chain_ref(nchain);
2431         }
2432         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2433
2434         /*
2435          * Copy media contents as needed.
2436          */
2437         switch(nchain->bref.type) {
2438         case HAMMER2_BREF_TYPE_VOLUME:
2439                 panic("hammer2_chain_duplicate: cannot be called w/volhdr");
2440                 break;
2441         case HAMMER2_BREF_TYPE_INODE:
2442                 KKASSERT(bytes == HAMMER2_INODE_BYTES);
2443                 if (ochain->data) {
2444                         nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2445                                               hmp->minode, M_WAITOK | M_ZERO);
2446                         nchain->data->ipdata = ochain->data->ipdata;
2447                 }
2448                 break;
2449         case HAMMER2_BREF_TYPE_INDIRECT:
2450                 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2451                     nchain->data) {
2452                         bcopy(ochain->data, nchain->data,
2453                               nchain->bytes);
2454                 }
2455                 break;
2456         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2457         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2458                 panic("hammer2_chain_duplicate: cannot be used to"
2459                       "create a freemap root or node");
2460                 break;
2461         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2462         case HAMMER2_BREF_TYPE_DATA:
2463         default:
2464                 if ((nchain->flags & HAMMER2_CHAIN_MODIFIED) &&
2465                     nchain->data) {
2466                         bcopy(ochain->data, nchain->data,
2467                               nchain->bytes);
2468                 }
2469                 /* leave chain->data NULL */
2470                 KKASSERT(nchain->data == NULL);
2471                 break;
2472         }
2473
2474         /*
2475          * Both chains must be locked for us to be able to set the
2476          * duplink.  The caller may expect valid data.
2477          *
2478          * Unmodified duplicated blocks may have the same bref, we
2479          * must be careful to avoid buffer cache deadlocks so we
2480          * unlock the old chain before resolving the new one.
2481          *
2482          * Insert nchain at the end of the duplication list.
2483          */
2484         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2485         /* extra ref still present from original allocation */
2486
2487         parent = ochain->parent;
2488         nchain->parent = parent;
2489         nchain->index = ochain->index;
2490         hammer2_chain_ref(parent);      /* nchain->parent ref */
2491
2492         kprintf("duplicate ochain %p(%d) nchain %p(%d) %08x\n",
2493                 ochain, ochain->refs, nchain, nchain->refs, nchain->flags);
2494
2495         spin_lock(&ochain->core->cst.spin);
2496         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
2497         ochain->delete_tid = trans->sync_tid;
2498         atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2499         if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2500                 hammer2_chain_ref(ochain);
2501                 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2502         }
2503         if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, nchain)) {
2504                 panic("hammer2_chain_link: collision");
2505         }
2506         KKASSERT(nchain->duplink == NULL);
2507         nchain->duplink = ochain->duplink;
2508         ochain->duplink = nchain;       /* inherits excess ref from alloc */
2509         spin_unlock(&ochain->core->cst.spin);
2510
2511         /*
2512          * Cleanup.  Also note that nchain must be re-resolved to ensure
2513          * that it's data is resolved because we locked it RESOLVE_NEVER
2514          * up above.
2515          */
2516         *chainp = nchain;               /* inherits locked */
2517         hammer2_chain_unlock(ochain);   /* replacing ochain */
2518         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2519         hammer2_chain_unlock(nchain);
2520
2521         hammer2_chain_parent_setsubmod(trans, nchain);
2522 }
2523
2524 /*
2525  * Create a snapshot of the specified {parent, chain} with the specified
2526  * label.
2527  *
2528  * (a) We create a duplicate connected to the super-root as the specified
2529  *     label.
2530  *
2531  * (b) We issue a restricted flush using the current transaction on the
2532  *     duplicate.
2533  *
2534  * (c) We disconnect and reallocate the duplicate's core.
2535  */
2536 int
2537 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_inode_t *ip,
2538                        hammer2_ioc_pfs_t *pfs)
2539 {
2540         hammer2_mount_t *hmp = trans->hmp;
2541         hammer2_chain_t *chain;
2542         hammer2_chain_t *nchain;
2543         hammer2_chain_t *parent;
2544         hammer2_inode_data_t *ipdata;
2545         size_t name_len = strlen(pfs->name);
2546         hammer2_key_t lhc = hammer2_dirhash(pfs->name, name_len);
2547         int error;
2548
2549         /*
2550          * Create disconnected duplicate
2551          */
2552         KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2553         nchain = ip->chain;
2554         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2555         hammer2_chain_duplicate(trans, NULL, -1, &nchain, NULL);
2556         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_RECYCLE);
2557
2558         /*
2559          * Create named entry in the super-root.
2560          */
2561         parent = hammer2_chain_lookup_init(hmp->schain, 0);
2562         error = 0;
2563         while (error == 0) {
2564                 chain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
2565                 if (chain == NULL)
2566                         break;
2567                 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
2568                         error = ENOSPC;
2569                 hammer2_chain_unlock(chain);
2570                 chain = NULL;
2571                 ++lhc;
2572         }
2573         hammer2_chain_create(trans, &parent, &nchain, lhc, 0,
2574                              HAMMER2_BREF_TYPE_INODE,
2575                              HAMMER2_INODE_BYTES);
2576         hammer2_chain_modify(trans, &nchain, HAMMER2_MODIFY_ASSERTNOCOPY);
2577         hammer2_chain_lookup_done(parent);
2578         parent = NULL;  /* safety */
2579
2580         /*
2581          * Name fixup
2582          */
2583         ipdata = &nchain->data->ipdata;
2584         ipdata->name_key = lhc;
2585         ipdata->name_len = name_len;
2586         ksnprintf(ipdata->filename, sizeof(ipdata->filename), "%s", pfs->name);
2587
2588         /*
2589          * Set PFS type, generate a unique filesystem id, and generate
2590          * a cluster id.  Use the same clid when snapshotting a PFS root,
2591          * which theoretically allows the snapshot to be used as part of
2592          * the same cluster (perhaps as a cache).
2593          */
2594         ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2595         kern_uuidgen(&ipdata->pfs_fsid, 1);
2596         if (ip->chain == ip->pmp->rchain)
2597                 ipdata->pfs_clid = ip->chain->data->ipdata.pfs_clid;
2598         else
2599                 kern_uuidgen(&ipdata->pfs_clid, 1);
2600
2601         /*
2602          * Issue a restricted flush of the snapshot.  This is a synchronous
2603          * operation.
2604          */
2605         trans->flags |= HAMMER2_TRANS_RESTRICTED;
2606         kprintf("SNAPSHOTA\n");
2607         tsleep(trans, 0, "snapslp", hz*4);
2608         kprintf("SNAPSHOTB\n");
2609         hammer2_chain_flush(trans, nchain);
2610         trans->flags &= ~HAMMER2_TRANS_RESTRICTED;
2611
2612         /*
2613          * Remove the duplication
2614          */
2615         chain = ip->chain;
2616         KKASSERT(chain->duplink == nchain);
2617         KKASSERT(chain->core == nchain->core);
2618         KKASSERT(nchain->refs >= 2);
2619         chain->duplink = nchain->duplink;
2620         hammer2_chain_drop(nchain);
2621
2622         kprintf("snapshot %s nchain->refs %d nchain->flags %08x\n",
2623                 pfs->name, nchain->refs, nchain->flags);
2624         hammer2_chain_unlock(nchain);
2625
2626         return (error);
2627 }
2628
2629 /*
2630  * Create an indirect block that covers one or more of the elements in the
2631  * current parent.  Either returns the existing parent with no locking or
2632  * ref changes or returns the new indirect block locked and referenced
2633  * and leaving the original parent lock/ref intact as well.
2634  *
2635  * If an error occurs, NULL is returned and *errorp is set to the error.
2636  *
2637  * The returned chain depends on where the specified key falls.
2638  *
2639  * The key/keybits for the indirect mode only needs to follow three rules:
2640  *
2641  * (1) That all elements underneath it fit within its key space and
2642  *
2643  * (2) That all elements outside it are outside its key space.
2644  *
2645  * (3) When creating the new indirect block any elements in the current
2646  *     parent that fit within the new indirect block's keyspace must be
2647  *     moved into the new indirect block.
2648  *
2649  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2650  *     keyspace the the current parent, but lookup/iteration rules will
2651  *     ensure (and must ensure) that rule (2) for all parents leading up
2652  *     to the nearest inode or the root volume header is adhered to.  This
2653  *     is accomplished by always recursing through matching keyspaces in
2654  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
2655  *
2656  * The current implementation calculates the current worst-case keyspace by
2657  * iterating the current parent and then divides it into two halves, choosing
2658  * whichever half has the most elements (not necessarily the half containing
2659  * the requested key).
2660  *
2661  * We can also opt to use the half with the least number of elements.  This
2662  * causes lower-numbered keys (aka logical file offsets) to recurse through
2663  * fewer indirect blocks and higher-numbered keys to recurse through more.
2664  * This also has the risk of not moving enough elements to the new indirect
2665  * block and being forced to create several indirect blocks before the element
2666  * can be inserted.
2667  *
2668  * Must be called with an exclusively locked parent.
2669  */
2670 static
2671 hammer2_chain_t *
2672 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2673                               hammer2_key_t create_key, int create_bits,
2674                               int *errorp)
2675 {
2676         hammer2_mount_t *hmp = trans->hmp;
2677         hammer2_blockref_t *base;
2678         hammer2_blockref_t *bref;
2679         hammer2_chain_t *chain;
2680         hammer2_chain_t *child;
2681         hammer2_chain_t *ichain;
2682         hammer2_chain_t dummy;
2683         hammer2_key_t key = create_key;
2684         int keybits = create_bits;
2685         int locount = 0;
2686         int hicount = 0;
2687         int count;
2688         int nbytes;
2689         int i;
2690
2691         /*
2692          * Calculate the base blockref pointer or NULL if the chain
2693          * is known to be empty.  We need to calculate the array count
2694          * for RB lookups either way.
2695          */
2696         KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
2697         *errorp = 0;
2698
2699         /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2700         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2701                 base = NULL;
2702
2703                 switch(parent->bref.type) {
2704                 case HAMMER2_BREF_TYPE_INODE:
2705                         count = HAMMER2_SET_COUNT;
2706                         break;
2707                 case HAMMER2_BREF_TYPE_INDIRECT:
2708                 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2709                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2710                         count = parent->bytes / sizeof(hammer2_blockref_t);
2711                         break;
2712                 case HAMMER2_BREF_TYPE_VOLUME:
2713                         count = HAMMER2_SET_COUNT;
2714                         break;
2715                 default:
2716                         panic("hammer2_chain_create_indirect: "
2717                               "unrecognized blockref type: %d",
2718                               parent->bref.type);
2719                         count = 0;
2720                         break;
2721                 }
2722         } else {
2723                 switch(parent->bref.type) {
2724                 case HAMMER2_BREF_TYPE_INODE:
2725                         base = &parent->data->ipdata.u.blockset.blockref[0];
2726                         count = HAMMER2_SET_COUNT;
2727                         break;
2728                 case HAMMER2_BREF_TYPE_INDIRECT:
2729                 case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2730                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2731                         base = &parent->data->npdata.blockref[0];
2732                         count = parent->bytes / sizeof(hammer2_blockref_t);
2733                         break;
2734                 case HAMMER2_BREF_TYPE_VOLUME:
2735                         base = &hmp->voldata.sroot_blockset.blockref[0];
2736                         count = HAMMER2_SET_COUNT;
2737                         break;
2738                 default:
2739                         panic("hammer2_chain_create_indirect: "
2740                               "unrecognized blockref type: %d",
2741                               parent->bref.type);
2742                         count = 0;
2743                         break;
2744                 }
2745         }
2746
2747         /*
2748          * Scan for an unallocated bref, also skipping any slots occupied
2749          * by in-memory chain elements which may not yet have been updated
2750          * in the parent's bref array.
2751          *
2752          * Deleted elements are ignored.
2753          */
2754         bzero(&dummy, sizeof(dummy));
2755         dummy.delete_tid = HAMMER2_MAX_TID;
2756
2757         spin_lock(&parent->core->cst.spin);
2758         for (i = 0; i < count; ++i) {
2759                 int nkeybits;
2760
2761                 child = hammer2_chain_find_locked(parent, i);
2762                 if (child) {
2763                         if (child->flags & HAMMER2_CHAIN_DELETED)
2764                                 continue;
2765                         bref = &child->bref;
2766                 } else if (base && base[i].type) {
2767                         bref = &base[i];
2768                 } else {
2769                         continue;
2770                 }
2771
2772                 /*
2773                  * Expand our calculated key range (key, keybits) to fit
2774                  * the scanned key.  nkeybits represents the full range
2775                  * that we will later cut in half (two halves @ nkeybits - 1).
2776                  */
2777                 nkeybits = keybits;
2778                 if (nkeybits < bref->keybits) {
2779                         if (bref->keybits > 64) {
2780                                 kprintf("bad bref index %d chain %p bref %p\n", i, chain, bref);
2781                                 Debugger("fubar");
2782                         }
2783                         nkeybits = bref->keybits;
2784                 }
2785                 while (nkeybits < 64 &&
2786                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
2787                         (key ^ bref->key)) != 0) {
2788                         ++nkeybits;
2789                 }
2790
2791                 /*
2792                  * If the new key range is larger we have to determine
2793                  * which side of the new key range the existing keys fall
2794                  * under by checking the high bit, then collapsing the
2795                  * locount into the hicount or vise-versa.
2796                  */
2797                 if (keybits != nkeybits) {
2798                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
2799                                 hicount += locount;
2800                                 locount = 0;
2801                         } else {
2802                                 locount += hicount;
2803                                 hicount = 0;
2804                         }
2805                         keybits = nkeybits;
2806                 }
2807
2808                 /*
2809                  * The newly scanned key will be in the lower half or the
2810                  * higher half of the (new) key range.
2811                  */
2812                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
2813                         ++hicount;
2814                 else
2815                         ++locount;
2816         }
2817         spin_unlock(&parent->core->cst.spin);
2818         bref = NULL;    /* now invalid (safety) */
2819
2820         /*
2821          * Adjust keybits to represent half of the full range calculated
2822          * above (radix 63 max)
2823          */
2824         --keybits;
2825
2826         /*
2827          * Select whichever half contains the most elements.  Theoretically
2828          * we can select either side as long as it contains at least one
2829          * element (in order to ensure that a free slot is present to hold
2830          * the indirect block).
2831          */
2832         key &= ~(((hammer2_key_t)1 << keybits) - 1);
2833         if (hammer2_indirect_optimize) {
2834                 /*
2835                  * Insert node for least number of keys, this will arrange
2836                  * the first few blocks of a large file or the first few
2837                  * inodes in a directory with fewer indirect blocks when
2838                  * created linearly.
2839                  */
2840                 if (hicount < locount && hicount != 0)
2841                         key |= (hammer2_key_t)1 << keybits;
2842                 else
2843                         key &= ~(hammer2_key_t)1 << keybits;
2844         } else {
2845                 /*
2846                  * Insert node for most number of keys, best for heavily
2847                  * fragmented files.
2848                  */
2849                 if (hicount > locount)
2850                         key |= (hammer2_key_t)1 << keybits;
2851                 else
2852                         key &= ~(hammer2_key_t)1 << keybits;
2853         }
2854
2855         /*
2856          * How big should our new indirect block be?  It has to be at least
2857          * as large as its parent.
2858          */
2859         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2860                 nbytes = HAMMER2_IND_BYTES_MIN;
2861         else
2862                 nbytes = HAMMER2_IND_BYTES_MAX;
2863         if (nbytes < count * sizeof(hammer2_blockref_t))
2864                 nbytes = count * sizeof(hammer2_blockref_t);
2865
2866         /*
2867          * Ok, create our new indirect block
2868          */
2869         switch(parent->bref.type) {
2870         case HAMMER2_BREF_TYPE_FREEMAP_ROOT:
2871         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2872                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2873                 break;
2874         default:
2875                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2876                 break;
2877         }
2878         dummy.bref.key = key;
2879         dummy.bref.keybits = keybits;
2880         dummy.bref.data_off = hammer2_allocsize(nbytes);
2881         dummy.bref.methods = parent->bref.methods;
2882
2883         ichain = hammer2_chain_alloc(hmp, &dummy.bref);
2884         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2885         hammer2_chain_core_alloc(ichain, NULL);
2886         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2887         hammer2_chain_drop(ichain);     /* excess ref from alloc */
2888
2889         /*
2890          * We have to mark it modified to allocate its block, but use
2891          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
2892          * it won't be acted upon by the flush code.
2893          */
2894         hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
2895
2896         /*
2897          * Iterate the original parent and move the matching brefs into
2898          * the new indirect block.
2899          *
2900          * XXX handle flushes.
2901          */
2902         spin_lock(&parent->core->cst.spin);
2903         for (i = 0; i < count; ++i) {
2904                 /*
2905                  * For keying purposes access the bref from the media or
2906                  * from our in-memory cache.  In cases where the in-memory
2907                  * cache overrides the media the keyrefs will be the same
2908                  * anyway so we can avoid checking the cache when the media
2909                  * has a key.
2910                  */
2911                 child = hammer2_chain_find_locked(parent, i);
2912                 if (child) {
2913                         if (child->flags & HAMMER2_CHAIN_DELETED) {
2914                                 if (ichain->index < 0)
2915                                         ichain->index = i;
2916                                 continue;
2917                         }
2918                         bref = &child->bref;
2919                 } else if (base && base[i].type) {
2920                         bref = &base[i];
2921                 } else {
2922                         if (ichain->index < 0)
2923                                 ichain->index = i;
2924                         continue;
2925                 }
2926
2927                 /*
2928                  * Skip keys not in the chosen half (low or high), only bit
2929                  * (keybits - 1) needs to be compared but for safety we
2930                  * will compare all msb bits plus that bit again.
2931                  */
2932                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2933                     (key ^ bref->key)) != 0) {
2934                         continue;
2935                 }
2936
2937                 /*
2938                  * This element is being moved from the parent, its slot
2939                  * is available for our new indirect block.
2940                  */
2941                 if (ichain->index < 0)
2942                         ichain->index = i;
2943
2944                 /*
2945                  * Load the new indirect block by acquiring or allocating
2946                  * the related chain entries, then move them to the new
2947                  * parent (ichain) by deleting them from their old location
2948                  * and inserting a duplicate of the chain and any modified
2949                  * sub-chain in the new location.
2950                  *
2951                  * We must set MOVED in the chain being duplicated and
2952                  * SUBMODIFIED in the parent(s) so the flush code knows
2953                  * what is going on.  The latter is done after the loop.
2954                  *
2955                  * WARNING! chain->cst.spin must be held when chain->parent is
2956                  *          modified, even though we own the full blown lock,
2957                  *          to deal with setsubmod and rename races.
2958                  *          (XXX remove this req).
2959                  */
2960                 spin_unlock(&parent->core->cst.spin);
2961                 chain = hammer2_chain_get(parent, i, HAMMER2_LOOKUP_NODATA);
2962                 hammer2_chain_delete(trans, parent, chain);
2963                 hammer2_chain_duplicate(trans, ichain, i, &chain, NULL);
2964
2965                 hammer2_chain_unlock(chain);
2966                 KKASSERT(parent->refs > 0);
2967                 chain = NULL;
2968                 spin_lock(&parent->core->cst.spin);
2969         }
2970         spin_unlock(&parent->core->cst.spin);
2971
2972         /*
2973          * Insert the new indirect block into the parent now that we've
2974          * cleared out some entries in the parent.  We calculated a good
2975          * insertion index in the loop above (ichain->index).
2976          *
2977          * We don't have to set MOVED here because we mark ichain modified
2978          * down below (so the normal modified -> flush -> set-moved sequence
2979          * applies).
2980          *
2981          * The insertion shouldn't race as this is a completely new block
2982          * and the parent is locked.
2983          */
2984         if (ichain->index < 0)
2985                 kprintf("indirect parent %p count %d key %016jx/%d\n",
2986                         parent, count, (intmax_t)key, keybits);
2987         KKASSERT(ichain->index >= 0);
2988         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2989         spin_lock(&parent->core->cst.spin);
2990         if (RB_INSERT(hammer2_chain_tree, &parent->core->rbtree, ichain))
2991                 panic("hammer2_chain_create_indirect: ichain insertion");
2992         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_ONRBTREE);
2993         ichain->parent = parent;
2994         hammer2_chain_ref(parent);      /* ichain->parent ref */
2995         spin_unlock(&parent->core->cst.spin);
2996         KKASSERT(parent->duplink == NULL); /* XXX mus be inside spin */
2997
2998         /*
2999          * Mark the new indirect block modified after insertion, which
3000          * will propagate up through parent all the way to the root and
3001          * also allocate the physical block in ichain for our caller,
3002          * and assign ichain->data to a pre-zero'd space (because there
3003          * is not prior data to copy into it).
3004          *
3005          * We have to set SUBMODIFIED in ichain's flags manually so the
3006          * flusher knows it has to recurse through it to get to all of
3007          * our moved blocks, then call setsubmod() to set the bit
3008          * recursively.
3009          */
3010         /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3011         hammer2_chain_parent_setsubmod(trans, ichain);
3012         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_SUBMODIFIED);
3013
3014         /*
3015          * Figure out what to return.
3016          */
3017         if (create_bits > keybits) {
3018                 /*
3019                  * Key being created is way outside the key range,
3020                  * return the original parent.
3021                  */
3022                 hammer2_chain_unlock(ichain);
3023         } else if (~(((hammer2_key_t)1 << keybits) - 1) &
3024                    (create_key ^ key)) {
3025                 /*
3026                  * Key being created is outside the key range,
3027                  * return the original parent.
3028                  */
3029                 hammer2_chain_unlock(ichain);
3030         } else {
3031                 /*
3032                  * Otherwise its in the range, return the new parent.
3033                  * (leave both the new and old parent locked).
3034                  */
3035                 parent = ichain;
3036         }
3037
3038         return(parent);
3039 }
3040
3041 /*
3042  * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3043  * set chain->delete_tid.
3044  *
3045  * This function does NOT generate a modification to the parent.  It
3046  * would be nearly impossible to figure out which parent to modify anyway.
3047  * Such modifications are handled by the flush code and are properly merged
3048  * using the flush synchronization point.
3049  *
3050  * The find/get code will properly overload the RBTREE check on top of
3051  * the bref check to detect deleted entries.
3052  *
3053  * This function is NOT recursive.  Any entity already pushed into the
3054  * chain (such as an inode) may still need visibility into its contents,
3055  * as well as the ability to read and modify the contents.  For example,
3056  * for an unlinked file which is still open.
3057  *
3058  * NOTE: This function does NOT set chain->modify_tid, allowing future
3059  *       code to distinguish between live and deleted chains by testing
3060  *       sync_tid.
3061  *
3062  * NOTE: Deletions normally do not occur in the middle of a duplication
3063  *       chain but we use a trick for hardlink migration that refactors
3064  *       the originating inode without deleting it, so we make no assumptions
3065  *       here.
3066  */
3067 void
3068 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3069                      hammer2_chain_t *chain)
3070 {
3071         KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3072
3073         /*
3074          * Nothing to do if already marked.
3075          */
3076         if (chain->flags & HAMMER2_CHAIN_DELETED)
3077                 return;
3078
3079         /*
3080          * We must set MOVED along with DELETED for the flush code to
3081          * recognize the operation and properly disconnect the chain
3082          * in-memory.
3083          *
3084          * The setting of DELETED causes finds, lookups, and _next iterations
3085          * to no longer recognize the chain.  RB_SCAN()s will still have
3086          * visibility (needed for flush serialization points).
3087          */
3088         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3089         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3090                 hammer2_chain_ref(chain);
3091                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3092         }
3093         chain->delete_tid = trans->sync_tid;
3094         hammer2_chain_parent_setsubmod(trans, chain);
3095 }
3096
3097 void
3098 hammer2_chain_wait(hammer2_chain_t *chain)
3099 {
3100         tsleep(chain, 0, "chnflw", 1);
3101 }