hammer2 - Add missing bqrelse()
[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 for_type, int *errorp);
75 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
76
77 /*
78  * We use a red-black tree to guarantee safe lookups under shared locks.
79  *
80  * Chains can be overloaded onto the same index, creating a different
81  * view of a blockref table based on a transaction id.  The RBTREE
82  * deconflicts the view by sub-sorting on delete_tid.
83  *
84  * NOTE: Any 'current' chain which is not yet deleted will have a
85  *       delete_tid of HAMMER2_MAX_TID (0xFFF....FFFLLU).
86  */
87 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
88
89 int
90 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
91 {
92         if (chain1->index < chain2->index)
93                 return(-1);
94         if (chain1->index > chain2->index)
95                 return(1);
96         if (chain1->delete_tid < chain2->delete_tid)
97                 return(-1);
98         if (chain1->delete_tid > chain2->delete_tid)
99                 return(1);
100         return(0);
101 }
102
103 static __inline
104 int
105 hammer2_isclusterable(hammer2_chain_t *chain)
106 {
107         if (hammer2_cluster_enable) {
108                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
109                     chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
110                     chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
111                         return(1);
112                 }
113         }
114         return(0);
115 }
116
117 /*
118  * Recursively set the SUBMODIFIED flag up to the root starting at chain's
119  * parent.  SUBMODIFIED is not set in chain itself.
120  *
121  * This function only operates on current-time transactions and is not
122  * used during flushes.  Instead, the flush code manages the flag itself.
123  */
124 void
125 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
126 {
127         hammer2_chain_core_t *above;
128
129         if (trans->flags & HAMMER2_TRANS_ISFLUSH)
130                 return;
131         while ((above = chain->above) != NULL) {
132                 spin_lock(&above->cst.spin);
133                 chain = above->first_parent;
134                 while (hammer2_chain_refactor_test(chain, 1))
135                         chain = chain->next_parent;
136                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_SUBMODIFIED);
137                 spin_unlock(&above->cst.spin);
138         }
139 }
140
141 /*
142  * Allocate a new disconnected chain element representing the specified
143  * bref.  chain->refs is set to 1 and the passed bref is copied to
144  * chain->bref.  chain->bytes is derived from the bref.
145  *
146  * chain->core is NOT allocated and the media data and bp pointers are left
147  * NULL.  The caller must call chain_core_alloc() to allocate or associate
148  * a core with the chain.
149  *
150  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
151  */
152 hammer2_chain_t *
153 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_trans_t *trans,
154                     hammer2_blockref_t *bref)
155 {
156         hammer2_chain_t *chain;
157         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
158
159         /*
160          * Construct the appropriate system structure.
161          */
162         switch(bref->type) {
163         case HAMMER2_BREF_TYPE_INODE:
164         case HAMMER2_BREF_TYPE_INDIRECT:
165         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
166         case HAMMER2_BREF_TYPE_DATA:
167         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
168                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
169                 break;
170         case HAMMER2_BREF_TYPE_VOLUME:
171         case HAMMER2_BREF_TYPE_FREEMAP:
172                 chain = NULL;
173                 panic("hammer2_chain_alloc volume type illegal for op");
174         default:
175                 chain = NULL;
176                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
177                       bref->type);
178         }
179
180         chain->hmp = hmp;
181         chain->bref = *bref;
182         chain->index = -1;              /* not yet assigned */
183         chain->bytes = bytes;
184         chain->refs = 1;
185         chain->flags = HAMMER2_CHAIN_ALLOCATED;
186         chain->delete_tid = HAMMER2_MAX_TID;
187         if (trans)
188                 chain->modify_tid = trans->sync_tid;
189
190         return (chain);
191 }
192
193 /*
194  * Associate an existing core with the chain or allocate a new core.
195  *
196  * The core is not locked.  No additional refs on the chain are made.
197  */
198 void
199 hammer2_chain_core_alloc(hammer2_chain_t *chain, hammer2_chain_core_t *core)
200 {
201         hammer2_chain_t **scanp;
202
203         KKASSERT(chain->core == NULL);
204         KKASSERT(chain->next_parent == NULL);
205
206         if (core == NULL) {
207                 core = kmalloc(sizeof(*core), chain->hmp->mchain,
208                                M_WAITOK | M_ZERO);
209                 RB_INIT(&core->rbtree);
210                 core->sharecnt = 1;
211                 chain->core = core;
212                 ccms_cst_init(&core->cst, chain);
213                 core->first_parent = chain;
214         } else {
215                 atomic_add_int(&core->sharecnt, 1);
216                 chain->core = core;
217                 spin_lock(&core->cst.spin);
218                 if (core->first_parent == NULL) {
219                         core->first_parent = chain;
220                 } else {
221                         scanp = &core->first_parent;
222                         while (*scanp)
223                                 scanp = &(*scanp)->next_parent;
224                         *scanp = chain;
225                         hammer2_chain_ref(chain);       /* next_parent link */
226                 }
227                 spin_unlock(&core->cst.spin);
228         }
229 }
230
231 /*
232  * Add a reference to a chain element, preventing its destruction.
233  */
234 void
235 hammer2_chain_ref(hammer2_chain_t *chain)
236 {
237         atomic_add_int(&chain->refs, 1);
238 }
239
240 /*
241  * Drop the caller's reference to the chain.  When the ref count drops to
242  * zero this function will disassociate the chain from its parent and
243  * deallocate it, then recursely drop the parent using the implied ref
244  * from the chain's chain->parent.
245  *
246  * WARNING! Just because we are able to deallocate a chain doesn't mean
247  *          that chain->core->rbtree is empty.  There can still be a sharecnt
248  *          on chain->core and RBTREE entries that refer to different parents.
249  */
250 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
251
252 void
253 hammer2_chain_drop(hammer2_chain_t *chain)
254 {
255         u_int refs;
256         u_int need = 0;
257
258 #if 1
259         if (chain->flags & HAMMER2_CHAIN_MOVED)
260                 ++need;
261         if (chain->flags & HAMMER2_CHAIN_MODIFIED)
262                 ++need;
263         KKASSERT(chain->refs > need);
264 #endif
265
266         while (chain) {
267                 refs = chain->refs;
268                 cpu_ccfence();
269                 KKASSERT(refs > 0);
270
271                 if (refs == 1) {
272                         chain = hammer2_chain_lastdrop(chain);
273                 } else {
274                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
275                                 break;
276                         /* retry the same chain */
277                 }
278         }
279 }
280
281 /*
282  * Safe handling of the 1->0 transition on chain.  Returns a chain for
283  * recursive drop or NULL, possibly returning the same chain of the atomic
284  * op fails.
285  *
286  * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
287  */
288 static
289 hammer2_chain_t *
290 hammer2_chain_lastdrop(hammer2_chain_t *chain)
291 {
292         hammer2_mount_t *hmp;
293         hammer2_chain_core_t *above;
294         hammer2_chain_core_t *core;
295         hammer2_chain_t *rdrop1;
296         hammer2_chain_t *rdrop2;
297
298         /*
299          * Spinlock the core and check to see if it is empty.  If it is
300          * not empty we leave chain intact with refs == 0.
301          */
302         if ((core = chain->core) != NULL) {
303                 spin_lock(&core->cst.spin);
304                 if (RB_ROOT(&core->rbtree)) {
305                         if (atomic_cmpset_int(&chain->refs, 1, 0)) {
306                                 /* 1->0 transition successful */
307                                 spin_unlock(&core->cst.spin);
308                                 return(NULL);
309                         } else {
310                                 /* 1->0 transition failed, retry */
311                                 spin_unlock(&core->cst.spin);
312                                 return(chain);
313                         }
314                 }
315         }
316
317         hmp = chain->hmp;
318         rdrop1 = NULL;
319         rdrop2 = NULL;
320
321         /*
322          * Spinlock the parent and try to drop the last ref.  On success
323          * remove chain from its parent.
324          */
325         if ((above = chain->above) != NULL) {
326                 spin_lock(&above->cst.spin);
327                 if (!atomic_cmpset_int(&chain->refs, 1, 0)) {
328                         /* 1->0 transition failed */
329                         spin_unlock(&above->cst.spin);
330                         if (core)
331                                 spin_unlock(&core->cst.spin);
332                         return(chain);
333                         /* stop */
334                 }
335
336                 /*
337                  * 1->0 transition successful
338                  */
339                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
340                 RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
341                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
342                 chain->above = NULL;
343
344                 /*
345                  * Calculate a chain to return for a recursive drop.
346                  *
347                  * XXX this needs help, we have a potential deep-recursion
348                  * problem which we try to address but sometimes we wind up
349                  * with two elements that have to be dropped.
350                  *
351                  * If the chain has an associated core with refs at 0
352                  * the chain must be the first in the core's linked list
353                  * by definition, and we will recursively drop the ref
354                  * implied by the chain->next_parent field.
355                  *
356                  * Otherwise if the rbtree containing chain is empty we try
357                  * to recursively drop our parent (only the first one could
358                  * possibly have refs == 0 since the rest are linked via
359                  * next_parent).
360                  *
361                  * Otherwise we try to recursively drop a sibling.
362                  */
363                 if (chain->next_parent) {
364                         KKASSERT(core != NULL);
365                         rdrop1 = chain->next_parent;
366                 }
367                 if (RB_EMPTY(&above->rbtree)) {
368                         rdrop2 = above->first_parent;
369                         if (rdrop2 == NULL || rdrop2->refs ||
370                             atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0) {
371                                 rdrop2 = NULL;
372                         }
373                 } else {
374                         rdrop2 = RB_ROOT(&above->rbtree);
375                         if (atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
376                                 rdrop2 = NULL;
377                 }
378                 spin_unlock(&above->cst.spin);
379                 above = NULL;   /* safety */
380         } else {
381                 if (chain->next_parent) {
382                         KKASSERT(core != NULL);
383                         rdrop1 = chain->next_parent;
384                 }
385         }
386
387         /*
388          * We still have the core spinlock (if core is non-NULL).  The
389          * above spinlock is gone.
390          */
391         if (core) {
392                 KKASSERT(core->first_parent == chain);
393                 if (chain->next_parent) {
394                         /* parent should already be set */
395                         KKASSERT(rdrop1 == chain->next_parent);
396                 }
397                 core->first_parent = chain->next_parent;
398                 chain->next_parent = NULL;
399                 chain->core = NULL;
400
401                 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
402                         /*
403                          * On the 1->0 transition of core we can destroy
404                          * it.
405                          */
406                         spin_unlock(&core->cst.spin);
407                         KKASSERT(core->cst.count == 0);
408                         KKASSERT(core->cst.upgrade == 0);
409                         kfree(core, hmp->mchain);
410                 } else {
411                         spin_unlock(&core->cst.spin);
412                 }
413                 core = NULL;    /* safety */
414         }
415
416         /*
417          * All spin locks are gone, finish freeing stuff.
418          */
419         KKASSERT((chain->flags & (HAMMER2_CHAIN_MOVED |
420                                   HAMMER2_CHAIN_MODIFIED)) == 0);
421
422         switch(chain->bref.type) {
423         case HAMMER2_BREF_TYPE_VOLUME:
424         case HAMMER2_BREF_TYPE_FREEMAP:
425                 chain->data = NULL;
426                 break;
427         case HAMMER2_BREF_TYPE_INODE:
428                 if (chain->data) {
429                         kfree(chain->data, hmp->mchain);
430                         chain->data = NULL;
431                 }
432                 break;
433         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
434                 if (chain->data) {
435                         kfree(chain->data, hmp->mchain);
436                         chain->data = NULL;
437                 }
438                 break;
439         default:
440                 KKASSERT(chain->data == NULL);
441                 break;
442         }
443
444         KKASSERT(chain->bp == NULL);
445         chain->hmp = NULL;
446
447         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
448                 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
449                 kfree(chain, hmp->mchain);
450         }
451         if (rdrop1 && rdrop2) {
452                 hammer2_chain_drop(rdrop1);
453                 return(rdrop2);
454         } else if (rdrop1)
455                 return(rdrop1);
456         else
457                 return(rdrop2);
458 }
459
460 /*
461  * Ref and lock a chain element, acquiring its data with I/O if necessary,
462  * and specify how you would like the data to be resolved.
463  *
464  * Returns 0 on success or an error code if the data could not be acquired.
465  * The chain element is locked on return regardless of whether an error
466  * occurred or not.
467  *
468  * The lock is allowed to recurse, multiple locking ops will aggregate
469  * the requested resolve types.  Once data is assigned it will not be
470  * removed until the last unlock.
471  *
472  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
473  *                         (typically used to avoid device/logical buffer
474  *                          aliasing for data)
475  *
476  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
477  *                         the INITIAL-create state (indirect blocks only).
478  *
479  *                         Do not resolve data elements for DATA chains.
480  *                         (typically used to avoid device/logical buffer
481  *                          aliasing for data)
482  *
483  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
484  *
485  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
486  *                         it will be locked exclusive.
487  *
488  * NOTE: Embedded elements (volume header, inodes) are always resolved
489  *       regardless.
490  *
491  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
492  *       element will instantiate and zero its buffer, and flush it on
493  *       release.
494  *
495  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
496  *       so as not to instantiate a device buffer, which could alias against
497  *       a logical file buffer.  However, if ALWAYS is specified the
498  *       device buffer will be instantiated anyway.
499  *
500  * WARNING! If data must be fetched a shared lock will temporarily be
501  *          upgraded to exclusive.  However, a deadlock can occur if
502  *          the caller owns more than one shared lock.
503  */
504 int
505 hammer2_chain_lock(hammer2_chain_t *chain, int how)
506 {
507         hammer2_mount_t *hmp;
508         hammer2_chain_core_t *core;
509         hammer2_blockref_t *bref;
510         hammer2_off_t pbase;
511         hammer2_off_t pmask;
512         hammer2_off_t peof;
513         ccms_state_t ostate;
514         size_t boff;
515         size_t psize;
516         int error;
517         char *bdata;
518
519         /*
520          * Ref and lock the element.  Recursive locks are allowed.
521          */
522         if ((how & HAMMER2_RESOLVE_NOREF) == 0)
523                 hammer2_chain_ref(chain);
524         atomic_add_int(&chain->lockcnt, 1);
525
526         hmp = chain->hmp;
527         KKASSERT(hmp != NULL);
528
529         /*
530          * Get the appropriate lock.
531          */
532         core = chain->core;
533         if (how & HAMMER2_RESOLVE_SHARED)
534                 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
535         else
536                 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
537
538         /*
539          * If we already have a valid data pointer no further action is
540          * necessary.
541          */
542         if (chain->data)
543                 return (0);
544
545         /*
546          * Do we have to resolve the data?
547          */
548         switch(how & HAMMER2_RESOLVE_MASK) {
549         case HAMMER2_RESOLVE_NEVER:
550                 return(0);
551         case HAMMER2_RESOLVE_MAYBE:
552                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
553                         return(0);
554                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
555                         return(0);
556 #if 0
557                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
558                         return(0);
559 #endif
560                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
561                         return(0);
562                 /* fall through */
563         case HAMMER2_RESOLVE_ALWAYS:
564                 break;
565         }
566
567         /*
568          * Upgrade to an exclusive lock so we can safely manipulate the
569          * buffer cache.  If another thread got to it before us we
570          * can just return.
571          */
572         ostate = ccms_thread_lock_upgrade(&core->cst);
573         if (chain->data) {
574                 ccms_thread_lock_downgrade(&core->cst, ostate);
575                 return (0);
576         }
577
578         /*
579          * We must resolve to a device buffer, either by issuing I/O or
580          * by creating a zero-fill element.  We do not mark the buffer
581          * dirty when creating a zero-fill element (the hammer2_chain_modify()
582          * API must still be used to do that).
583          *
584          * The device buffer is variable-sized in powers of 2 down
585          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
586          * chunk always contains buffers of the same size. (XXX)
587          *
588          * The minimum physical IO size may be larger than the variable
589          * block size.
590          */
591         bref = &chain->bref;
592
593         psize = hammer2_devblksize(chain->bytes);
594         pmask = (hammer2_off_t)psize - 1;
595         pbase = bref->data_off & ~pmask;
596         boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
597         KKASSERT(pbase != 0);
598         peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
599
600         /*
601          * The getblk() optimization can only be used on newly created
602          * elements if the physical block size matches the request.
603          */
604         if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
605             chain->bytes == psize) {
606                 chain->bp = getblk(hmp->devvp, pbase, psize, 0, 0);
607                 error = 0;
608         } else if (hammer2_isclusterable(chain)) {
609                 error = cluster_read(hmp->devvp, peof, pbase, psize,
610                                      psize, HAMMER2_PBUFSIZE*4,
611                                      &chain->bp);
612                 adjreadcounter(&chain->bref, chain->bytes);
613         } else {
614                 error = bread(hmp->devvp, pbase, psize, &chain->bp);
615                 adjreadcounter(&chain->bref, chain->bytes);
616         }
617
618         if (error) {
619                 kprintf("hammer2_chain_get: I/O error %016jx: %d\n",
620                         (intmax_t)pbase, error);
621                 bqrelse(chain->bp);
622                 chain->bp = NULL;
623                 ccms_thread_lock_downgrade(&core->cst, ostate);
624                 return (error);
625         }
626
627         /*
628          * Zero the data area if the chain is in the INITIAL-create state.
629          * Mark the buffer for bdwrite().  This clears the INITIAL state
630          * but does not mark the chain modified.
631          */
632         bdata = (char *)chain->bp->b_data + boff;
633         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
634                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
635                 bzero(bdata, chain->bytes);
636                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
637         }
638
639         /*
640          * Setup the data pointer, either pointing it to an embedded data
641          * structure and copying the data from the buffer, or pointing it
642          * into the buffer.
643          *
644          * The buffer is not retained when copying to an embedded data
645          * structure in order to avoid potential deadlocks or recursions
646          * on the same physical buffer.
647          */
648         switch (bref->type) {
649         case HAMMER2_BREF_TYPE_VOLUME:
650         case HAMMER2_BREF_TYPE_FREEMAP:
651                 /*
652                  * Copy data from bp to embedded buffer
653                  */
654                 panic("hammer2_chain_lock: called on unresolved volume header");
655 #if 0
656                 /* NOT YET */
657                 KKASSERT(pbase == 0);
658                 KKASSERT(chain->bytes == HAMMER2_PBUFSIZE);
659                 bcopy(bdata, &hmp->voldata, chain->bytes);
660                 chain->data = (void *)&hmp->voldata;
661                 bqrelse(chain->bp);
662                 chain->bp = NULL;
663 #endif
664                 break;
665         case HAMMER2_BREF_TYPE_INODE:
666                 /*
667                  * Copy data from bp to embedded buffer, do not retain the
668                  * device buffer.
669                  */
670                 KKASSERT(chain->bytes == sizeof(chain->data->ipdata));
671                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
672                 chain->data = kmalloc(sizeof(chain->data->ipdata),
673                                       hmp->mchain, M_WAITOK | M_ZERO);
674                 bcopy(bdata, &chain->data->ipdata, chain->bytes);
675                 bqrelse(chain->bp);
676                 chain->bp = NULL;
677                 break;
678         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
679                 KKASSERT(chain->bytes == sizeof(chain->data->bmdata));
680                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
681                 chain->data = kmalloc(sizeof(chain->data->bmdata),
682                                       hmp->mchain, M_WAITOK | M_ZERO);
683                 bcopy(bdata, &chain->data->bmdata, chain->bytes);
684                 bqrelse(chain->bp);
685                 chain->bp = NULL;
686                 break;
687         case HAMMER2_BREF_TYPE_INDIRECT:
688         case HAMMER2_BREF_TYPE_DATA:
689         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
690         default:
691                 /*
692                  * Point data at the device buffer and leave bp intact.
693                  */
694                 chain->data = (void *)bdata;
695                 break;
696         }
697
698         /*
699          * Make sure the bp is not specifically owned by this thread before
700          * restoring to a possibly shared lock, so another hammer2 thread
701          * can release it.
702          */
703         if (chain->bp)
704                 BUF_KERNPROC(chain->bp);
705         ccms_thread_lock_downgrade(&core->cst, ostate);
706         return (0);
707 }
708
709 /*
710  * Asynchronously read the device buffer (dbp) and execute the specified
711  * callback.  The caller should pass-in a locked chain (shared lock is ok).
712  * The function is responsible for unlocking the chain and for disposing
713  * of dbp.
714  *
715  * NOTE!  A NULL dbp (but non-NULL data) will be passed to the function
716  *        if the dbp is integrated into the chain, because we do not want
717  *        the caller to dispose of dbp in that situation.
718  */
719 static void hammer2_chain_load_async_callback(struct bio *bio);
720
721 void
722 hammer2_chain_load_async(hammer2_chain_t *chain,
723         void (*func)(hammer2_chain_t *, struct buf *, char *, void *),
724         void *arg)
725 {
726         hammer2_cbinfo_t *cbinfo;
727         hammer2_mount_t *hmp;
728         hammer2_blockref_t *bref;
729         hammer2_off_t pbase;
730         hammer2_off_t pmask;
731         hammer2_off_t peof;
732         struct buf *dbp;
733         size_t boff;
734         size_t psize;
735         char *bdata;
736
737         if (chain->data) {
738                 func(chain, NULL, (char *)chain->data, arg);
739                 return;
740         }
741
742         /*
743          * We must resolve to a device buffer, either by issuing I/O or
744          * by creating a zero-fill element.  We do not mark the buffer
745          * dirty when creating a zero-fill element (the hammer2_chain_modify()
746          * API must still be used to do that).
747          *
748          * The device buffer is variable-sized in powers of 2 down
749          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
750          * chunk always contains buffers of the same size. (XXX)
751          *
752          * The minimum physical IO size may be larger than the variable
753          * block size.
754          */
755         bref = &chain->bref;
756
757         psize = hammer2_devblksize(chain->bytes);
758         pmask = (hammer2_off_t)psize - 1;
759         pbase = bref->data_off & ~pmask;
760         boff = bref->data_off & (HAMMER2_OFF_MASK & pmask);
761         KKASSERT(pbase != 0);
762         peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
763
764         hmp = chain->hmp;
765
766         /*
767          * The getblk() optimization can only be used on newly created
768          * elements if the physical block size matches the request.
769          */
770         if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
771             chain->bytes == psize) {
772                 dbp = getblk(hmp->devvp, pbase, psize, 0, 0);
773                 /*atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);*/
774                 bdata = (char *)dbp->b_data + boff;
775                 bzero(bdata, chain->bytes);
776                 /*atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);*/
777                 func(chain, dbp, bdata, arg);
778                 bqrelse(dbp);
779                 return;
780         }
781
782         adjreadcounter(&chain->bref, chain->bytes);
783         cbinfo = kmalloc(sizeof(*cbinfo), hmp->mchain, M_INTWAIT | M_ZERO);
784         cbinfo->chain = chain;
785         cbinfo->func = func;
786         cbinfo->arg = arg;
787         cbinfo->boff = boff;
788
789         cluster_readcb(hmp->devvp, peof, pbase, psize,
790                 HAMMER2_PBUFSIZE*4, HAMMER2_PBUFSIZE*4,
791                 hammer2_chain_load_async_callback, cbinfo);
792 }
793
794 static void
795 hammer2_chain_load_async_callback(struct bio *bio)
796 {
797         hammer2_cbinfo_t *cbinfo;
798         hammer2_mount_t *hmp;
799         struct buf *dbp;
800         char *data;
801
802         /*
803          * Nobody is waiting for bio/dbp to complete, we are
804          * responsible for handling the biowait() equivalent
805          * on dbp which means clearing BIO_DONE and BIO_SYNC
806          * and calling bpdone() if it hasn't already been called
807          * to restore any covered holes in the buffer's backing
808          * store.
809          */
810         dbp = bio->bio_buf;
811         if ((bio->bio_flags & BIO_DONE) == 0)
812                 bpdone(dbp, 0);
813         bio->bio_flags &= ~(BIO_DONE | BIO_SYNC);
814
815         /*
816          * Extract the auxillary info and issue the callback.
817          * Finish up with the dbp after it returns.
818          */
819         cbinfo = bio->bio_caller_info1.ptr;
820         /*ccms_thread_lock_setown(cbinfo->chain->core);*/
821         data = dbp->b_data + cbinfo->boff;
822         hmp = cbinfo->chain->hmp;
823
824         cbinfo = bio->bio_caller_info1.ptr;
825         cbinfo->func(cbinfo->chain, dbp, data, cbinfo->arg);
826         /* cbinfo->chain is stale now */
827         bqrelse(dbp);
828         kfree(cbinfo, hmp->mchain);
829 }
830
831 /*
832  * Unlock and deref a chain element.
833  *
834  * On the last lock release any non-embedded data (chain->bp) will be
835  * retired.
836  */
837 void
838 hammer2_chain_unlock(hammer2_chain_t *chain)
839 {
840         hammer2_chain_core_t *core = chain->core;
841         ccms_state_t ostate;
842         long *counterp;
843         u_int lockcnt;
844
845         /*
846          * The core->cst lock can be shared across several chains so we
847          * need to track the per-chain lockcnt separately.
848          *
849          * If multiple locks are present (or being attempted) on this
850          * particular chain we can just unlock, drop refs, and return.
851          *
852          * Otherwise fall-through on the 1->0 transition.
853          */
854         for (;;) {
855                 lockcnt = chain->lockcnt;
856                 KKASSERT(lockcnt > 0);
857                 cpu_ccfence();
858                 if (lockcnt > 1) {
859                         if (atomic_cmpset_int(&chain->lockcnt,
860                                               lockcnt, lockcnt - 1)) {
861                                 ccms_thread_unlock(&core->cst);
862                                 hammer2_chain_drop(chain);
863                                 return;
864                         }
865                 } else {
866                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
867                                 break;
868                 }
869                 /* retry */
870         }
871
872         /*
873          * On the 1->0 transition we upgrade the core lock (if necessary)
874          * to exclusive for terminal processing.  If after upgrading we find
875          * that lockcnt is non-zero, another thread is racing us and will
876          * handle the unload for us later on, so just cleanup and return
877          * leaving the data/bp intact
878          *
879          * Otherwise if lockcnt is still 0 it is possible for it to become
880          * non-zero and race, but since we hold the core->cst lock
881          * exclusively all that will happen is that the chain will be
882          * reloaded after we unload it.
883          */
884         ostate = ccms_thread_lock_upgrade(&core->cst);
885         if (chain->lockcnt) {
886                 ccms_thread_unlock_upgraded(&core->cst, ostate);
887                 hammer2_chain_drop(chain);
888                 return;
889         }
890
891         /*
892          * Shortcut the case if the data is embedded or not resolved.
893          *
894          * Do NOT NULL out chain->data (e.g. inode data), it might be
895          * dirty.
896          *
897          * The DIRTYBP flag is non-applicable in this situation and can
898          * be cleared to keep the flags state clean.
899          */
900         if (chain->bp == NULL) {
901                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
902                 ccms_thread_unlock_upgraded(&core->cst, ostate);
903                 hammer2_chain_drop(chain);
904                 return;
905         }
906
907         /*
908          * Statistics
909          */
910         if ((chain->flags & HAMMER2_CHAIN_DIRTYBP) == 0) {
911                 ;
912         } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
913                 switch(chain->bref.type) {
914                 case HAMMER2_BREF_TYPE_DATA:
915                         counterp = &hammer2_ioa_file_write;
916                         break;
917                 case HAMMER2_BREF_TYPE_INODE:
918                         counterp = &hammer2_ioa_meta_write;
919                         break;
920                 case HAMMER2_BREF_TYPE_INDIRECT:
921                         counterp = &hammer2_ioa_indr_write;
922                         break;
923                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
924                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
925                         counterp = &hammer2_ioa_fmap_write;
926                         break;
927                 default:
928                         counterp = &hammer2_ioa_volu_write;
929                         break;
930                 }
931                 *counterp += chain->bytes;
932         } else {
933                 switch(chain->bref.type) {
934                 case HAMMER2_BREF_TYPE_DATA:
935                         counterp = &hammer2_iod_file_write;
936                         break;
937                 case HAMMER2_BREF_TYPE_INODE:
938                         counterp = &hammer2_iod_meta_write;
939                         break;
940                 case HAMMER2_BREF_TYPE_INDIRECT:
941                         counterp = &hammer2_iod_indr_write;
942                         break;
943                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
944                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
945                         counterp = &hammer2_iod_fmap_write;
946                         break;
947                 default:
948                         counterp = &hammer2_iod_volu_write;
949                         break;
950                 }
951                 *counterp += chain->bytes;
952         }
953
954         /*
955          * Clean out the bp.
956          *
957          * If a device buffer was used for data be sure to destroy the
958          * buffer when we are done to avoid aliases (XXX what about the
959          * underlying VM pages?).
960          *
961          * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
962          *       is possible.
963          */
964 #if 0
965         /*
966          * XXX our primary cache is now the block device, not
967          * the logical file. don't release the buffer.
968          */
969         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
970                 chain->bp->b_flags |= B_RELBUF;
971 #endif
972
973         /*
974          * The DIRTYBP flag tracks whether we have to bdwrite() the buffer
975          * or not.  The flag will get re-set when chain_modify() is called,
976          * even if MODIFIED is already set, allowing the OS to retire the
977          * buffer independent of a hammer2 flus.
978          */
979         chain->data = NULL;
980         if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
981                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
982                 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
983                         atomic_clear_int(&chain->flags,
984                                          HAMMER2_CHAIN_IOFLUSH);
985                         chain->bp->b_flags |= B_RELBUF;
986                         cluster_awrite(chain->bp);
987                 } else {
988                         chain->bp->b_flags |= B_CLUSTEROK;
989                         bdwrite(chain->bp);
990                 }
991         } else {
992                 if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
993                         atomic_clear_int(&chain->flags,
994                                          HAMMER2_CHAIN_IOFLUSH);
995                         chain->bp->b_flags |= B_RELBUF;
996                         brelse(chain->bp);
997                 } else {
998                         /* bp might still be dirty */
999                         bqrelse(chain->bp);
1000                 }
1001         }
1002         chain->bp = NULL;
1003         ccms_thread_unlock_upgraded(&core->cst, ostate);
1004         hammer2_chain_drop(chain);
1005 }
1006
1007 /*
1008  * Resize the chain's physical storage allocation in-place.  This may
1009  * replace the passed-in chain with a new chain.
1010  *
1011  * Chains can be resized smaller without reallocating the storage.
1012  * Resizing larger will reallocate the storage.
1013  *
1014  * Must be passed an exclusively locked parent and chain, returns a new
1015  * exclusively locked chain at the same index and unlocks the old chain.
1016  * Flushes the buffer if necessary.
1017  *
1018  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1019  * to avoid instantiating a device buffer that conflicts with the vnode
1020  * data buffer.  That is, the passed-in bp is a logical buffer, whereas
1021  * any chain-oriented bp would be a device buffer.
1022  *
1023  * XXX flags currently ignored, uses chain->bp to detect data/no-data.
1024  * XXX return error if cannot resize.
1025  */
1026 void
1027 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1028                      struct buf *bp,
1029                      hammer2_chain_t *parent, hammer2_chain_t **chainp,
1030                      int nradix, int flags)
1031 {
1032         hammer2_mount_t *hmp;
1033         hammer2_chain_t *chain;
1034         hammer2_off_t pbase;
1035         size_t obytes;
1036         size_t nbytes;
1037         size_t bbytes;
1038         int boff;
1039
1040         chain = *chainp;
1041         hmp = chain->hmp;
1042
1043         /*
1044          * Only data and indirect blocks can be resized for now.
1045          * (The volu root, inodes, and freemap elements use a fixed size).
1046          */
1047         KKASSERT(chain != &hmp->vchain);
1048         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1049                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1050
1051         /*
1052          * Nothing to do if the element is already the proper size
1053          */
1054         obytes = chain->bytes;
1055         nbytes = 1U << nradix;
1056         if (obytes == nbytes)
1057                 return;
1058
1059         /*
1060          * Delete the old chain and duplicate it at the same (parent, index),
1061          * returning a new chain.  This allows the old chain to still be
1062          * used by the flush code.  Duplication occurs in-place.
1063          *
1064          * The parent does not have to be locked for the delete/duplicate call,
1065          * but is in this particular code path.
1066          *
1067          * NOTE: If we are not crossing a synchronization point the
1068          *       duplication code will simply reuse the existing chain
1069          *       structure.
1070          */
1071         hammer2_chain_delete_duplicate(trans, &chain, 0);
1072
1073         /*
1074          * Set MODIFIED and add a chain ref to prevent destruction.  Both
1075          * modified flags share the same ref.  (duplicated chains do not
1076          * start out MODIFIED unless possibly if the duplication code
1077          * decided to reuse the existing chain as-is).
1078          *
1079          * If the chain is already marked MODIFIED then we can safely
1080          * return the previous allocation to the pool without having to
1081          * worry about snapshots.  XXX check flush synchronization.
1082          */
1083         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1084                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1085                 hammer2_chain_ref(chain);
1086         }
1087
1088         /*
1089          * Relocate the block, even if making it smaller (because different
1090          * block sizes may be in different regions).
1091          */
1092         hammer2_freemap_alloc(trans, chain->hmp, &chain->bref, nbytes);
1093         chain->bytes = nbytes;
1094         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1095
1096         /*
1097          * The device buffer may be larger than the allocation size.
1098          */
1099         bbytes = hammer2_devblksize(chain->bytes);
1100         pbase = chain->bref.data_off & ~(hammer2_off_t)(bbytes - 1);
1101         boff = chain->bref.data_off & HAMMER2_OFF_MASK & (bbytes - 1);
1102
1103         /*
1104          * For now just support it on DATA chains (and not on indirect
1105          * blocks).
1106          */
1107         KKASSERT(chain->bp == NULL);
1108
1109         /*
1110          * Make sure the chain is marked MOVED and SUBMOD is set in the
1111          * parent(s) so the adjustments are picked up by flush.
1112          */
1113         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
1114                 hammer2_chain_ref(chain);
1115                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
1116         }
1117         hammer2_chain_setsubmod(trans, chain);
1118         *chainp = chain;
1119 }
1120
1121 /*
1122  * Set a chain modified, making it read-write and duplicating it if necessary.
1123  * This function will assign a new physical block to the chain if necessary
1124  *
1125  * Duplication of already-modified chains is possible when the modification
1126  * crosses a flush synchronization boundary.
1127  *
1128  * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1129  *                   level or the COW operation will not work.
1130  *
1131  * Data blocks     - The chain is usually locked RESOLVE_NEVER so as not to
1132  *                   run the data through the device buffers.
1133  *
1134  * This function may return a different chain than was passed, in which case
1135  * the old chain will be unlocked and the new chain will be locked.
1136  *
1137  * ip->chain may be adjusted by hammer2_chain_modify_ip().
1138  */
1139 hammer2_inode_data_t *
1140 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1141                         hammer2_chain_t **chainp, int flags)
1142 {
1143         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1144         hammer2_chain_modify(trans, chainp, flags);
1145         if (ip->chain != *chainp)
1146                 hammer2_inode_repoint(ip, NULL, *chainp);
1147         return(&ip->chain->data->ipdata);
1148 }
1149
1150 void
1151 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1152                      int flags)
1153 {
1154         hammer2_mount_t *hmp;
1155         hammer2_chain_t *chain;
1156         hammer2_off_t pbase;
1157         hammer2_off_t pmask;
1158         hammer2_off_t peof;
1159         hammer2_tid_t flush_tid;
1160         struct buf *nbp;
1161         int error;
1162         int wasinitial;
1163         size_t psize;
1164         size_t boff;
1165         void *bdata;
1166
1167         /*
1168          * Data must be resolved if already assigned unless explicitly
1169          * flagged otherwise.
1170          */
1171         chain = *chainp;
1172         hmp = chain->hmp;
1173         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1174             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1175                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1176                 hammer2_chain_unlock(chain);
1177         }
1178
1179         /*
1180          * data is not optional for freemap chains (we must always be sure
1181          * to copy the data on COW storage allocations).
1182          */
1183         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1184             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1185                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1186                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1187         }
1188
1189         /*
1190          * If the chain is already marked MODIFIED we can usually just
1191          * return.  However, if a modified chain is modified again in
1192          * a synchronization-point-crossing manner we have to issue a
1193          * delete/duplicate on the chain to avoid flush interference.
1194          */
1195         if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1196                 /*
1197                  * Which flush_tid do we need to check?  If the chain is
1198                  * related to the freemap we have to use the freemap flush
1199                  * tid (free_flush_tid), otherwise we use the normal filesystem
1200                  * flush tid (topo_flush_tid).  The two flush domains are
1201                  * almost completely independent of each other.
1202                  */
1203                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1204                     chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1205                         flush_tid = hmp->topo_flush_tid; /* XXX */
1206                         goto skipxx;    /* XXX */
1207                 } else {
1208                         flush_tid = hmp->topo_flush_tid;
1209                 }
1210
1211                 /*
1212                  * Main tests
1213                  */
1214                 if (chain->modify_tid <= flush_tid &&
1215                     trans->sync_tid > flush_tid) {
1216                         /*
1217                          * Modifications cross synchronization point,
1218                          * requires delete-duplicate.
1219                          */
1220                         KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1221                         hammer2_chain_delete_duplicate(trans, chainp, 0);
1222                         chain = *chainp;
1223                         /* fall through using duplicate */
1224                 }
1225 skipxx: /* XXX */
1226                 /*
1227                  * Quick return path, set DIRTYBP to ensure that
1228                  * the later retirement of bp will write it out.
1229                  *
1230                  * quick return path also needs the modify_tid
1231                  * logic.
1232                  */
1233                 if (chain->bp)
1234                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1235                 if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1236                         chain->bref.modify_tid = trans->sync_tid;
1237                 chain->modify_tid = trans->sync_tid;
1238                 return;
1239         }
1240
1241         /*
1242          * modify_tid is only update for primary modifications, not for
1243          * propagated brefs.  mirror_tid will be updated regardless during
1244          * the flush, no need to set it here.
1245          */
1246         if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1247                 chain->bref.modify_tid = trans->sync_tid;
1248
1249         /*
1250          * Set MODIFIED and add a chain ref to prevent destruction.  Both
1251          * modified flags share the same ref.
1252          */
1253         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1254                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1255                 hammer2_chain_ref(chain);
1256         }
1257
1258         /*
1259          * Adjust chain->modify_tid so the flusher knows when the
1260          * modification occurred.
1261          */
1262         chain->modify_tid = trans->sync_tid;
1263
1264         /*
1265          * The modification or re-modification requires an allocation and
1266          * possible COW.
1267          *
1268          * We normally always allocate new storage here.  If storage exists
1269          * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1270          */
1271         if (chain != &hmp->vchain &&
1272             chain != &hmp->fchain &&
1273             ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1274              (flags & HAMMER2_MODIFY_NOREALLOC) == 0)
1275         ) {
1276                 hammer2_freemap_alloc(trans, chain->hmp,
1277                                       &chain->bref, chain->bytes);
1278                 /* XXX failed allocation */
1279         }
1280
1281         /*
1282          * Do not COW if OPTDATA is set.  INITIAL flag remains unchanged.
1283          * (OPTDATA does not prevent [re]allocation of storage, only the
1284          * related copy-on-write op).
1285          */
1286         if (flags & HAMMER2_MODIFY_OPTDATA)
1287                 goto skip2;
1288
1289         /*
1290          * Clearing the INITIAL flag (for indirect blocks) indicates that
1291          * we've processed the uninitialized storage allocation.
1292          *
1293          * If this flag is already clear we are likely in a copy-on-write
1294          * situation but we have to be sure NOT to bzero the storage if
1295          * no data is present.
1296          */
1297         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1298                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1299                 wasinitial = 1;
1300         } else {
1301                 wasinitial = 0;
1302         }
1303
1304 #if 0
1305         /*
1306          * We currently should never instantiate a device buffer for a
1307          * file data chain.  (We definitely can for a freemap chain).
1308          *
1309          * XXX we can now do this
1310          */
1311         KKASSERT(chain->bref.type != HAMMER2_BREF_TYPE_DATA);
1312 #endif
1313
1314         /*
1315          * Instantiate data buffer and possibly execute COW operation
1316          */
1317         switch(chain->bref.type) {
1318         case HAMMER2_BREF_TYPE_VOLUME:
1319         case HAMMER2_BREF_TYPE_FREEMAP:
1320         case HAMMER2_BREF_TYPE_INODE:
1321         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1322                 /*
1323                  * The data is embedded, no copy-on-write operation is
1324                  * needed.
1325                  */
1326                 KKASSERT(chain->bp == NULL);
1327                 break;
1328         case HAMMER2_BREF_TYPE_DATA:
1329         case HAMMER2_BREF_TYPE_INDIRECT:
1330         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1331                 /*
1332                  * Perform the copy-on-write operation
1333                  */
1334                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1335
1336                 psize = hammer2_devblksize(chain->bytes);
1337                 pmask = (hammer2_off_t)psize - 1;
1338                 pbase = chain->bref.data_off & ~pmask;
1339                 boff = chain->bref.data_off & (HAMMER2_OFF_MASK & pmask);
1340                 KKASSERT(pbase != 0);
1341                 peof = (pbase + HAMMER2_SEGMASK64) & ~HAMMER2_SEGMASK64;
1342
1343                 /*
1344                  * The getblk() optimization can only be used if the
1345                  * chain element size matches the physical block size.
1346                  */
1347                 if (chain->bp && chain->bp->b_loffset == pbase) {
1348                         nbp = chain->bp;
1349                         error = 0;
1350                 } else if (chain->bytes == psize) {
1351                         nbp = getblk(hmp->devvp, pbase, psize, 0, 0);
1352                         error = 0;
1353                 } else if (hammer2_isclusterable(chain)) {
1354                         error = cluster_read(hmp->devvp, peof, pbase, psize,
1355                                              psize, HAMMER2_PBUFSIZE*4,
1356                                              &nbp);
1357                         adjreadcounter(&chain->bref, chain->bytes);
1358                 } else {
1359                         error = bread(hmp->devvp, pbase, psize, &nbp);
1360                         adjreadcounter(&chain->bref, chain->bytes);
1361                 }
1362                 KKASSERT(error == 0);
1363                 bdata = (char *)nbp->b_data + boff;
1364
1365                 /*
1366                  * Copy or zero-fill on write depending on whether
1367                  * chain->data exists or not.  Retire the existing bp
1368                  * based on the DIRTYBP flag.  Set the DIRTYBP flag to
1369                  * indicate that retirement of nbp should use bdwrite().
1370                  */
1371                 if (chain->data) {
1372                         KKASSERT(chain->bp != NULL);
1373                         if (chain->data != bdata) {
1374                                 bcopy(chain->data, bdata, chain->bytes);
1375                         }
1376                 } else if (wasinitial) {
1377                         bzero(bdata, chain->bytes);
1378                 } else {
1379                         /*
1380                          * We have a problem.  We were asked to COW but
1381                          * we don't have any data to COW with!
1382                          */
1383                         panic("hammer2_chain_modify: having a COW %p\n",
1384                               chain);
1385                 }
1386                 if (chain->bp != nbp) {
1387                         if (chain->bp) {
1388                                 if (chain->flags & HAMMER2_CHAIN_DIRTYBP) {
1389                                         chain->bp->b_flags |= B_CLUSTEROK;
1390                                         bdwrite(chain->bp);
1391                                 } else {
1392                                         chain->bp->b_flags |= B_RELBUF;
1393                                         brelse(chain->bp);
1394                                 }
1395                         }
1396                         chain->bp = nbp;
1397                         BUF_KERNPROC(chain->bp);
1398                 }
1399                 chain->data = bdata;
1400                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DIRTYBP);
1401                 break;
1402         default:
1403                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1404                       chain->bref.type);
1405                 break;
1406
1407         }
1408 skip2:
1409         hammer2_chain_setsubmod(trans, chain);
1410 }
1411
1412 /*
1413  * Mark the volume as having been modified.  This short-cut version
1414  * does not have to lock the volume's chain, which allows the ioctl
1415  * code to make adjustments to connections without deadlocking.  XXX
1416  *
1417  * No ref is made on vchain when flagging it MODIFIED.
1418  */
1419 void
1420 hammer2_modify_volume(hammer2_mount_t *hmp)
1421 {
1422         hammer2_voldata_lock(hmp);
1423         hammer2_voldata_unlock(hmp, 1);
1424 }
1425
1426 /*
1427  * Locate an in-memory chain.  The parent must be locked.  The in-memory
1428  * chain is returned with a reference and without a lock, or NULL
1429  * if not found.
1430  *
1431  * This function returns the chain at the specified index with the highest
1432  * delete_tid.  The caller must check whether the chain is flagged
1433  * CHAIN_DELETED or not.  However, because chain iterations can be removed
1434  * from memory we must ALSO check that DELETED chains are not flushed.  A
1435  * DELETED chain which has been flushed must be ignored (the caller must
1436  * check the parent's blockref array).
1437  *
1438  * NOTE: If no chain is found the caller usually must check the on-media
1439  *       array to determine if a blockref exists at the index.
1440  */
1441 struct hammer2_chain_find_info {
1442         hammer2_chain_t *best;
1443         hammer2_tid_t   delete_tid;
1444         int index;
1445 };
1446
1447 static
1448 int
1449 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1450 {
1451         struct hammer2_chain_find_info *info = data;
1452
1453         if (child->index < info->index)
1454                 return(-1);
1455         if (child->index > info->index)
1456                 return(1);
1457         return(0);
1458 }
1459
1460 static
1461 int
1462 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1463 {
1464         struct hammer2_chain_find_info *info = data;
1465
1466         if (info->delete_tid < child->delete_tid) {
1467                 info->delete_tid = child->delete_tid;
1468                 info->best = child;
1469         }
1470         return(0);
1471 }
1472
1473 static
1474 hammer2_chain_t *
1475 hammer2_chain_find_locked(hammer2_chain_t *parent, int index)
1476 {
1477         struct hammer2_chain_find_info info;
1478         hammer2_chain_t *child;
1479
1480         info.index = index;
1481         info.delete_tid = 0;
1482         info.best = NULL;
1483
1484         RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1485                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1486                 &info);
1487         child = info.best;
1488
1489         return (child);
1490 }
1491
1492 hammer2_chain_t *
1493 hammer2_chain_find(hammer2_chain_t *parent, int index)
1494 {
1495         hammer2_chain_t *child;
1496
1497         spin_lock(&parent->core->cst.spin);
1498         child = hammer2_chain_find_locked(parent, index);
1499         if (child)
1500                 hammer2_chain_ref(child);
1501         spin_unlock(&parent->core->cst.spin);
1502
1503         return (child);
1504 }
1505
1506 /*
1507  * Return a locked chain structure with all associated data acquired.
1508  * (if LOOKUP_NOLOCK is requested the returned chain is only referenced).
1509  *
1510  * Caller must hold the parent locked shared or exclusive since we may
1511  * need the parent's bref array to find our block.
1512  *
1513  * The returned child is locked as requested.  If NOLOCK, the returned
1514  * child is still at least referenced.
1515  */
1516 hammer2_chain_t *
1517 hammer2_chain_get(hammer2_chain_t *parent, int index, int flags)
1518 {
1519         hammer2_blockref_t *bref;
1520         hammer2_mount_t *hmp = parent->hmp;
1521         hammer2_chain_core_t *above = parent->core;
1522         hammer2_chain_t *chain;
1523         hammer2_chain_t dummy;
1524         int how;
1525
1526         /*
1527          * Figure out how to lock.  MAYBE can be used to optimized
1528          * the initial-create state for indirect blocks.
1529          */
1530         if (flags & HAMMER2_LOOKUP_ALWAYS)
1531                 how = HAMMER2_RESOLVE_ALWAYS;
1532         else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK))
1533                 how = HAMMER2_RESOLVE_NEVER;
1534         else
1535                 how = HAMMER2_RESOLVE_MAYBE;
1536         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1537                 how |= HAMMER2_RESOLVE_SHARED;
1538
1539 retry:
1540         /*
1541          * First see if we have a (possibly modified) chain element cached
1542          * for this (parent, index).  Acquire the data if necessary.
1543          *
1544          * If chain->data is non-NULL the chain should already be marked
1545          * modified.
1546          */
1547         dummy.flags = 0;
1548         dummy.index = index;
1549         dummy.delete_tid = HAMMER2_MAX_TID;
1550         spin_lock(&above->cst.spin);
1551         chain = RB_FIND(hammer2_chain_tree, &above->rbtree, &dummy);
1552         if (chain) {
1553                 hammer2_chain_ref(chain);
1554                 spin_unlock(&above->cst.spin);
1555                 if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1556                         hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1557                 return(chain);
1558         }
1559         spin_unlock(&above->cst.spin);
1560
1561         /*
1562          * The parent chain must not be in the INITIAL state.
1563          */
1564         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1565                 panic("hammer2_chain_get: Missing bref(1)");
1566                 /* NOT REACHED */
1567         }
1568
1569         /*
1570          * No RBTREE entry found, lookup the bref and issue I/O (switch on
1571          * the parent's bref to determine where and how big the array is).
1572          */
1573         switch(parent->bref.type) {
1574         case HAMMER2_BREF_TYPE_INODE:
1575                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1576                 bref = &parent->data->ipdata.u.blockset.blockref[index];
1577                 break;
1578         case HAMMER2_BREF_TYPE_INDIRECT:
1579         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1580                 KKASSERT(parent->data != NULL);
1581                 KKASSERT(index >= 0 &&
1582                          index < parent->bytes / sizeof(hammer2_blockref_t));
1583                 bref = &parent->data->npdata[index];
1584                 break;
1585         case HAMMER2_BREF_TYPE_VOLUME:
1586                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1587                 bref = &hmp->voldata.sroot_blockset.blockref[index];
1588                 break;
1589         case HAMMER2_BREF_TYPE_FREEMAP:
1590                 KKASSERT(index >= 0 && index < HAMMER2_SET_COUNT);
1591                 bref = &hmp->voldata.freemap_blockset.blockref[index];
1592                 break;
1593         default:
1594                 bref = NULL;
1595                 panic("hammer2_chain_get: unrecognized blockref type: %d",
1596                       parent->bref.type);
1597         }
1598         if (bref->type == 0) {
1599                 panic("hammer2_chain_get: Missing bref(2)");
1600                 /* NOT REACHED */
1601         }
1602
1603         /*
1604          * Allocate a chain structure representing the existing media
1605          * entry.  Resulting chain has one ref and is not locked.
1606          *
1607          * The locking operation we do later will issue I/O to read it.
1608          */
1609         chain = hammer2_chain_alloc(hmp, NULL, bref);
1610         hammer2_chain_core_alloc(chain, NULL);  /* ref'd chain returned */
1611
1612         /*
1613          * Link the chain into its parent.  A spinlock is required to safely
1614          * access the RBTREE, and it is possible to collide with another
1615          * hammer2_chain_get() operation because the caller might only hold
1616          * a shared lock on the parent.
1617          */
1618         KKASSERT(parent->refs > 0);
1619         spin_lock(&above->cst.spin);
1620         chain->above = above;
1621         chain->index = index;
1622         if (RB_INSERT(hammer2_chain_tree, &above->rbtree, chain)) {
1623                 chain->above = NULL;
1624                 chain->index = -1;
1625                 spin_unlock(&above->cst.spin);
1626                 hammer2_chain_drop(chain);
1627                 goto retry;
1628         }
1629         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
1630         spin_unlock(&above->cst.spin);
1631
1632         /*
1633          * Our new chain is referenced but NOT locked.  Lock the chain
1634          * below.  The locking operation also resolves its data.
1635          *
1636          * If NOLOCK is set the release will release the one-and-only lock.
1637          */
1638         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0) {
1639                 hammer2_chain_lock(chain, how); /* recusive lock */
1640                 hammer2_chain_drop(chain);      /* excess ref */
1641         }
1642         return (chain);
1643 }
1644
1645 /*
1646  * Lookup initialization/completion API
1647  */
1648 hammer2_chain_t *
1649 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1650 {
1651         if (flags & HAMMER2_LOOKUP_SHARED) {
1652                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1653                                            HAMMER2_RESOLVE_SHARED);
1654         } else {
1655                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1656         }
1657         return (parent);
1658 }
1659
1660 void
1661 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1662 {
1663         if (parent)
1664                 hammer2_chain_unlock(parent);
1665 }
1666
1667 static
1668 hammer2_chain_t *
1669 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1670 {
1671         hammer2_chain_t *oparent;
1672         hammer2_chain_t *nparent;
1673         hammer2_chain_core_t *above;
1674
1675         oparent = *parentp;
1676         above = oparent->above;
1677
1678         spin_lock(&above->cst.spin);
1679         nparent = above->first_parent;
1680         while (hammer2_chain_refactor_test(nparent, 1))
1681                 nparent = nparent->next_parent;
1682         hammer2_chain_ref(nparent);     /* protect nparent, use in lock */
1683         spin_unlock(&above->cst.spin);
1684
1685         hammer2_chain_unlock(oparent);
1686         hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1687         *parentp = nparent;
1688
1689         return (nparent);
1690 }
1691
1692 /*
1693  * Locate any key between key_beg and key_end inclusive.  (*parentp)
1694  * typically points to an inode but can also point to a related indirect
1695  * block and this function will recurse upwards and find the inode again.
1696  *
1697  * WARNING!  THIS DOES NOT RETURN KEYS IN LOGICAL KEY ORDER!  ANY KEY
1698  *           WITHIN THE RANGE CAN BE RETURNED.  HOWEVER, AN ITERATION
1699  *           WHICH PICKS UP WHERE WE LEFT OFF WILL CONTINUE THE SCAN
1700  *           AND ALL IN-RANGE KEYS WILL EVENTUALLY BE RETURNED (NOT
1701  *           NECESSARILY IN ORDER).
1702  *
1703  * (*parentp) must be exclusively locked and referenced and can be an inode
1704  * or an existing indirect block within the inode.
1705  *
1706  * On return (*parentp) will be modified to point at the deepest parent chain
1707  * element encountered during the search, as a helper for an insertion or
1708  * deletion.   The new (*parentp) will be locked and referenced and the old
1709  * will be unlocked and dereferenced (no change if they are both the same).
1710  *
1711  * The matching chain will be returned exclusively locked.  If NOLOCK is
1712  * requested the chain will be returned only referenced.
1713  *
1714  * NULL is returned if no match was found, but (*parentp) will still
1715  * potentially be adjusted.
1716  *
1717  * This function will also recurse up the chain if the key is not within the
1718  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1719  * can simply allow (*parentp) to float inside the loop.
1720  *
1721  * NOTE!  chain->data is not always resolved.  By default it will not be
1722  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1723  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1724  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1725  *        buffer).
1726  */
1727 hammer2_chain_t *
1728 hammer2_chain_lookup(hammer2_chain_t **parentp,
1729                      hammer2_key_t key_beg, hammer2_key_t key_end,
1730                      int flags)
1731 {
1732         hammer2_mount_t *hmp;
1733         hammer2_chain_t *parent;
1734         hammer2_chain_t *chain;
1735         hammer2_chain_t *tmp;
1736         hammer2_blockref_t *base;
1737         hammer2_blockref_t *bref;
1738         hammer2_key_t scan_beg;
1739         hammer2_key_t scan_end;
1740         int count = 0;
1741         int i;
1742         int how_always = HAMMER2_RESOLVE_ALWAYS;
1743         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1744
1745         if (flags & HAMMER2_LOOKUP_ALWAYS)
1746                 how_maybe = how_always;
1747
1748         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1749                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1750                 how_always |= HAMMER2_RESOLVE_SHARED;
1751         }
1752
1753         /*
1754          * Recurse (*parentp) upward if necessary until the parent completely
1755          * encloses the key range or we hit the inode.
1756          */
1757         parent = *parentp;
1758         hmp = parent->hmp;
1759
1760         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1761                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1762                 scan_beg = parent->bref.key;
1763                 scan_end = scan_beg +
1764                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1765                 if (key_beg >= scan_beg && key_end <= scan_end)
1766                         break;
1767                 parent = hammer2_chain_getparent(parentp, how_maybe);
1768         }
1769
1770 again:
1771         /*
1772          * Locate the blockref array.  Currently we do a fully associative
1773          * search through the array.
1774          */
1775         switch(parent->bref.type) {
1776         case HAMMER2_BREF_TYPE_INODE:
1777                 /*
1778                  * Special shortcut for embedded data returns the inode
1779                  * itself.  Callers must detect this condition and access
1780                  * the embedded data (the strategy code does this for us).
1781                  *
1782                  * This is only applicable to regular files and softlinks.
1783                  */
1784                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1785                         if (flags & HAMMER2_LOOKUP_NOLOCK)
1786                                 hammer2_chain_ref(parent);
1787                         else
1788                                 hammer2_chain_lock(parent, how_always);
1789                         return (parent);
1790                 }
1791                 base = &parent->data->ipdata.u.blockset.blockref[0];
1792                 count = HAMMER2_SET_COUNT;
1793                 break;
1794         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1795         case HAMMER2_BREF_TYPE_INDIRECT:
1796                 /*
1797                  * Handle MATCHIND on the parent
1798                  */
1799                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1800                         scan_beg = parent->bref.key;
1801                         scan_end = scan_beg +
1802                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1803                         if (key_beg == scan_beg && key_end == scan_end) {
1804                                 chain = parent;
1805                                 hammer2_chain_lock(chain, how_maybe);
1806                                 goto done;
1807                         }
1808                 }
1809                 /*
1810                  * Optimize indirect blocks in the INITIAL state to avoid
1811                  * I/O.
1812                  */
1813                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1814                         base = NULL;
1815                 } else {
1816                         if (parent->data == NULL)
1817                                 panic("parent->data is NULL");
1818                         base = &parent->data->npdata[0];
1819                 }
1820                 count = parent->bytes / sizeof(hammer2_blockref_t);
1821                 break;
1822         case HAMMER2_BREF_TYPE_VOLUME:
1823                 base = &hmp->voldata.sroot_blockset.blockref[0];
1824                 count = HAMMER2_SET_COUNT;
1825                 break;
1826         case HAMMER2_BREF_TYPE_FREEMAP:
1827                 base = &hmp->voldata.freemap_blockset.blockref[0];
1828                 count = HAMMER2_SET_COUNT;
1829                 break;
1830         default:
1831                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1832                       parent->bref.type);
1833                 base = NULL;    /* safety */
1834                 count = 0;      /* safety */
1835         }
1836
1837         /*
1838          * If the element and key overlap we use the element.
1839          *
1840          * NOTE! Deleted elements are effectively invisible.  Deletions
1841          *       proactively clear the parent bref to the deleted child
1842          *       so we do not try to shadow here to avoid parent updates
1843          *       (which would be difficult since multiple deleted elements
1844          *       might represent different flush synchronization points).
1845          */
1846         bref = NULL;
1847         scan_beg = 0;   /* avoid compiler warning */
1848         scan_end = 0;   /* avoid compiler warning */
1849
1850         for (i = 0; i < count; ++i) {
1851                 tmp = hammer2_chain_find(parent, i);
1852                 if (tmp) {
1853                         if (tmp->flags & HAMMER2_CHAIN_DELETED) {
1854                                 hammer2_chain_drop(tmp);
1855                                 continue;
1856                         }
1857                         bref = &tmp->bref;
1858                         KKASSERT(bref->type != 0);
1859                 } else if (base == NULL || base[i].type == 0) {
1860                         continue;
1861                 } else {
1862                         bref = &base[i];
1863                 }
1864                 scan_beg = bref->key;
1865                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
1866                 if (tmp)
1867                         hammer2_chain_drop(tmp);
1868                 if (key_beg <= scan_end && key_end >= scan_beg)
1869                         break;
1870         }
1871         if (i == count) {
1872                 if (key_beg == key_end)
1873                         return (NULL);
1874                 return (hammer2_chain_next(parentp, NULL,
1875                                            key_beg, key_end, flags));
1876         }
1877
1878         /*
1879          * Acquire the new chain element.  If the chain element is an
1880          * indirect block we must search recursively.
1881          *
1882          * It is possible for the tmp chain above to be removed from
1883          * the RBTREE but the parent lock ensures it would not have been
1884          * destroyed from the media, so the chain_get() code will simply
1885          * reload it from the media in that case.
1886          */
1887         chain = hammer2_chain_get(parent, i, flags);
1888         if (chain == NULL)
1889                 return (NULL);
1890
1891         /*
1892          * If the chain element is an indirect block it becomes the new
1893          * parent and we loop on it.
1894          *
1895          * The parent always has to be locked with at least RESOLVE_MAYBE
1896          * so we can access its data.  It might need a fixup if the caller
1897          * passed incompatible flags.  Be careful not to cause a deadlock
1898          * as a data-load requires an exclusive lock.
1899          *
1900          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1901          * range is within the requested key range we return the indirect
1902          * block and do NOT loop.  This is usually only used to acquire
1903          * freemap nodes.
1904          */
1905         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1906             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1907                 hammer2_chain_unlock(parent);
1908                 *parentp = parent = chain;
1909                 if (flags & HAMMER2_LOOKUP_NOLOCK) {
1910                         hammer2_chain_lock(chain,
1911                                            how_maybe |
1912                                            HAMMER2_RESOLVE_NOREF);
1913                 } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
1914                            chain->data == NULL) {
1915                         hammer2_chain_ref(chain);
1916                         hammer2_chain_unlock(chain);
1917                         hammer2_chain_lock(chain,
1918                                            how_maybe |
1919                                            HAMMER2_RESOLVE_NOREF);
1920                 }
1921                 goto again;
1922         }
1923 done:
1924         /*
1925          * All done, return the chain
1926          */
1927         return (chain);
1928 }
1929
1930 /*
1931  * After having issued a lookup we can iterate all matching keys.
1932  *
1933  * If chain is non-NULL we continue the iteration from just after it's index.
1934  *
1935  * If chain is NULL we assume the parent was exhausted and continue the
1936  * iteration at the next parent.
1937  *
1938  * parent must be locked on entry and remains locked throughout.  chain's
1939  * lock status must match flags.  Chain is always at least referenced.
1940  *
1941  * WARNING!  The MATCHIND flag does not apply to this function.
1942  */
1943 hammer2_chain_t *
1944 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1945                    hammer2_key_t key_beg, hammer2_key_t key_end,
1946                    int flags)
1947 {
1948         hammer2_mount_t *hmp;
1949         hammer2_chain_t *parent;
1950         hammer2_chain_t *tmp;
1951         hammer2_blockref_t *base;
1952         hammer2_blockref_t *bref;
1953         hammer2_key_t scan_beg;
1954         hammer2_key_t scan_end;
1955         int i;
1956         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1957         int count;
1958
1959         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1960                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1961
1962         parent = *parentp;
1963         hmp = parent->hmp;
1964
1965 again:
1966         /*
1967          * Calculate the next index and recalculate the parent if necessary.
1968          */
1969         if (chain) {
1970                 /*
1971                  * Continue iteration within current parent.  If not NULL
1972                  * the passed-in chain may or may not be locked, based on
1973                  * the LOOKUP_NOLOCK flag (passed in as returned from lookup
1974                  * or a prior next).
1975                  */
1976                 i = chain->index + 1;
1977                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1978                         hammer2_chain_drop(chain);
1979                 else
1980                         hammer2_chain_unlock(chain);
1981
1982                 /*
1983                  * Any scan where the lookup returned degenerate data embedded
1984                  * in the inode has an invalid index and must terminate.
1985                  */
1986                 if (chain == parent)
1987                         return(NULL);
1988                 chain = NULL;
1989         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1990                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1991                 /*
1992                  * We reached the end of the iteration.
1993                  */
1994                 return (NULL);
1995         } else {
1996                 /*
1997                  * Continue iteration with next parent unless the current
1998                  * parent covers the range.
1999                  */
2000                 scan_beg = parent->bref.key;
2001                 scan_end = scan_beg +
2002                             ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2003                 if (key_beg >= scan_beg && key_end <= scan_end)
2004                         return (NULL);
2005
2006                 i = parent->index + 1;
2007                 parent = hammer2_chain_getparent(parentp, how_maybe);
2008         }
2009
2010 again2:
2011         /*
2012          * Locate the blockref array.  Currently we do a fully associative
2013          * search through the array.
2014          */
2015         switch(parent->bref.type) {
2016         case HAMMER2_BREF_TYPE_INODE:
2017                 base = &parent->data->ipdata.u.blockset.blockref[0];
2018                 count = HAMMER2_SET_COUNT;
2019                 break;
2020         case HAMMER2_BREF_TYPE_INDIRECT:
2021         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2022                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2023                         base = NULL;
2024                 } else {
2025                         KKASSERT(parent->data != NULL);
2026                         base = &parent->data->npdata[0];
2027                 }
2028                 count = parent->bytes / sizeof(hammer2_blockref_t);
2029                 break;
2030         case HAMMER2_BREF_TYPE_VOLUME:
2031                 base = &hmp->voldata.sroot_blockset.blockref[0];
2032                 count = HAMMER2_SET_COUNT;
2033                 break;
2034         case HAMMER2_BREF_TYPE_FREEMAP:
2035                 base = &hmp->voldata.freemap_blockset.blockref[0];
2036                 count = HAMMER2_SET_COUNT;
2037                 break;
2038         default:
2039                 panic("hammer2_chain_next: unrecognized blockref type: %d",
2040                       parent->bref.type);
2041                 base = NULL;    /* safety */
2042                 count = 0;      /* safety */
2043                 break;
2044         }
2045         KKASSERT(i <= count);
2046
2047         /*
2048          * Look for the key.  If we are unable to find a match and an exact
2049          * match was requested we return NULL.  If a range was requested we
2050          * run hammer2_chain_next() to iterate.
2051          *
2052          * NOTE! Deleted elements are effectively invisible.  Deletions
2053          *       proactively clear the parent bref to the deleted child
2054          *       so we do not try to shadow here to avoid parent updates
2055          *       (which would be difficult since multiple deleted elements
2056          *       might represent different flush synchronization points).
2057          */
2058         bref = NULL;
2059         scan_beg = 0;   /* avoid compiler warning */
2060         scan_end = 0;   /* avoid compiler warning */
2061
2062         while (i < count) {
2063                 tmp = hammer2_chain_find(parent, i);
2064                 if (tmp) {
2065                         if (tmp->flags & HAMMER2_CHAIN_DELETED) {
2066                                 hammer2_chain_drop(tmp);
2067                                 ++i;
2068                                 continue;
2069                         }
2070                         bref = &tmp->bref;
2071                 } else if (base == NULL || base[i].type == 0) {
2072                         ++i;
2073                         continue;
2074                 } else {
2075                         bref = &base[i];
2076                 }
2077                 scan_beg = bref->key;
2078                 scan_end = scan_beg + ((hammer2_key_t)1 << bref->keybits) - 1;
2079                 if (tmp)
2080                         hammer2_chain_drop(tmp);
2081                 if (key_beg <= scan_end && key_end >= scan_beg)
2082                         break;
2083                 ++i;
2084         }
2085
2086         /*
2087          * If we couldn't find a match recurse up a parent to continue the
2088          * search.
2089          */
2090         if (i == count)
2091                 goto again;
2092
2093         /*
2094          * Acquire the new chain element.  If the chain element is an
2095          * indirect block we must search recursively.
2096          */
2097         chain = hammer2_chain_get(parent, i, flags);
2098         if (chain == NULL)
2099                 return (NULL);
2100
2101         /*
2102          * If the chain element is an indirect block it becomes the new
2103          * parent and we loop on it.
2104          *
2105          * The parent always has to be locked with at least RESOLVE_MAYBE
2106          * so we can access its data.  It might need a fixup if the caller
2107          * passed incompatible flags.  Be careful not to cause a deadlock
2108          * as a data-load requires an exclusive lock.
2109          *
2110          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2111          * range is within the requested key range we return the indirect
2112          * block and do NOT loop.  This is usually only used to acquire
2113          * freemap nodes.
2114          */
2115         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2116             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2117                 if ((flags & HAMMER2_LOOKUP_MATCHIND) == 0 ||
2118                     key_beg > scan_beg || key_end < scan_end) {
2119                         hammer2_chain_unlock(parent);
2120                         *parentp = parent = chain;
2121                         chain = NULL;
2122                         if (flags & HAMMER2_LOOKUP_NOLOCK) {
2123                                 hammer2_chain_lock(parent,
2124                                                    how_maybe |
2125                                                    HAMMER2_RESOLVE_NOREF);
2126                         } else if ((flags & HAMMER2_LOOKUP_NODATA) &&
2127                                    parent->data == NULL) {
2128                                 hammer2_chain_ref(parent);
2129                                 hammer2_chain_unlock(parent);
2130                                 hammer2_chain_lock(parent,
2131                                                    how_maybe |
2132                                                    HAMMER2_RESOLVE_NOREF);
2133                         }
2134                         i = 0;
2135                         goto again2;
2136                 }
2137         }
2138
2139         /*
2140          * All done, return chain
2141          */
2142         return (chain);
2143 }
2144
2145 /*
2146  * Loop on parent's children, issuing the callback for each child.
2147  *
2148  * Uses LOOKUP flags.
2149  */
2150 int
2151 hammer2_chain_iterate(hammer2_chain_t *parent,
2152                       int (*callback)(hammer2_chain_t *parent,
2153                                       hammer2_chain_t **chainp,
2154                                       void *arg),
2155                       void *arg, int flags)
2156 {
2157         hammer2_chain_t *chain;
2158         hammer2_blockref_t *base;
2159         int count;
2160         int i;
2161         int res;
2162
2163         /*
2164          * Scan the children (if any)
2165          */
2166         res = 0;
2167         i = 0;
2168         for (;;) {
2169                 /*
2170                  * Calculate the blockref array on each loop in order
2171                  * to allow the callback to temporarily unlock/relock
2172                  * the parent.
2173                  */
2174                 switch(parent->bref.type) {
2175                 case HAMMER2_BREF_TYPE_INODE:
2176                         base = &parent->data->ipdata.u.blockset.blockref[0];
2177                         count = HAMMER2_SET_COUNT;
2178                         break;
2179                 case HAMMER2_BREF_TYPE_INDIRECT:
2180                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2181                         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2182                                 base = NULL;
2183                         } else {
2184                                 KKASSERT(parent->data != NULL);
2185                                 base = &parent->data->npdata[0];
2186                         }
2187                         count = parent->bytes / sizeof(hammer2_blockref_t);
2188                         break;
2189                 case HAMMER2_BREF_TYPE_VOLUME:
2190                         base = &parent->hmp->voldata.sroot_blockset.blockref[0];
2191                         count = HAMMER2_SET_COUNT;
2192                         break;
2193                 case HAMMER2_BREF_TYPE_FREEMAP:
2194                         base = &parent->hmp->voldata.freemap_blockset.blockref[0];
2195                         count = HAMMER2_SET_COUNT;
2196                         break;
2197                 default:
2198                         /*
2199                          * The function allows calls on non-recursive
2200                          * chains and will effectively be a nop() in that
2201                          * case.
2202                          */
2203                         base = NULL;
2204                         count = 0;
2205                         break;
2206                 }
2207
2208                 /*
2209                  * Loop termination
2210                  */
2211                 if (i >= count)
2212                         break;
2213
2214                 /*
2215                  * Lookup the child, properly overloading any elements
2216                  * held in memory.
2217                  *
2218                  * NOTE: Deleted elements cover any underlying base[] entry
2219                  *       (which might not have been zero'd out yet).
2220                  *
2221                  * NOTE: The fact that there can be multiple stacked
2222                  *       deleted elements at the same index is hidden
2223                  *       by hammer2_chain_find().
2224                  */
2225                 chain = hammer2_chain_find(parent, i);
2226                 if (chain) {
2227                         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2228                                 hammer2_chain_drop(chain);
2229                                 ++i;
2230                                 continue;
2231                         }
2232                 } else if (base == NULL || base[i].type == 0) {
2233                         ++i;
2234                         continue;
2235                 }
2236                 if (chain)
2237                         hammer2_chain_drop(chain);
2238                 chain = hammer2_chain_get(parent, i, flags);
2239                 if (chain) {
2240                         res = callback(parent, &chain, arg);
2241                         if (chain) {
2242                                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2243                                         hammer2_chain_drop(chain);
2244                                 else
2245                                         hammer2_chain_unlock(chain);
2246                         }
2247                         if (res < 0)
2248                                 break;
2249                 }
2250                 ++i;
2251         }
2252         return res;
2253 }
2254
2255 /*
2256  * Create and return a new hammer2 system memory structure of the specified
2257  * key, type and size and insert it under (*parentp).  This is a full
2258  * insertion, based on the supplied key/keybits, and may involve creating
2259  * indirect blocks and moving other chains around via delete/duplicate.
2260  *
2261  * (*parentp) must be exclusive locked and may be replaced on return
2262  * depending on how much work the function had to do.
2263  *
2264  * (*chainp) usually starts out NULL and returns the newly created chain,
2265  * but if the caller desires the caller may allocate a disconnected chain
2266  * and pass it in instead.  (It is also possible for the caller to use
2267  * chain_duplicate() to create a disconnected chain, manipulate it, then
2268  * pass it into this function to insert it).
2269  *
2270  * This function should NOT be used to insert INDIRECT blocks.  It is
2271  * typically used to create/insert inodes and data blocks.
2272  *
2273  * Caller must pass-in an exclusively locked parent the new chain is to
2274  * be inserted under, and optionally pass-in a disconnected, exclusively
2275  * locked chain to insert (else we create a new chain).  The function will
2276  * adjust (*parentp) as necessary, create or connect the chain, and
2277  * return an exclusively locked chain in *chainp.
2278  */
2279 int
2280 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2281                      hammer2_chain_t **chainp,
2282                      hammer2_key_t key, int keybits, int type, size_t bytes)
2283 {
2284         hammer2_mount_t *hmp;
2285         hammer2_chain_t *chain;
2286         hammer2_chain_t *child;
2287         hammer2_chain_t *parent = *parentp;
2288         hammer2_chain_core_t *above;
2289         hammer2_blockref_t dummy;
2290         hammer2_blockref_t *base;
2291         int allocated = 0;
2292         int error = 0;
2293         int count;
2294         int i;
2295
2296         above = parent->core;
2297         KKASSERT(ccms_thread_lock_owned(&above->cst));
2298         hmp = parent->hmp;
2299         chain = *chainp;
2300
2301         if (chain == NULL) {
2302                 /*
2303                  * First allocate media space and construct the dummy bref,
2304                  * then allocate the in-memory chain structure.  Set the
2305                  * INITIAL flag for fresh chains.
2306                  */
2307                 bzero(&dummy, sizeof(dummy));
2308                 dummy.type = type;
2309                 dummy.key = key;
2310                 dummy.keybits = keybits;
2311                 dummy.data_off = hammer2_getradix(bytes);
2312                 dummy.methods = parent->bref.methods;
2313                 chain = hammer2_chain_alloc(hmp, trans, &dummy);
2314                 hammer2_chain_core_alloc(chain, NULL);
2315
2316                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2317
2318                 /*
2319                  * Lock the chain manually, chain_lock will load the chain
2320                  * which we do NOT want to do.  (note: chain->refs is set
2321                  * to 1 by chain_alloc() for us, but lockcnt is not).
2322                  */
2323                 chain->lockcnt = 1;
2324                 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2325                 allocated = 1;
2326
2327                 /*
2328                  * We do NOT set INITIAL here (yet).  INITIAL is only
2329                  * used for indirect blocks.
2330                  *
2331                  * Recalculate bytes to reflect the actual media block
2332                  * allocation.
2333                  */
2334                 bytes = (hammer2_off_t)1 <<
2335                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2336                 chain->bytes = bytes;
2337
2338                 switch(type) {
2339                 case HAMMER2_BREF_TYPE_VOLUME:
2340                 case HAMMER2_BREF_TYPE_FREEMAP:
2341                         panic("hammer2_chain_create: called with volume type");
2342                         break;
2343                 case HAMMER2_BREF_TYPE_INODE:
2344                         KKASSERT(bytes == HAMMER2_INODE_BYTES);
2345                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2346                         chain->data = kmalloc(sizeof(chain->data->ipdata),
2347                                               hmp->mchain, M_WAITOK | M_ZERO);
2348                         break;
2349                 case HAMMER2_BREF_TYPE_INDIRECT:
2350                         panic("hammer2_chain_create: cannot be used to"
2351                               "create indirect block");
2352                         break;
2353                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2354                         panic("hammer2_chain_create: cannot be used to"
2355                               "create freemap root or node");
2356                         break;
2357                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2358                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2359                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_EMBEDDED);
2360                         chain->data = kmalloc(sizeof(chain->data->bmdata),
2361                                               hmp->mchain, M_WAITOK | M_ZERO);
2362                         break;
2363                 case HAMMER2_BREF_TYPE_DATA:
2364                 default:
2365                         /* leave chain->data NULL */
2366                         KKASSERT(chain->data == NULL);
2367                         break;
2368                 }
2369         } else {
2370                 /*
2371                  * Potentially update the existing chain's key/keybits.
2372                  *
2373                  * Do NOT mess with the current state of the INITIAL flag.
2374                  */
2375                 chain->bref.key = key;
2376                 chain->bref.keybits = keybits;
2377                 KKASSERT(chain->above == NULL);
2378         }
2379
2380 again:
2381         above = parent->core;
2382
2383         /*
2384          * Locate a free blockref in the parent's array
2385          */
2386         switch(parent->bref.type) {
2387         case HAMMER2_BREF_TYPE_INODE:
2388                 KKASSERT((parent->data->ipdata.op_flags &
2389                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2390                 KKASSERT(parent->data != NULL);
2391                 base = &parent->data->ipdata.u.blockset.blockref[0];
2392                 count = HAMMER2_SET_COUNT;
2393                 break;
2394         case HAMMER2_BREF_TYPE_INDIRECT:
2395         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2396                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2397                         base = NULL;
2398                 } else {
2399                         KKASSERT(parent->data != NULL);
2400                         base = &parent->data->npdata[0];
2401                 }
2402                 count = parent->bytes / sizeof(hammer2_blockref_t);
2403                 break;
2404         case HAMMER2_BREF_TYPE_VOLUME:
2405                 KKASSERT(parent->data != NULL);
2406                 base = &hmp->voldata.sroot_blockset.blockref[0];
2407                 count = HAMMER2_SET_COUNT;
2408                 break;
2409         case HAMMER2_BREF_TYPE_FREEMAP:
2410                 KKASSERT(parent->data != NULL);
2411                 base = &hmp->voldata.freemap_blockset.blockref[0];
2412                 count = HAMMER2_SET_COUNT;
2413                 break;
2414         default:
2415                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2416                       parent->bref.type);
2417                 count = 0;
2418                 break;
2419         }
2420
2421         /*
2422          * Scan for an unallocated bref, also skipping any slots occupied
2423          * by in-memory chain elements that may not yet have been updated
2424          * in the parent's bref array.
2425          *
2426          * We don't have to hold the spinlock to save an empty slot as
2427          * new slots can only transition from empty if the parent is
2428          * locked exclusively.
2429          */
2430         spin_lock(&above->cst.spin);
2431         for (i = 0; i < count; ++i) {
2432                 child = hammer2_chain_find_locked(parent, i);
2433                 if (child) {
2434                         if (child->flags & HAMMER2_CHAIN_DELETED)
2435                                 break;
2436                         continue;
2437                 }
2438                 if (base == NULL)
2439                         break;
2440                 if (base[i].type == 0)
2441                         break;
2442         }
2443         spin_unlock(&above->cst.spin);
2444
2445         /*
2446          * If no free blockref could be found we must create an indirect
2447          * block and move a number of blockrefs into it.  With the parent
2448          * locked we can safely lock each child in order to move it without
2449          * causing a deadlock.
2450          *
2451          * This may return the new indirect block or the old parent depending
2452          * on where the key falls.  NULL is returned on error.
2453          */
2454         if (i == count) {
2455                 hammer2_chain_t *nparent;
2456
2457                 nparent = hammer2_chain_create_indirect(trans, parent,
2458                                                         key, keybits,
2459                                                         type, &error);
2460                 if (nparent == NULL) {
2461                         if (allocated)
2462                                 hammer2_chain_drop(chain);
2463                         chain = NULL;
2464                         goto done;
2465                 }
2466                 if (parent != nparent) {
2467                         hammer2_chain_unlock(parent);
2468                         parent = *parentp = nparent;
2469                 }
2470                 goto again;
2471         }
2472
2473         /*
2474          * Link the chain into its parent.  Later on we will have to set
2475          * the MOVED bit in situations where we don't mark the new chain
2476          * as being modified.
2477          */
2478         if (chain->above != NULL)
2479                 panic("hammer2: hammer2_chain_create: chain already connected");
2480         KKASSERT(chain->above == NULL);
2481         KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2482
2483         chain->above = above;
2484         chain->index = i;
2485         spin_lock(&above->cst.spin);
2486         if (RB_INSERT(hammer2_chain_tree, &above->rbtree, chain))
2487                 panic("hammer2_chain_create: collision");
2488         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2489         spin_unlock(&above->cst.spin);
2490
2491         if (allocated) {
2492                 /*
2493                  * Mark the newly created chain modified.
2494                  *
2495                  * Device buffers are not instantiated for DATA elements
2496                  * as these are handled by logical buffers.
2497                  *
2498                  * Indirect and freemap node indirect blocks are handled
2499                  * by hammer2_chain_create_indirect() and not by this
2500                  * function.
2501                  *
2502                  * Data for all other bref types is expected to be
2503                  * instantiated (INODE, LEAF).
2504                  */
2505                 switch(chain->bref.type) {
2506                 case HAMMER2_BREF_TYPE_DATA:
2507                         hammer2_chain_modify(trans, &chain,
2508                                              HAMMER2_MODIFY_OPTDATA |
2509                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2510                         break;
2511                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2512                 case HAMMER2_BREF_TYPE_INODE:
2513                         hammer2_chain_modify(trans, &chain,
2514                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2515                         break;
2516                 default:
2517                         /*
2518                          * Remaining types are not supported by this function.
2519                          * In particular, INDIRECT and LEAF_NODE types are
2520                          * handled by create_indirect().
2521                          */
2522                         panic("hammer2_chain_create: bad type: %d",
2523                               chain->bref.type);
2524                         /* NOT REACHED */
2525                         break;
2526                 }
2527         } else {
2528                 /*
2529                  * When reconnecting a chain we must set MOVED and setsubmod
2530                  * so the flush recognizes that it must update the bref in
2531                  * the parent.
2532                  */
2533                 if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2534                         hammer2_chain_ref(chain);
2535                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
2536                 }
2537                 hammer2_chain_setsubmod(trans, chain);
2538         }
2539
2540 done:
2541         *chainp = chain;
2542
2543         return (error);
2544 }
2545
2546 /*
2547  * Replace (*chainp) with a duplicate.  The original *chainp is unlocked
2548  * and the replacement will be returned locked.  Both the original and the
2549  * new chain will share the same RBTREE (have the same chain->core), with
2550  * the new chain becoming the 'current' chain (meaning it is the first in
2551  * the linked list at core->chain_first).
2552  *
2553  * If (parent, i) then the new duplicated chain is inserted under the parent
2554  * at the specified index (the parent must not have a ref at that index).
2555  *
2556  * If (NULL, -1) then the new duplicated chain is not inserted anywhere,
2557  * similar to if it had just been chain_alloc()'d (suitable for passing into
2558  * hammer2_chain_create() after this function returns).
2559  *
2560  * NOTE! Duplication is used in order to retain the original topology to
2561  *       support flush synchronization points.  Both the original and the
2562  *       new chain will have the same transaction id and thus the operation
2563  *       appears atomic w/regards to media flushes.
2564  */
2565 static void hammer2_chain_dup_fixup(hammer2_chain_t *ochain,
2566                                     hammer2_chain_t *nchain);
2567
2568 void
2569 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t *parent, int i,
2570                         hammer2_chain_t **chainp, hammer2_blockref_t *bref)
2571 {
2572         hammer2_mount_t *hmp;
2573         hammer2_blockref_t *base;
2574         hammer2_chain_t *ochain;
2575         hammer2_chain_t *nchain;
2576         hammer2_chain_t *scan;
2577         hammer2_chain_core_t *above;
2578         size_t bytes;
2579         int count;
2580         int oflags;
2581         void *odata;
2582
2583         /*
2584          * First create a duplicate of the chain structure, associating
2585          * it with the same core, making it the same size, pointing it
2586          * to the same bref (the same media block).
2587          */
2588         ochain = *chainp;
2589         hmp = ochain->hmp;
2590         if (bref == NULL)
2591                 bref = &ochain->bref;
2592         nchain = hammer2_chain_alloc(hmp, trans, bref);
2593         hammer2_chain_core_alloc(nchain, ochain->core);
2594         bytes = (hammer2_off_t)1 <<
2595                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2596         nchain->bytes = bytes;
2597         nchain->modify_tid = ochain->modify_tid;
2598
2599         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2600         hammer2_chain_dup_fixup(ochain, nchain);
2601
2602         /*
2603          * If parent is not NULL, insert into the parent at the requested
2604          * index.  The newly duplicated chain must be marked MOVED and
2605          * SUBMODIFIED set in its parent(s).
2606          *
2607          * Having both chains locked is extremely important for atomicy.
2608          */
2609         if (parent) {
2610                 /*
2611                  * Locate a free blockref in the parent's array
2612                  */
2613                 above = parent->core;
2614                 KKASSERT(ccms_thread_lock_owned(&above->cst));
2615
2616                 switch(parent->bref.type) {
2617                 case HAMMER2_BREF_TYPE_INODE:
2618                         KKASSERT((parent->data->ipdata.op_flags &
2619                                   HAMMER2_OPFLAG_DIRECTDATA) == 0);
2620                         KKASSERT(parent->data != NULL);
2621                         base = &parent->data->ipdata.u.blockset.blockref[0];
2622                         count = HAMMER2_SET_COUNT;
2623                         break;
2624                 case HAMMER2_BREF_TYPE_INDIRECT:
2625                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2626                         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2627                                 base = NULL;
2628                         } else {
2629                                 KKASSERT(parent->data != NULL);
2630                                 base = &parent->data->npdata[0];
2631                         }
2632                         count = parent->bytes / sizeof(hammer2_blockref_t);
2633                         break;
2634                 case HAMMER2_BREF_TYPE_VOLUME:
2635                         KKASSERT(parent->data != NULL);
2636                         base = &hmp->voldata.sroot_blockset.blockref[0];
2637                         count = HAMMER2_SET_COUNT;
2638                         break;
2639                 case HAMMER2_BREF_TYPE_FREEMAP:
2640                         KKASSERT(parent->data != NULL);
2641                         base = &hmp->voldata.freemap_blockset.blockref[0];
2642                         count = HAMMER2_SET_COUNT;
2643                         break;
2644                 default:
2645                         panic("hammer2_chain_create: unrecognized "
2646                               "blockref type: %d",
2647                               parent->bref.type);
2648                         count = 0;
2649                         break;
2650                 }
2651                 KKASSERT(i >= 0 && i < count);
2652
2653                 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2654                 KKASSERT(parent->refs > 0);
2655
2656                 spin_lock(&above->cst.spin);
2657                 nchain->above = above;
2658                 nchain->index = i;
2659                 scan = hammer2_chain_find_locked(parent, i);
2660                 KKASSERT(base == NULL || base[i].type == 0 ||
2661                          scan == NULL ||
2662                          (scan->flags & HAMMER2_CHAIN_DELETED));
2663                 if (RB_INSERT(hammer2_chain_tree, &above->rbtree,
2664                               nchain)) {
2665                         panic("hammer2_chain_duplicate: collision");
2666                 }
2667                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
2668                 spin_unlock(&above->cst.spin);
2669
2670                 if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2671                         hammer2_chain_ref(nchain);
2672                         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2673                 }
2674                 hammer2_chain_setsubmod(trans, nchain);
2675         }
2676
2677         /*
2678          * We have to unlock ochain to flush any dirty data, asserting the
2679          * case (data == NULL) to catch any extra locks that might have been
2680          * present, then transfer state to nchain.
2681          */
2682         oflags = ochain->flags;
2683         odata = ochain->data;
2684         hammer2_chain_unlock(ochain);
2685         KKASSERT((ochain->flags & HAMMER2_CHAIN_EMBEDDED) ||
2686                  ochain->data == NULL);
2687
2688         if (oflags & HAMMER2_CHAIN_INITIAL)
2689                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2690
2691         /*
2692          * WARNING!  We should never resolve DATA to device buffers
2693          *           (XXX allow it if the caller did?), and since
2694          *           we currently do not have the logical buffer cache
2695          *           buffer in-hand to fix its cached physical offset
2696          *           we also force the modify code to not COW it. XXX
2697          */
2698         if (oflags & HAMMER2_CHAIN_MODIFIED) {
2699                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2700                         hammer2_chain_modify(trans, &nchain,
2701                                              HAMMER2_MODIFY_OPTDATA |
2702                                              HAMMER2_MODIFY_NOREALLOC |
2703                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2704                 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2705                         hammer2_chain_modify(trans, &nchain,
2706                                              HAMMER2_MODIFY_OPTDATA |
2707                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2708                 } else {
2709                         hammer2_chain_modify(trans, &nchain,
2710                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2711                 }
2712                 hammer2_chain_drop(nchain);
2713         } else {
2714                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2715                         hammer2_chain_drop(nchain);
2716                 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2717                         hammer2_chain_drop(nchain);
2718                 } else {
2719                         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_ALWAYS |
2720                                                    HAMMER2_RESOLVE_NOREF);
2721                         hammer2_chain_unlock(nchain);
2722                 }
2723         }
2724         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2725         *chainp = nchain;
2726 }
2727
2728 #if 0
2729                 /*
2730                  * When the chain is in the INITIAL state we must still
2731                  * ensure that a block has been assigned so MOVED processing
2732                  * works as expected.
2733                  */
2734                 KKASSERT (nchain->bref.type != HAMMER2_BREF_TYPE_DATA);
2735                 hammer2_chain_modify(trans, &nchain,
2736                                      HAMMER2_MODIFY_OPTDATA |
2737                                      HAMMER2_MODIFY_ASSERTNOCOPY);
2738
2739
2740         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE |
2741                                    HAMMER2_RESOLVE_NOREF); /* eat excess ref */
2742         hammer2_chain_unlock(nchain);
2743 #endif
2744
2745 /*
2746  * Special in-place delete-duplicate sequence which does not require a
2747  * locked parent.  (*chainp) is marked DELETED and atomically replaced
2748  * with a duplicate.  Atomicy is at the very-fine spin-lock level in
2749  * order to ensure that lookups do not race us.
2750  */
2751 void
2752 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2753                                int flags)
2754 {
2755         hammer2_mount_t *hmp;
2756         hammer2_chain_t *ochain;
2757         hammer2_chain_t *nchain;
2758         hammer2_chain_core_t *above;
2759         size_t bytes;
2760         int oflags;
2761         void *odata;
2762
2763         /*
2764          * First create a duplicate of the chain structure
2765          */
2766         ochain = *chainp;
2767         hmp = ochain->hmp;
2768         nchain = hammer2_chain_alloc(hmp, trans, &ochain->bref);    /* 1 ref */
2769         if (flags & HAMMER2_DELDUP_RECORE)
2770                 hammer2_chain_core_alloc(nchain, NULL);
2771         else
2772                 hammer2_chain_core_alloc(nchain, ochain->core);
2773         above = ochain->above;
2774
2775         bytes = (hammer2_off_t)1 <<
2776                 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2777         nchain->bytes = bytes;
2778         nchain->modify_tid = ochain->modify_tid;
2779         nchain->data_count += ochain->data_count;
2780         nchain->inode_count += ochain->inode_count;
2781
2782         /*
2783          * Lock nchain and insert into ochain's core hierarchy, marking
2784          * ochain DELETED at the same time.  Having both chains locked
2785          * is extremely important for atomicy.
2786          */
2787         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
2788         hammer2_chain_dup_fixup(ochain, nchain);
2789         /* extra ref still present from original allocation */
2790
2791         nchain->index = ochain->index;
2792
2793         spin_lock(&above->cst.spin);
2794         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
2795         ochain->delete_tid = trans->sync_tid;
2796         nchain->above = above;
2797         atomic_set_int(&ochain->flags, HAMMER2_CHAIN_DELETED);
2798         if ((ochain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2799                 hammer2_chain_ref(ochain);
2800                 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_MOVED);
2801         }
2802         if (RB_INSERT(hammer2_chain_tree, &above->rbtree, nchain)) {
2803                 panic("hammer2_chain_delete_duplicate: collision");
2804         }
2805         spin_unlock(&above->cst.spin);
2806
2807         /*
2808          * We have to unlock ochain to flush any dirty data, asserting the
2809          * case (data == NULL) to catch any extra locks that might have been
2810          * present, then transfer state to nchain.
2811          */
2812         oflags = ochain->flags;
2813         odata = ochain->data;
2814         hammer2_chain_unlock(ochain);   /* replacing ochain */
2815         KKASSERT(ochain->bref.type == HAMMER2_BREF_TYPE_INODE ||
2816                  ochain->data == NULL);
2817
2818         if (oflags & HAMMER2_CHAIN_INITIAL)
2819                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_INITIAL);
2820
2821         /*
2822          * WARNING!  We should never resolve DATA to device buffers
2823          *           (XXX allow it if the caller did?), and since
2824          *           we currently do not have the logical buffer cache
2825          *           buffer in-hand to fix its cached physical offset
2826          *           we also force the modify code to not COW it. XXX
2827          */
2828         if (oflags & HAMMER2_CHAIN_MODIFIED) {
2829                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2830                         hammer2_chain_modify(trans, &nchain,
2831                                              HAMMER2_MODIFY_OPTDATA |
2832                                              HAMMER2_MODIFY_NOREALLOC |
2833                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2834                 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2835                         hammer2_chain_modify(trans, &nchain,
2836                                              HAMMER2_MODIFY_OPTDATA |
2837                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2838                 } else {
2839                         hammer2_chain_modify(trans, &nchain,
2840                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2841                 }
2842                 hammer2_chain_drop(nchain);
2843         } else {
2844                 if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2845                         hammer2_chain_drop(nchain);
2846                 } else if (oflags & HAMMER2_CHAIN_INITIAL) {
2847                         hammer2_chain_drop(nchain);
2848                 } else {
2849                         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_ALWAYS |
2850                                                    HAMMER2_RESOLVE_NOREF);
2851                         hammer2_chain_unlock(nchain);
2852                 }
2853         }
2854
2855         /*
2856          * Unconditionally set the MOVED and SUBMODIFIED bit to force
2857          * update of parent bref and indirect blockrefs during flush.
2858          */
2859         if ((nchain->flags & HAMMER2_CHAIN_MOVED) == 0) {
2860                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_MOVED);
2861                 hammer2_chain_ref(nchain);
2862         }
2863         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SUBMODIFIED);
2864         hammer2_chain_setsubmod(trans, nchain);
2865         *chainp = nchain;
2866 }
2867
2868 /*
2869  * Helper function to fixup inodes.  The caller procedure stack may hold
2870  * multiple locks on ochain if it represents an inode, preventing our
2871  * unlock from retiring its state to the buffer cache.
2872  *
2873  * In this situation any attempt to access the buffer cache could result
2874  * either in stale data or a deadlock.  Work around the problem by copying
2875  * the embedded data directly.
2876  */
2877 static
2878 void
2879 hammer2_chain_dup_fixup(hammer2_chain_t *ochain, hammer2_chain_t *nchain)
2880 {
2881         if (ochain->data == NULL)
2882                 return;
2883         switch(ochain->bref.type) {
2884         case HAMMER2_BREF_TYPE_INODE:
2885                 KKASSERT(nchain->data == NULL);
2886                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2887                 nchain->data = kmalloc(sizeof(nchain->data->ipdata),
2888                                        ochain->hmp->mchain, M_WAITOK | M_ZERO);
2889                 nchain->data->ipdata = ochain->data->ipdata;
2890                 break;
2891         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2892                 KKASSERT(nchain->data == NULL);
2893                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_EMBEDDED);
2894                 nchain->data = kmalloc(sizeof(nchain->data->bmdata),
2895                                        ochain->hmp->mchain, M_WAITOK | M_ZERO);
2896                 bcopy(ochain->data->bmdata,
2897                       nchain->data->bmdata,
2898                       sizeof(nchain->data->bmdata));
2899                 break;
2900         default:
2901                 break;
2902         }
2903 }
2904
2905 /*
2906  * Create a snapshot of the specified {parent, chain} with the specified
2907  * label.
2908  *
2909  * (a) We create a duplicate connected to the super-root as the specified
2910  *     label.
2911  *
2912  * (b) We issue a restricted flush using the current transaction on the
2913  *     duplicate.
2914  *
2915  * (c) We disconnect and reallocate the duplicate's core.
2916  */
2917 int
2918 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_inode_t *ip,
2919                        hammer2_ioc_pfs_t *pfs)
2920 {
2921         hammer2_cluster_t *cluster;
2922         hammer2_mount_t *hmp;
2923         hammer2_chain_t *chain;
2924         hammer2_chain_t *nchain;
2925         hammer2_chain_t *parent;
2926         hammer2_inode_data_t *ipdata;
2927         size_t name_len;
2928         hammer2_key_t lhc;
2929         int error;
2930
2931         name_len = strlen(pfs->name);
2932         lhc = hammer2_dirhash(pfs->name, name_len);
2933         cluster = ip->pmp->mount_cluster;
2934         hmp = ip->chain->hmp;
2935         KKASSERT(hmp == cluster->hmp);  /* XXX */
2936
2937         /*
2938          * Create disconnected duplicate
2939          */
2940         KKASSERT((trans->flags & HAMMER2_TRANS_RESTRICTED) == 0);
2941         nchain = ip->chain;
2942         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_MAYBE);
2943         hammer2_chain_duplicate(trans, NULL, -1, &nchain, NULL);
2944         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_RECYCLE |
2945                                        HAMMER2_CHAIN_SNAPSHOT);
2946
2947         /*
2948          * Create named entry in the super-root.
2949          */
2950         parent = hammer2_chain_lookup_init(hmp->schain, 0);
2951         error = 0;
2952         while (error == 0) {
2953                 chain = hammer2_chain_lookup(&parent, lhc, lhc, 0);
2954                 if (chain == NULL)
2955                         break;
2956                 if ((lhc & HAMMER2_DIRHASH_LOMASK) == HAMMER2_DIRHASH_LOMASK)
2957                         error = ENOSPC;
2958                 hammer2_chain_unlock(chain);
2959                 chain = NULL;
2960                 ++lhc;
2961         }
2962         hammer2_chain_create(trans, &parent, &nchain, lhc, 0,
2963                              HAMMER2_BREF_TYPE_INODE,
2964                              HAMMER2_INODE_BYTES);
2965         hammer2_chain_modify(trans, &nchain, HAMMER2_MODIFY_ASSERTNOCOPY);
2966         hammer2_chain_lookup_done(parent);
2967         parent = NULL;  /* safety */
2968
2969         /*
2970          * Name fixup
2971          */
2972         ipdata = &nchain->data->ipdata;
2973         ipdata->name_key = lhc;
2974         ipdata->name_len = name_len;
2975         ksnprintf(ipdata->filename, sizeof(ipdata->filename), "%s", pfs->name);
2976
2977         /*
2978          * Set PFS type, generate a unique filesystem id, and generate
2979          * a cluster id.  Use the same clid when snapshotting a PFS root,
2980          * which theoretically allows the snapshot to be used as part of
2981          * the same cluster (perhaps as a cache).
2982          */
2983         ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
2984         kern_uuidgen(&ipdata->pfs_fsid, 1);
2985         if (ip->chain == cluster->rchain)
2986                 ipdata->pfs_clid = ip->chain->data->ipdata.pfs_clid;
2987         else
2988                 kern_uuidgen(&ipdata->pfs_clid, 1);
2989
2990         /*
2991          * Issue a restricted flush of the snapshot.  This is a synchronous
2992          * operation.
2993          */
2994         trans->flags |= HAMMER2_TRANS_RESTRICTED;
2995         kprintf("SNAPSHOTA\n");
2996         tsleep(trans, 0, "snapslp", hz*4);
2997         kprintf("SNAPSHOTB\n");
2998         hammer2_chain_flush(trans, nchain);
2999         trans->flags &= ~HAMMER2_TRANS_RESTRICTED;
3000
3001 #if 0
3002         /*
3003          * Remove the link b/c nchain is a snapshot and snapshots don't
3004          * follow CHAIN_DELETED semantics ?
3005          */
3006         chain = ip->chain;
3007
3008
3009         KKASSERT(chain->duplink == nchain);
3010         KKASSERT(chain->core == nchain->core);
3011         KKASSERT(nchain->refs >= 2);
3012         chain->duplink = nchain->duplink;
3013         atomic_clear_int(&nchain->flags, HAMMER2_CHAIN_DUPTARGET);
3014         hammer2_chain_drop(nchain);
3015 #endif
3016
3017         kprintf("snapshot %s nchain->refs %d nchain->flags %08x\n",
3018                 pfs->name, nchain->refs, nchain->flags);
3019         hammer2_chain_unlock(nchain);
3020
3021         return (error);
3022 }
3023
3024 /*
3025  * Create an indirect block that covers one or more of the elements in the
3026  * current parent.  Either returns the existing parent with no locking or
3027  * ref changes or returns the new indirect block locked and referenced
3028  * and leaving the original parent lock/ref intact as well.
3029  *
3030  * If an error occurs, NULL is returned and *errorp is set to the error.
3031  *
3032  * The returned chain depends on where the specified key falls.
3033  *
3034  * The key/keybits for the indirect mode only needs to follow three rules:
3035  *
3036  * (1) That all elements underneath it fit within its key space and
3037  *
3038  * (2) That all elements outside it are outside its key space.
3039  *
3040  * (3) When creating the new indirect block any elements in the current
3041  *     parent that fit within the new indirect block's keyspace must be
3042  *     moved into the new indirect block.
3043  *
3044  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3045  *     keyspace the the current parent, but lookup/iteration rules will
3046  *     ensure (and must ensure) that rule (2) for all parents leading up
3047  *     to the nearest inode or the root volume header is adhered to.  This
3048  *     is accomplished by always recursing through matching keyspaces in
3049  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3050  *
3051  * The current implementation calculates the current worst-case keyspace by
3052  * iterating the current parent and then divides it into two halves, choosing
3053  * whichever half has the most elements (not necessarily the half containing
3054  * the requested key).
3055  *
3056  * We can also opt to use the half with the least number of elements.  This
3057  * causes lower-numbered keys (aka logical file offsets) to recurse through
3058  * fewer indirect blocks and higher-numbered keys to recurse through more.
3059  * This also has the risk of not moving enough elements to the new indirect
3060  * block and being forced to create several indirect blocks before the element
3061  * can be inserted.
3062  *
3063  * Must be called with an exclusively locked parent.
3064  */
3065 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3066                                 hammer2_key_t *keyp, int keybits,
3067                                 hammer2_blockref_t *base, int count);
3068 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3069                                 hammer2_key_t *keyp, int keybits,
3070                                 hammer2_blockref_t *base, int count);
3071 static
3072 hammer2_chain_t *
3073 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3074                               hammer2_key_t create_key, int create_bits,
3075                               int for_type, int *errorp)
3076 {
3077         hammer2_mount_t *hmp;
3078         hammer2_chain_core_t *above;
3079         hammer2_chain_core_t *icore;
3080         hammer2_blockref_t *base;
3081         hammer2_blockref_t *bref;
3082         hammer2_chain_t *chain;
3083         hammer2_chain_t *child;
3084         hammer2_chain_t *ichain;
3085         hammer2_chain_t dummy;
3086         hammer2_key_t key = create_key;
3087         int keybits = create_bits;
3088         int count;
3089         int nbytes;
3090         int i;
3091
3092         /*
3093          * Calculate the base blockref pointer or NULL if the chain
3094          * is known to be empty.  We need to calculate the array count
3095          * for RB lookups either way.
3096          */
3097         hmp = parent->hmp;
3098         *errorp = 0;
3099         KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3100         above = parent->core;
3101
3102         /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3103         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3104                 base = NULL;
3105
3106                 switch(parent->bref.type) {
3107                 case HAMMER2_BREF_TYPE_INODE:
3108                         count = HAMMER2_SET_COUNT;
3109                         break;
3110                 case HAMMER2_BREF_TYPE_INDIRECT:
3111                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3112                         count = parent->bytes / sizeof(hammer2_blockref_t);
3113                         break;
3114                 case HAMMER2_BREF_TYPE_VOLUME:
3115                         count = HAMMER2_SET_COUNT;
3116                         break;
3117                 case HAMMER2_BREF_TYPE_FREEMAP:
3118                         count = HAMMER2_SET_COUNT;
3119                         break;
3120                 default:
3121                         panic("hammer2_chain_create_indirect: "
3122                               "unrecognized blockref type: %d",
3123                               parent->bref.type);
3124                         count = 0;
3125                         break;
3126                 }
3127         } else {
3128                 switch(parent->bref.type) {
3129                 case HAMMER2_BREF_TYPE_INODE:
3130                         base = &parent->data->ipdata.u.blockset.blockref[0];
3131                         count = HAMMER2_SET_COUNT;
3132                         break;
3133                 case HAMMER2_BREF_TYPE_INDIRECT:
3134                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3135                         base = &parent->data->npdata[0];
3136                         count = parent->bytes / sizeof(hammer2_blockref_t);
3137                         break;
3138                 case HAMMER2_BREF_TYPE_VOLUME:
3139                         base = &hmp->voldata.sroot_blockset.blockref[0];
3140                         count = HAMMER2_SET_COUNT;
3141                         break;
3142                 case HAMMER2_BREF_TYPE_FREEMAP:
3143                         base = &hmp->voldata.freemap_blockset.blockref[0];
3144                         count = HAMMER2_SET_COUNT;
3145                         break;
3146                 default:
3147                         panic("hammer2_chain_create_indirect: "
3148                               "unrecognized blockref type: %d",
3149                               parent->bref.type);
3150                         count = 0;
3151                         break;
3152                 }
3153         }
3154
3155         /*
3156          * dummy used in later chain allocation (no longer used for lookups).
3157          */
3158         bzero(&dummy, sizeof(dummy));
3159         dummy.delete_tid = HAMMER2_MAX_TID;
3160
3161         /*
3162          * When creating an indirect block for a freemap node or leaf
3163          * the key/keybits must be fitted to static radix levels because
3164          * particular radix levels use particular reserved blocks in the
3165          * related zone.
3166          *
3167          * This routine calculates the key/radix of the indirect block
3168          * we need to create, and whether it is on the high-side or the
3169          * low-side.
3170          */
3171         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3172             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3173                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3174                                                        base, count);
3175         } else {
3176                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3177                                                       base, count);
3178         }
3179
3180         /*
3181          * Normalize the key for the radix being represented, keeping the
3182          * high bits and throwing away the low bits.
3183          */
3184         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3185
3186         /*
3187          * How big should our new indirect block be?  It has to be at least
3188          * as large as its parent.
3189          */
3190         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3191                 nbytes = HAMMER2_IND_BYTES_MIN;
3192         else
3193                 nbytes = HAMMER2_IND_BYTES_MAX;
3194         if (nbytes < count * sizeof(hammer2_blockref_t))
3195                 nbytes = count * sizeof(hammer2_blockref_t);
3196
3197         /*
3198          * Ok, create our new indirect block
3199          */
3200         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3201             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3202                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3203         } else {
3204                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3205         }
3206         dummy.bref.key = key;
3207         dummy.bref.keybits = keybits;
3208         dummy.bref.data_off = hammer2_getradix(nbytes);
3209         dummy.bref.methods = parent->bref.methods;
3210
3211         ichain = hammer2_chain_alloc(hmp, trans, &dummy.bref);
3212         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3213         hammer2_chain_core_alloc(ichain, NULL);
3214         icore = ichain->core;
3215         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3216         hammer2_chain_drop(ichain);     /* excess ref from alloc */
3217
3218         /*
3219          * We have to mark it modified to allocate its block, but use
3220          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3221          * it won't be acted upon by the flush code.
3222          *
3223          * XXX leave the node unmodified, depend on the SUBMODIFIED
3224          * flush to assign and modify parent blocks.
3225          */
3226         hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3227
3228         /*
3229          * Iterate the original parent and move the matching brefs into
3230          * the new indirect block.
3231          *
3232          * At the same time locate an empty slot (or what will become an
3233          * empty slot) and assign the new indirect block to that slot.
3234          *
3235          * XXX handle flushes.
3236          */
3237         spin_lock(&above->cst.spin);
3238         for (i = 0; i < count; ++i) {
3239                 /*
3240                  * For keying purposes access the bref from the media or
3241                  * from our in-memory cache.  In cases where the in-memory
3242                  * cache overrides the media the keyrefs will be the same
3243                  * anyway so we can avoid checking the cache when the media
3244                  * has a key.
3245                  */
3246                 child = hammer2_chain_find_locked(parent, i);
3247                 if (child) {
3248                         if (child->flags & HAMMER2_CHAIN_DELETED) {
3249                                 if (ichain->index < 0)
3250                                         ichain->index = i;
3251                                 continue;
3252                         }
3253                         bref = &child->bref;
3254                 } else if (base && base[i].type) {
3255                         bref = &base[i];
3256                 } else {
3257                         if (ichain->index < 0)
3258                                 ichain->index = i;
3259                         continue;
3260                 }
3261
3262                 /*
3263                  * Skip keys that are not within the key/radix of the new
3264                  * indirect block.  They stay in the parent.
3265                  */
3266                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3267                     (key ^ bref->key)) != 0) {
3268                         continue;
3269                 }
3270
3271                 /*
3272                  * This element is being moved from the parent, its slot
3273                  * is available for our new indirect block.
3274                  */
3275                 if (ichain->index < 0)
3276                         ichain->index = i;
3277
3278                 /*
3279                  * Load the new indirect block by acquiring or allocating
3280                  * the related chain entries, then move them to the new
3281                  * parent (ichain) by deleting them from their old location
3282                  * and inserting a duplicate of the chain and any modified
3283                  * sub-chain in the new location.
3284                  *
3285                  * We must set MOVED in the chain being duplicated and
3286                  * SUBMODIFIED in the parent(s) so the flush code knows
3287                  * what is going on.  The latter is done after the loop.
3288                  *
3289                  * WARNING! above->cst.spin must be held when parent is
3290                  *          modified, even though we own the full blown lock,
3291                  *          to deal with setsubmod and rename races.
3292                  *          (XXX remove this req).
3293                  */
3294                 spin_unlock(&above->cst.spin);
3295                 chain = hammer2_chain_get(parent, i, HAMMER2_LOOKUP_NODATA);
3296                 hammer2_chain_delete(trans, chain, HAMMER2_DELETE_WILLDUP);
3297                 hammer2_chain_duplicate(trans, ichain, i, &chain, NULL);
3298                 hammer2_chain_unlock(chain);
3299                 KKASSERT(parent->refs > 0);
3300                 chain = NULL;
3301                 spin_lock(&above->cst.spin);
3302         }
3303         spin_unlock(&above->cst.spin);
3304
3305         /*
3306          * Insert the new indirect block into the parent now that we've
3307          * cleared out some entries in the parent.  We calculated a good
3308          * insertion index in the loop above (ichain->index).
3309          *
3310          * We don't have to set MOVED here because we mark ichain modified
3311          * down below (so the normal modified -> flush -> set-moved sequence
3312          * applies).
3313          *
3314          * The insertion shouldn't race as this is a completely new block
3315          * and the parent is locked.
3316          */
3317         if (ichain->index < 0)
3318                 kprintf("indirect parent %p count %d key %016jx/%d\n",
3319                         parent, count, (intmax_t)key, keybits);
3320         KKASSERT(ichain->index >= 0);
3321         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3322         spin_lock(&above->cst.spin);
3323         if (RB_INSERT(hammer2_chain_tree, &above->rbtree, ichain))
3324                 panic("hammer2_chain_create_indirect: ichain insertion");
3325         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_ONRBTREE);
3326         ichain->above = above;
3327         spin_unlock(&above->cst.spin);
3328
3329         /*
3330          * Mark the new indirect block modified after insertion, which
3331          * will propagate up through parent all the way to the root and
3332          * also allocate the physical block in ichain for our caller,
3333          * and assign ichain->data to a pre-zero'd space (because there
3334          * is not prior data to copy into it).
3335          *
3336          * We have to set SUBMODIFIED in ichain's flags manually so the
3337          * flusher knows it has to recurse through it to get to all of
3338          * our moved blocks, then call setsubmod() to set the bit
3339          * recursively.
3340          */
3341         /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3342         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_SUBMODIFIED);
3343         hammer2_chain_setsubmod(trans, ichain);
3344
3345         /*
3346          * Figure out what to return.
3347          */
3348         if (~(((hammer2_key_t)1 << keybits) - 1) &
3349                    (create_key ^ key)) {
3350                 /*
3351                  * Key being created is outside the key range,
3352                  * return the original parent.
3353                  */
3354                 hammer2_chain_unlock(ichain);
3355         } else {
3356                 /*
3357                  * Otherwise its in the range, return the new parent.
3358                  * (leave both the new and old parent locked).
3359                  */
3360                 parent = ichain;
3361         }
3362
3363         return(parent);
3364 }
3365
3366 /*
3367  * Calculate the keybits and highside/lowside of the freemap node the
3368  * caller is creating.
3369  *
3370  * This routine will specify the next higher-level freemap key/radix
3371  * representing the lowest-ordered set.  By doing so, eventually all
3372  * low-ordered sets will be moved one level down.
3373  *
3374  * We have to be careful here because the freemap reserves a limited
3375  * number of blocks for a limited number of levels.  So we can't just
3376  * push indiscriminately.
3377  */
3378 int
3379 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3380                              int keybits, hammer2_blockref_t *base, int count)
3381 {
3382         hammer2_chain_core_t *above;
3383         hammer2_chain_t *child;
3384         hammer2_blockref_t *bref;
3385         hammer2_key_t key;
3386         int locount;
3387         int hicount;
3388         int i;
3389
3390         key = *keyp;
3391         above = parent->core;
3392         locount = 0;
3393         hicount = 0;
3394         keybits = 64;
3395
3396         /*
3397          * Calculate the range of keys in the array being careful to skip
3398          * slots which are overridden with a deletion.
3399          */
3400         spin_lock(&above->cst.spin);
3401         for (i = 0; i < count; ++i) {
3402                 child = hammer2_chain_find_locked(parent, i);
3403                 if (child) {
3404                         if (child->flags & HAMMER2_CHAIN_DELETED)
3405                                 continue;
3406                         bref = &child->bref;
3407                 } else if (base && base[i].type) {
3408                         bref = &base[i];
3409                 } else {
3410                         continue;
3411                 }
3412
3413                 if (keybits > bref->keybits) {
3414                         key = bref->key;
3415                         keybits = bref->keybits;
3416                 } else if (keybits == bref->keybits && bref->key < key) {
3417                         key = bref->key;
3418                 }
3419         }
3420         spin_unlock(&above->cst.spin);
3421
3422         /*
3423          * Return the keybits for a higher-level FREEMAP_NODE covering
3424          * this node.
3425          */
3426         switch(keybits) {
3427         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3428                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3429                 break;
3430         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3431                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3432                 break;
3433         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3434                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3435                 break;
3436         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3437                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3438                 break;
3439         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3440                 panic("hammer2_chain_indkey_freemap: level too high");
3441                 break;
3442         default:
3443                 panic("hammer2_chain_indkey_freemap: bad radix");
3444                 break;
3445         }
3446         *keyp = key;
3447
3448         return (keybits);
3449 }
3450
3451 /*
3452  * Calculate the keybits and highside/lowside of the indirect block the
3453  * caller is creating.
3454  */
3455 static int
3456 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3457                             int keybits, hammer2_blockref_t *base, int count)
3458 {
3459         hammer2_chain_core_t *above;
3460         hammer2_chain_t *child;
3461         hammer2_blockref_t *bref;
3462         hammer2_key_t key;
3463         int nkeybits;
3464         int locount;
3465         int hicount;
3466         int i;
3467
3468         key = *keyp;
3469         above = parent->core;
3470         locount = 0;
3471         hicount = 0;
3472
3473         /*
3474          * Calculate the range of keys in the array being careful to skip
3475          * slots which are overridden with a deletion.  Once the scan
3476          * completes we will cut the key range in half and shift half the
3477          * range into the new indirect block.
3478          */
3479         spin_lock(&above->cst.spin);
3480         for (i = 0; i < count; ++i) {
3481                 child = hammer2_chain_find_locked(parent, i);
3482                 if (child) {
3483                         if (child->flags & HAMMER2_CHAIN_DELETED)
3484                                 continue;
3485                         bref = &child->bref;
3486                 } else if (base && base[i].type) {
3487                         bref = &base[i];
3488                 } else {
3489                         continue;
3490                 }
3491
3492                 /*
3493                  * Expand our calculated key range (key, keybits) to fit
3494                  * the scanned key.  nkeybits represents the full range
3495                  * that we will later cut in half (two halves @ nkeybits - 1).
3496                  */
3497                 nkeybits = keybits;
3498                 if (nkeybits < bref->keybits) {
3499                         if (bref->keybits > 64) {
3500                                 kprintf("bad bref index %d chain %p bref %p\n",
3501                                         i, child, bref);
3502                                 Debugger("fubar");
3503                         }
3504                         nkeybits = bref->keybits;
3505                 }
3506                 while (nkeybits < 64 &&
3507                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3508                         (key ^ bref->key)) != 0) {
3509                         ++nkeybits;
3510                 }
3511
3512                 /*
3513                  * If the new key range is larger we have to determine
3514                  * which side of the new key range the existing keys fall
3515                  * under by checking the high bit, then collapsing the
3516                  * locount into the hicount or vise-versa.
3517                  */
3518                 if (keybits != nkeybits) {
3519                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3520                                 hicount += locount;
3521                                 locount = 0;
3522                         } else {
3523                                 locount += hicount;
3524                                 hicount = 0;
3525                         }
3526                         keybits = nkeybits;
3527                 }
3528
3529                 /*
3530                  * The newly scanned key will be in the lower half or the
3531                  * higher half of the (new) key range.
3532                  */
3533                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3534                         ++hicount;
3535                 else
3536                         ++locount;
3537         }
3538         spin_unlock(&above->cst.spin);
3539         bref = NULL;    /* now invalid (safety) */
3540
3541         /*
3542          * Adjust keybits to represent half of the full range calculated
3543          * above (radix 63 max)
3544          */
3545         --keybits;
3546
3547         /*
3548          * Select whichever half contains the most elements.  Theoretically
3549          * we can select either side as long as it contains at least one
3550          * element (in order to ensure that a free slot is present to hold
3551          * the indirect block).
3552          */
3553         if (hammer2_indirect_optimize) {
3554                 /*
3555                  * Insert node for least number of keys, this will arrange
3556                  * the first few blocks of a large file or the first few
3557                  * inodes in a directory with fewer indirect blocks when
3558                  * created linearly.
3559                  */
3560                 if (hicount < locount && hicount != 0)
3561                         key |= (hammer2_key_t)1 << keybits;
3562                 else
3563                         key &= ~(hammer2_key_t)1 << keybits;
3564         } else {
3565                 /*
3566                  * Insert node for most number of keys, best for heavily
3567                  * fragmented files.
3568                  */
3569                 if (hicount > locount)
3570                         key |= (hammer2_key_t)1 << keybits;
3571                 else
3572                         key &= ~(hammer2_key_t)1 << keybits;
3573         }
3574         *keyp = key;
3575
3576         return (keybits);
3577 }
3578
3579 /*
3580  * Sets CHAIN_DELETED and CHAIN_MOVED in the chain being deleted and
3581  * set chain->delete_tid.
3582  *
3583  * This function does NOT generate a modification to the parent.  It
3584  * would be nearly impossible to figure out which parent to modify anyway.
3585  * Such modifications are handled by the flush code and are properly merged
3586  * using the flush synchronization point.
3587  *
3588  * The find/get code will properly overload the RBTREE check on top of
3589  * the bref check to detect deleted entries.
3590  *
3591  * This function is NOT recursive.  Any entity already pushed into the
3592  * chain (such as an inode) may still need visibility into its contents,
3593  * as well as the ability to read and modify the contents.  For example,
3594  * for an unlinked file which is still open.
3595  *
3596  * NOTE: This function does NOT set chain->modify_tid, allowing future
3597  *       code to distinguish between live and deleted chains by testing
3598  *       sync_tid.
3599  *
3600  * NOTE: Deletions normally do not occur in the middle of a duplication
3601  *       chain but we use a trick for hardlink migration that refactors
3602  *       the originating inode without deleting it, so we make no assumptions
3603  *       here.
3604  */
3605 void
3606 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3607 {
3608         KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3609
3610         /*
3611          * Nothing to do if already marked.
3612          */
3613         if (chain->flags & HAMMER2_CHAIN_DELETED)
3614                 return;
3615
3616         /*
3617          * We must set MOVED along with DELETED for the flush code to
3618          * recognize the operation and properly disconnect the chain
3619          * in-memory.
3620          *
3621          * The setting of DELETED causes finds, lookups, and _next iterations
3622          * to no longer recognize the chain.  RB_SCAN()s will still have
3623          * visibility (needed for flush serialization points).
3624          *
3625          * We need the spinlock on the core whos RBTREE contains chain
3626          * to protect against races.
3627          */
3628         spin_lock(&chain->above->cst.spin);
3629         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3630         if ((chain->flags & HAMMER2_CHAIN_MOVED) == 0) {
3631                 hammer2_chain_ref(chain);
3632                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MOVED);
3633         }
3634         chain->delete_tid = trans->sync_tid;
3635         spin_unlock(&chain->above->cst.spin);
3636
3637         /*
3638          * Mark the underlying block as possibly being free unless WILLDUP
3639          * is set.  Duplication can occur in many situations, particularly
3640          * when chains are moved to indirect blocks.
3641          */
3642         if ((flags & HAMMER2_DELETE_WILLDUP) == 0)
3643                 hammer2_freemap_free(trans, chain->hmp, &chain->bref, 0);
3644         hammer2_chain_setsubmod(trans, chain);
3645 }
3646
3647 void
3648 hammer2_chain_wait(hammer2_chain_t *chain)
3649 {
3650         tsleep(chain, 0, "chnflw", 1);
3651 }
3652
3653 static
3654 void
3655 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
3656 {
3657         long *counterp;
3658
3659         switch(bref->type) {
3660         case HAMMER2_BREF_TYPE_DATA:
3661                 counterp = &hammer2_iod_file_read;
3662                 break;
3663         case HAMMER2_BREF_TYPE_INODE:
3664                 counterp = &hammer2_iod_meta_read;
3665                 break;
3666         case HAMMER2_BREF_TYPE_INDIRECT:
3667                 counterp = &hammer2_iod_indr_read;
3668                 break;
3669         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3670         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3671                 counterp = &hammer2_iod_fmap_read;
3672                 break;
3673         default:
3674                 counterp = &hammer2_iod_volu_read;
3675                 break;
3676         }
3677         *counterp += bytes;
3678 }