hammer2 - Fix upgrade deadlock
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2015 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  * and 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 structure.
38  *
39  * Chains are the in-memory version on media objects (volume header, inodes,
40  * indirect blocks, data blocks, etc).  Chains represent a portion of the
41  * HAMMER2 topology.
42  *
43  * Chains are no-longer delete-duplicated.  Instead, the original in-memory
44  * chain will be moved along with its block reference (e.g. for things like
45  * renames, hardlink operations, modifications, etc), and will be indexed
46  * on a secondary list for flush handling instead of propagating a flag
47  * upward to the root.
48  *
49  * Concurrent front-end operations can still run against backend flushes
50  * as long as they do not cross the current flush boundary.  An operation
51  * running above the current flush (in areas not yet flushed) can become
52  * part of the current flush while ano peration running below the current
53  * flush can become part of the next flush.
54  */
55 #include <sys/cdefs.h>
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/types.h>
59 #include <sys/lock.h>
60 #include <sys/kern_syscall.h>
61 #include <sys/uuid.h>
62
63 #include <crypto/sha2/sha2.h>
64
65 #include "hammer2.h"
66
67 static int hammer2_indirect_optimize;   /* XXX SYSCTL */
68
69 static hammer2_chain_t *hammer2_chain_create_indirect(
70                 hammer2_chain_t *parent,
71                 hammer2_key_t key, int keybits,
72                 hammer2_tid_t mtid, int for_type, int *errorp);
73 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain,
74                 int lastdrop);
75 static hammer2_chain_t *hammer2_combined_find(
76                 hammer2_chain_t *parent,
77                 hammer2_blockref_t *base, int count,
78                 int *cache_indexp, hammer2_key_t *key_nextp,
79                 hammer2_key_t key_beg, hammer2_key_t key_end,
80                 hammer2_blockref_t **bresp);
81
82 /*
83  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
84  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
85  * dbtree or to dbq.
86  *
87  * Chains in delete-duplicate sequences can always iterate through core_entry
88  * to locate the live version of the chain.
89  */
90 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
91
92 extern int h2timer[32];
93 extern int h2last;
94 extern int h2lid;
95
96 #define TIMER(which)    do {                            \
97         if (h2last)                                     \
98                 h2timer[h2lid] += (int)(ticks - h2last);\
99         h2last = ticks;                                 \
100         h2lid = which;                                  \
101 } while(0)
102
103 int
104 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
105 {
106         hammer2_key_t c1_beg;
107         hammer2_key_t c1_end;
108         hammer2_key_t c2_beg;
109         hammer2_key_t c2_end;
110
111         /*
112          * Compare chains.  Overlaps are not supposed to happen and catch
113          * any software issues early we count overlaps as a match.
114          */
115         c1_beg = chain1->bref.key;
116         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
117         c2_beg = chain2->bref.key;
118         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
119
120         if (c1_end < c2_beg)    /* fully to the left */
121                 return(-1);
122         if (c1_beg > c2_end)    /* fully to the right */
123                 return(1);
124         return(0);              /* overlap (must not cross edge boundary) */
125 }
126
127 static __inline
128 int
129 hammer2_isclusterable(hammer2_chain_t *chain)
130 {
131         if (hammer2_cluster_enable) {
132                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
133                     chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
134                     chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
135                         return(1);
136                 }
137         }
138         return(0);
139 }
140
141 /*
142  * Make a chain visible to the flusher.  The flusher needs to be able to
143  * do flushes of subdirectory chains or single files so it does a top-down
144  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
145  * or UPDATE chains and flushes back up the chain to the volume root.
146  *
147  * This routine sets ONFLUSH upward until it hits the volume root.  For
148  * simplicity we ignore PFSROOT boundaries whos rules can be complex.
149  * Extra ONFLUSH flagging doesn't hurt the filesystem.
150  */
151 void
152 hammer2_chain_setflush(hammer2_chain_t *chain)
153 {
154         hammer2_chain_t *parent;
155
156         if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
157                 hammer2_spin_sh(&chain->core.spin);
158                 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
159                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
160                         if ((parent = chain->parent) == NULL)
161                                 break;
162                         hammer2_spin_sh(&parent->core.spin);
163                         hammer2_spin_unsh(&chain->core.spin);
164                         chain = parent;
165                 }
166                 hammer2_spin_unsh(&chain->core.spin);
167         }
168 }
169
170 /*
171  * Allocate a new disconnected chain element representing the specified
172  * bref.  chain->refs is set to 1 and the passed bref is copied to
173  * chain->bref.  chain->bytes is derived from the bref.
174  *
175  * chain->pmp inherits pmp unless the chain is an inode (other than the
176  * super-root inode).
177  *
178  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
179  */
180 hammer2_chain_t *
181 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
182                     hammer2_blockref_t *bref)
183 {
184         hammer2_chain_t *chain;
185         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
186
187         atomic_add_long(&hammer2_chain_allocs, 1);
188
189         /*
190          * Construct the appropriate system structure.
191          */
192         switch(bref->type) {
193         case HAMMER2_BREF_TYPE_INODE:
194         case HAMMER2_BREF_TYPE_INDIRECT:
195         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
196         case HAMMER2_BREF_TYPE_DATA:
197         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
198                 /*
199                  * Chain's are really only associated with the hmp but we
200                  * maintain a pmp association for per-mount memory tracking
201                  * purposes.  The pmp can be NULL.
202                  */
203                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
204                 break;
205         case HAMMER2_BREF_TYPE_VOLUME:
206         case HAMMER2_BREF_TYPE_FREEMAP:
207                 /*
208                  * Only hammer2_chain_bulksnap() calls this function with these
209                  * types.
210                  */
211                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
212                 break;
213         default:
214                 chain = NULL;
215                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
216                       bref->type);
217         }
218
219         /*
220          * Initialize the new chain structure.  pmp must be set to NULL for
221          * chains belonging to the super-root topology of a device mount.
222          */
223         if (pmp == hmp->spmp)
224                 chain->pmp = NULL;
225         else
226                 chain->pmp = pmp;
227         chain->hmp = hmp;
228         chain->bref = *bref;
229         chain->bytes = bytes;
230         chain->refs = 1;
231         chain->flags = HAMMER2_CHAIN_ALLOCATED;
232
233         /*
234          * Set the PFS boundary flag if this chain represents a PFS root.
235          */
236         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
237                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
238         hammer2_chain_core_init(chain);
239
240         return (chain);
241 }
242
243 /*
244  * Initialize a chain's core structure.  This structure used to be allocated
245  * but is now embedded.
246  *
247  * The core is not locked.  No additional refs on the chain are made.
248  * (trans) must not be NULL if (core) is not NULL.
249  */
250 void
251 hammer2_chain_core_init(hammer2_chain_t *chain)
252 {
253         /*
254          * Fresh core under nchain (no multi-homing of ochain's
255          * sub-tree).
256          */
257         RB_INIT(&chain->core.rbtree);   /* live chains */
258         hammer2_mtx_init(&chain->lock, "h2chain");
259 }
260
261 /*
262  * Add a reference to a chain element, preventing its destruction.
263  *
264  * (can be called with spinlock held)
265  */
266 void
267 hammer2_chain_ref(hammer2_chain_t *chain)
268 {
269         if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
270                 /*
271                  * 0->non-zero transition must ensure that chain is removed
272                  * from the LRU list.
273                  *
274                  * NOTE: Already holding lru_spin here so we cannot call
275                  *       hammer2_chain_ref() to get it off lru_list, do
276                  *       it manually.
277                  */
278                 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
279                         hammer2_pfs_t *pmp = chain->pmp;
280                         hammer2_spin_ex(&pmp->lru_spin);
281                         if (chain->flags & HAMMER2_CHAIN_ONLRU) {
282                                 atomic_add_int(&pmp->lru_count, -1);
283                                 atomic_clear_int(&chain->flags,
284                                                  HAMMER2_CHAIN_ONLRU);
285                                 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
286                         }
287                         hammer2_spin_unex(&pmp->lru_spin);
288                 }
289         }
290 #if 0
291         kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
292         print_backtrace(8);
293 #endif
294 }
295
296 /*
297  * Insert the chain in the core rbtree.
298  *
299  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
300  * chain is a special case used by the flush code that is placed on the
301  * unstaged deleted list to avoid confusing the live view.
302  */
303 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
304 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
305 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
306
307 static
308 int
309 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
310                      int flags, int generation)
311 {
312         hammer2_chain_t *xchain;
313         int error = 0;
314
315         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
316                 hammer2_spin_ex(&parent->core.spin);
317
318         /*
319          * Interlocked by spinlock, check for race
320          */
321         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
322             parent->core.generation != generation) {
323                 error = EAGAIN;
324                 goto failed;
325         }
326
327         /*
328          * Insert chain
329          */
330         xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
331         KASSERT(xchain == NULL,
332                 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
333                 chain, xchain, chain->bref.key));
334         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
335         chain->parent = parent;
336         ++parent->core.chain_count;
337         ++parent->core.generation;      /* XXX incs for _get() too, XXX */
338
339         /*
340          * We have to keep track of the effective live-view blockref count
341          * so the create code knows when to push an indirect block.
342          */
343         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
344                 atomic_add_int(&parent->core.live_count, 1);
345 failed:
346         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
347                 hammer2_spin_unex(&parent->core.spin);
348         return error;
349 }
350
351 /*
352  * Drop the caller's reference to the chain.  When the ref count drops to
353  * zero this function will try to disassociate the chain from its parent and
354  * deallocate it, then recursely drop the parent using the implied ref
355  * from the chain's chain->parent.
356  */
357 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
358
359 void
360 hammer2_chain_drop(hammer2_chain_t *chain)
361 {
362         u_int refs;
363
364         if (hammer2_debug & 0x200000)
365                 Debugger("drop");
366 #if 0
367         kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
368         print_backtrace(8);
369 #endif
370
371         KKASSERT(chain->refs > 0);
372
373         while (chain) {
374                 refs = chain->refs;
375                 cpu_ccfence();
376                 KKASSERT(refs > 0);
377
378                 if (refs == 1) {
379                         chain = hammer2_chain_lastdrop(chain);
380                 } else {
381                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
382                                 break;
383                         /* retry the same chain */
384                 }
385         }
386 }
387
388 /*
389  * Safe handling of the 1->0 transition on chain.  Returns a chain for
390  * recursive drop or NULL, possibly returning the same chain if the atomic
391  * op fails.
392  *
393  * When two chains need to be recursively dropped we use the chain we
394  * would otherwise free to placehold the additional chain.  It's a bit
395  * convoluted but we can't just recurse without potentially blowing out
396  * the kernel stack.
397  *
398  * The chain cannot be freed if it has any children.
399  * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
400  * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
401  *
402  * The core spinlock is allowed nest child-to-parent (not parent-to-child).
403  */
404 static
405 hammer2_chain_t *
406 hammer2_chain_lastdrop(hammer2_chain_t *chain)
407 {
408         hammer2_pfs_t *pmp;
409         hammer2_dev_t *hmp;
410         hammer2_chain_t *parent;
411         hammer2_chain_t *rdrop;
412         hammer2_io_t *dio;
413
414         /*
415          * Critical field access.
416          */
417         hammer2_spin_ex(&chain->core.spin);
418
419         if ((parent = chain->parent) != NULL) {
420                 /*
421                  * If the chain has a parent the UPDATE bit prevents scrapping
422                  * as the chain is needed to properly flush the parent.  Try
423                  * to complete the 1->0 transition and return NULL.  Retry
424                  * (return chain) if we are unable to complete the 1->0
425                  * transition, else return NULL (nothing more to do).
426                  *
427                  * If the chain has a parent the MODIFIED bit prevents
428                  * scrapping.
429                  *
430                  * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
431                  */
432                 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
433                                     HAMMER2_CHAIN_MODIFIED)) {
434                         if (atomic_cmpset_int(&chain->refs, 1, 0)) {
435                                 dio = hammer2_chain_drop_data(chain, 0);
436                                 hammer2_spin_unex(&chain->core.spin);
437                                 if (dio)
438                                         hammer2_io_bqrelse(&dio);
439                                 chain = NULL;
440                         } else {
441                                 hammer2_spin_unex(&chain->core.spin);
442                         }
443                         return (chain);
444                 }
445                 /* spinlock still held */
446         } else {
447                 /*
448                  * The chain has no parent and can be flagged for destruction.
449                  * Since it has no parent, UPDATE can also be cleared.
450                  */
451                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
452                 if (chain->flags & HAMMER2_CHAIN_UPDATE)
453                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
454
455                 /*
456                  * If the chain has children or if it has been MODIFIED and
457                  * also recorded for DEDUP, we must still flush the chain.
458                  *
459                  * In the case where it has children, the DESTROY flag test
460                  * in the flush code will prevent unnecessary flushes of
461                  * MODIFIED chains that are not flagged DEDUP so don't worry
462                  * about that here.
463                  */
464                 if (chain->core.chain_count ||
465                     (chain->flags & (HAMMER2_CHAIN_MODIFIED |
466                                      HAMMER2_CHAIN_DEDUP)) ==
467                     (HAMMER2_CHAIN_MODIFIED |
468                      HAMMER2_CHAIN_DEDUP)) {
469                         /*
470                          * Put on flushq (should ensure refs > 1), retry
471                          * the drop.
472                          */
473                         hammer2_spin_unex(&chain->core.spin);
474                         hammer2_delayed_flush(chain);
475                         return(chain);  /* retry drop */
476                 }
477
478                 /*
479                  * Otherwise we can scrap the MODIFIED bit if it is set,
480                  * and continue along the freeing path.
481                  */
482                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
483                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
484                         atomic_add_long(&hammer2_count_modified_chains, -1);
485                 }
486                 /* spinlock still held */
487         }
488
489         /* spinlock still held */
490         dio = NULL;
491
492         /*
493          * If any children exist we must leave the chain intact with refs == 0.
494          * They exist because chains are retained below us which have refs or
495          * may require flushing.  This case can occur when parent != NULL.
496          *
497          * Retry (return chain) if we fail to transition the refs to 0, else
498          * return NULL indication nothing more to do.
499          *
500          * Chains with children are NOT put on the LRU list.
501          */
502         if (chain->core.chain_count) {
503                 if (parent)
504                         hammer2_spin_ex(&parent->core.spin);
505                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
506                         dio = hammer2_chain_drop_data(chain, 1);
507                         hammer2_spin_unex(&chain->core.spin);
508                         if (parent)
509                                 hammer2_spin_unex(&parent->core.spin);
510                         chain = NULL;
511                         if (dio)
512                                 hammer2_io_bqrelse(&dio);
513                 } else {
514                         hammer2_spin_unex(&chain->core.spin);
515                         if (parent)
516                                 hammer2_spin_unex(&parent->core.spin);
517                 }
518                 return (chain);
519         }
520         /* spinlock still held */
521         /* no chains left under us */
522
523         /*
524          * chain->core has no children left so no accessors can get to our
525          * chain from there.  Now we have to lock the parent core to interlock
526          * remaining possible accessors that might bump chain's refs before
527          * we can safely drop chain's refs with intent to free the chain.
528          */
529         hmp = chain->hmp;
530         pmp = chain->pmp;       /* can be NULL */
531         rdrop = NULL;
532
533         parent = chain->parent;
534
535         /*
536          * WARNING! chain's spin lock is still held here, and other spinlocks
537          *          will be acquired and released in the code below.  We
538          *          cannot be making fancy procedure calls!
539          */
540
541         /*
542          * We can cache the chain if it is associated with a pmp
543          * and not flagged as being destroyed or requesting a full
544          * release.  In this situation the chain is not removed
545          * from its parent, i.e. it can still be looked up.
546          *
547          * We intentionally do not cache DATA chains because these
548          * were likely used to load data into the logical buffer cache
549          * and will not be accessed again for some time.
550          */
551         if ((chain->flags &
552              (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
553             chain->pmp &&
554             chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
555                 if (parent)
556                         hammer2_spin_ex(&parent->core.spin);
557                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
558                         /*
559                          * 1->0 transition failed, retry.  Do not drop
560                          * the chain's data yet!
561                          */
562                         if (parent)
563                                 hammer2_spin_unex(&parent->core.spin);
564                         hammer2_spin_unex(&chain->core.spin);
565
566                         return(chain);
567                 }
568
569                 /*
570                  * Success, be sure to clean out the chain's data
571                  * before putting it on a queue that it might be
572                  * reused from.
573                  */
574                 dio = hammer2_chain_drop_data(chain, 1);
575
576                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
577                 hammer2_spin_ex(&pmp->lru_spin);
578                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
579                 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
580
581                 /*
582                  * If we are over the LRU limit we need to drop something.
583                  */
584                 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
585                         rdrop = TAILQ_FIRST(&pmp->lru_list);
586                         atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
587                         TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
588                         atomic_add_int(&rdrop->refs, 1);
589                         atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
590                 } else {
591                         atomic_add_int(&pmp->lru_count, 1);
592                 }
593                 hammer2_spin_unex(&pmp->lru_spin);
594                 if (parent) {
595                         hammer2_spin_unex(&parent->core.spin);
596                         parent = NULL;  /* safety */
597                 }
598                 hammer2_spin_unex(&chain->core.spin);
599                 if (dio)
600                         hammer2_io_bqrelse(&dio);
601
602                 return rdrop;
603                 /* NOT REACHED */
604         }
605
606         /*
607          * Spinlock the parent and try to drop the last ref on chain.
608          * On success determine if we should dispose of the chain
609          * (remove the chain from its parent, etc).
610          *
611          * (normal core locks are top-down recursive but we define
612          * core spinlocks as bottom-up recursive, so this is safe).
613          */
614         if (parent) {
615                 hammer2_spin_ex(&parent->core.spin);
616                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
617                         /*
618                          * 1->0 transition failed, retry.
619                          */
620                         hammer2_spin_unex(&parent->core.spin);
621                         dio = hammer2_chain_drop_data(chain, 0);
622                         hammer2_spin_unex(&chain->core.spin);
623                         if (dio)
624                                 hammer2_io_bqrelse(&dio);
625                         return(chain);
626                 }
627
628                 /*
629                  * 1->0 transition successful, remove chain from the
630                  * parent.
631                  */
632                 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
633                         RB_REMOVE(hammer2_chain_tree,
634                                   &parent->core.rbtree, chain);
635                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
636                         --parent->core.chain_count;
637                         chain->parent = NULL;
638                 }
639
640                 /*
641                  * If our chain was the last chain in the parent's core the
642                  * core is now empty and its parent might have to be
643                  * re-dropped if it has 0 refs.
644                  */
645                 if (parent->core.chain_count == 0) {
646                         rdrop = parent;
647                         atomic_add_int(&rdrop->refs, 1);
648                         /*
649                         if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
650                                 rdrop = NULL;
651                         */
652                 }
653                 hammer2_spin_unex(&parent->core.spin);
654                 parent = NULL;  /* safety */
655                 /* FALL THROUGH */
656         }
657
658         /*
659          * Successful 1->0 transition and the chain can be destroyed now.
660          *
661          * We still have the core spinlock, and core's chain_count is 0.
662          * Any parent spinlock is gone.
663          */
664         hammer2_spin_unex(&chain->core.spin);
665         KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
666                  chain->core.chain_count == 0);
667
668         /*
669          * All spin locks are gone, no pointers remain to the chain, finish
670          * freeing it.
671          */
672         KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
673                                   HAMMER2_CHAIN_MODIFIED)) == 0);
674         dio = hammer2_chain_drop_data(chain, 1);
675         if (dio)
676                 hammer2_io_bqrelse(&dio);
677
678         /*
679          * Once chain resources are gone we can use the now dead chain
680          * structure to placehold what might otherwise require a recursive
681          * drop, because we have potentially two things to drop and can only
682          * return one directly.
683          */
684         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
685                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
686                 chain->hmp = NULL;
687                 kfree(chain, hmp->mchain);
688         }
689
690         /*
691          * Possible chaining loop when parent re-drop needed.
692          */
693         return(rdrop);
694 }
695
696 /*
697  * On either last lock release or last drop
698  */
699 static hammer2_io_t *
700 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
701 {
702         hammer2_io_t *dio;
703
704         if ((dio = chain->dio) != NULL) {
705                 chain->dio = NULL;
706                 chain->data = NULL;
707         } else {
708                 switch(chain->bref.type) {
709                 case HAMMER2_BREF_TYPE_VOLUME:
710                 case HAMMER2_BREF_TYPE_FREEMAP:
711                         if (lastdrop)
712                                 chain->data = NULL;
713                         break;
714                 default:
715                         KKASSERT(chain->data == NULL);
716                         break;
717                 }
718         }
719         return dio;
720 }
721
722 /*
723  * Lock a referenced chain element, acquiring its data with I/O if necessary,
724  * and specify how you would like the data to be resolved.
725  *
726  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
727  *
728  * The lock is allowed to recurse, multiple locking ops will aggregate
729  * the requested resolve types.  Once data is assigned it will not be
730  * removed until the last unlock.
731  *
732  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
733  *                         (typically used to avoid device/logical buffer
734  *                          aliasing for data)
735  *
736  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
737  *                         the INITIAL-create state (indirect blocks only).
738  *
739  *                         Do not resolve data elements for DATA chains.
740  *                         (typically used to avoid device/logical buffer
741  *                          aliasing for data)
742  *
743  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
744  *
745  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
746  *                         it will be locked exclusive.
747  *
748  * NOTE: Embedded elements (volume header, inodes) are always resolved
749  *       regardless.
750  *
751  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
752  *       element will instantiate and zero its buffer, and flush it on
753  *       release.
754  *
755  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
756  *       so as not to instantiate a device buffer, which could alias against
757  *       a logical file buffer.  However, if ALWAYS is specified the
758  *       device buffer will be instantiated anyway.
759  *
760  * WARNING! This function blocks on I/O if data needs to be fetched.  This
761  *          blocking can run concurrent with other compatible lock holders
762  *          who do not need data returning.  The lock is not upgraded to
763  *          exclusive during a data fetch, a separate bit is used to
764  *          interlock I/O.  However, an exclusive lock holder can still count
765  *          on being interlocked against an I/O fetch managed by a shared
766  *          lock holder.
767  */
768 void
769 hammer2_chain_lock(hammer2_chain_t *chain, int how)
770 {
771         /*
772          * Ref and lock the element.  Recursive locks are allowed.
773          */
774         KKASSERT(chain->refs > 0);
775         atomic_add_int(&chain->lockcnt, 1);
776
777         TIMER(20);
778         /*
779          * Get the appropriate lock.
780          */
781         if (how & HAMMER2_RESOLVE_SHARED)
782                 hammer2_mtx_sh(&chain->lock);
783         else
784                 hammer2_mtx_ex(&chain->lock);
785         ++curthread->td_tracker;
786         TIMER(21);
787
788         /*
789          * If we already have a valid data pointer no further action is
790          * necessary.
791          */
792         if (chain->data)
793                 return;
794         TIMER(22);
795
796         /*
797          * Do we have to resolve the data?
798          */
799         switch(how & HAMMER2_RESOLVE_MASK) {
800         case HAMMER2_RESOLVE_NEVER:
801                 return;
802         case HAMMER2_RESOLVE_MAYBE:
803                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
804                         return;
805                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
806                         return;
807 #if 0
808                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
809                         return;
810                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
811                         return;
812 #endif
813                 /* fall through */
814         case HAMMER2_RESOLVE_ALWAYS:
815         default:
816                 break;
817         }
818
819         /*
820          * Caller requires data
821          */
822         hammer2_chain_load_data(chain);
823 }
824
825 /*
826  * Downgrade an exclusive chain lock to a shared chain lock.
827  *
828  * NOTE: There is no upgrade equivalent due to the ease of
829  *       deadlocks in that direction.
830  */
831 void
832 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
833 {
834         hammer2_mtx_downgrade(&chain->lock);
835 }
836
837 /*
838  * Obtains a second shared lock on the chain, does not account the second
839  * shared lock as being owned by the current thread.
840  *
841  * Caller must already own a shared lock on this chain.
842  *
843  * The lock function is required to obtain the second shared lock without
844  * blocking on pending exclusive requests.
845  */
846 void
847 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
848 {
849         hammer2_mtx_sh_again(&chain->lock);
850         atomic_add_int(&chain->lockcnt, 1);
851         /* do not count in td_tracker for this thread */
852 }
853
854 /*
855  * Accounts for a shared lock that was pushed to us as being owned by our
856  * thread.
857  */
858 void
859 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
860 {
861         ++curthread->td_tracker;
862 }
863
864 /*
865  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
866  * may be of any type.
867  *
868  * Once chain->data is set it cannot be disposed of until all locks are
869  * released.
870  */
871 void
872 hammer2_chain_load_data(hammer2_chain_t *chain)
873 {
874         hammer2_blockref_t *bref;
875         hammer2_dev_t *hmp;
876         char *bdata;
877         int error;
878
879         /*
880          * Degenerate case, data already present.
881          */
882         if (chain->data)
883                 return;
884         TIMER(23);
885
886         hmp = chain->hmp;
887         KKASSERT(hmp != NULL);
888
889         /*
890          * Gain the IOINPROG bit, interlocked block.
891          */
892         for (;;) {
893                 u_int oflags;
894                 u_int nflags;
895
896                 oflags = chain->flags;
897                 cpu_ccfence();
898                 if (oflags & HAMMER2_CHAIN_IOINPROG) {
899                         nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
900                         tsleep_interlock(&chain->flags, 0);
901                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
902                                 tsleep(&chain->flags, PINTERLOCKED,
903                                         "h2iocw", 0);
904                         }
905                         /* retry */
906                 } else {
907                         nflags = oflags | HAMMER2_CHAIN_IOINPROG;
908                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
909                                 break;
910                         }
911                         /* retry */
912                 }
913         }
914         TIMER(24);
915
916         /*
917          * We own CHAIN_IOINPROG
918          *
919          * Degenerate case if we raced another load.
920          */
921         if (chain->data)
922                 goto done;
923
924         /*
925          * We must resolve to a device buffer, either by issuing I/O or
926          * by creating a zero-fill element.  We do not mark the buffer
927          * dirty when creating a zero-fill element (the hammer2_chain_modify()
928          * API must still be used to do that).
929          *
930          * The device buffer is variable-sized in powers of 2 down
931          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
932          * chunk always contains buffers of the same size. (XXX)
933          *
934          * The minimum physical IO size may be larger than the variable
935          * block size.
936          */
937         bref = &chain->bref;
938
939         /*
940          * The getblk() optimization can only be used on newly created
941          * elements if the physical block size matches the request.
942          */
943         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
944                 error = hammer2_io_new(hmp, bref->type,
945                                        bref->data_off, chain->bytes,
946                                        &chain->dio);
947         } else {
948                 error = hammer2_io_bread(hmp, bref->type,
949                                          bref->data_off, chain->bytes,
950                                          &chain->dio);
951                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
952         }
953         TIMER(25);
954         if (error) {
955                 chain->error = HAMMER2_ERROR_IO;
956                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
957                         (intmax_t)bref->data_off, error);
958                 hammer2_io_bqrelse(&chain->dio);
959                 goto done;
960         }
961         chain->error = 0;
962
963         /*
964          * NOTE: A locked chain's data cannot be modified without first
965          *       calling hammer2_chain_modify().
966          */
967
968         /*
969          * Clear INITIAL.  In this case we used io_new() and the buffer has
970          * been zero'd and marked dirty.
971          */
972         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
973         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
974                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
975                 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
976         } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
977                 /*
978                  * check data not currently synchronized due to
979                  * modification.  XXX assumes data stays in the buffer
980                  * cache, which might not be true (need biodep on flush
981                  * to calculate crc?  or simple crc?).
982                  */
983         } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
984                 uint64_t mask;
985
986         TIMER(26);
987                 if (hammer2_io_crc_good(chain, &mask)) {
988                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
989                 } else if (hammer2_chain_testcheck(chain, bdata) == 0) {
990                         kprintf("chain %016jx.%02x meth=%02x "
991                                 "CHECK FAIL %08x (flags=%08x)\n",
992                                 chain->bref.data_off,
993                                 chain->bref.type,
994                                 chain->bref.methods,
995                                 hammer2_icrc32(bdata, chain->bytes),
996                                 chain->flags);
997                         chain->error = HAMMER2_ERROR_CHECK;
998                 } else {
999                         hammer2_io_crc_setmask(chain->dio, mask);
1000 #if 0
1001                         kprintf("chain %02x %016jx %u\n",
1002                                 chain->bref.type, chain->bref.key,
1003                                 chain->bytes);
1004 #endif
1005                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1006                 }
1007         }
1008         TIMER(27);
1009
1010         /*
1011          * Setup the data pointer, either pointing it to an embedded data
1012          * structure and copying the data from the buffer, or pointing it
1013          * into the buffer.
1014          *
1015          * The buffer is not retained when copying to an embedded data
1016          * structure in order to avoid potential deadlocks or recursions
1017          * on the same physical buffer.
1018          *
1019          * WARNING! Other threads can start using the data the instant we
1020          *          set chain->data non-NULL.
1021          */
1022         switch (bref->type) {
1023         case HAMMER2_BREF_TYPE_VOLUME:
1024         case HAMMER2_BREF_TYPE_FREEMAP:
1025                 /*
1026                  * Copy data from bp to embedded buffer
1027                  */
1028                 panic("hammer2_chain_lock: called on unresolved volume header");
1029                 break;
1030         case HAMMER2_BREF_TYPE_INODE:
1031         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1032         case HAMMER2_BREF_TYPE_INDIRECT:
1033         case HAMMER2_BREF_TYPE_DATA:
1034         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1035         default:
1036                 /*
1037                  * Point data at the device buffer and leave dio intact.
1038                  */
1039                 chain->data = (void *)bdata;
1040                 break;
1041         }
1042
1043         /*
1044          * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1045          */
1046 done:
1047         for (;;) {
1048                 u_int oflags;
1049                 u_int nflags;
1050
1051                 oflags = chain->flags;
1052                 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1053                                     HAMMER2_CHAIN_IOSIGNAL);
1054                 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1055                 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1056                         if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1057                                 wakeup(&chain->flags);
1058                         break;
1059                 }
1060         }
1061         TIMER(28);
1062 }
1063
1064 /*
1065  * Unlock and deref a chain element.
1066  *
1067  * Remember that the presence of children under chain prevent the chain's
1068  * destruction but do not add additional references, so the dio will still
1069  * be dropped.
1070  */
1071 void
1072 hammer2_chain_unlock(hammer2_chain_t *chain)
1073 {
1074         u_int lockcnt;
1075
1076         --curthread->td_tracker;
1077         /*
1078          * If multiple locks are present (or being attempted) on this
1079          * particular chain we can just unlock, drop refs, and return.
1080          *
1081          * Otherwise fall-through on the 1->0 transition.
1082          */
1083         for (;;) {
1084                 lockcnt = chain->lockcnt;
1085                 KKASSERT(lockcnt > 0);
1086                 cpu_ccfence();
1087                 if (lockcnt > 1) {
1088                         if (atomic_cmpset_int(&chain->lockcnt,
1089                                               lockcnt, lockcnt - 1)) {
1090                                 hammer2_mtx_unlock(&chain->lock);
1091                                 return;
1092                         }
1093                 } else {
1094                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1095                                 break;
1096                 }
1097                 /* retry */
1098         }
1099
1100         /*
1101          * Normally we want to disassociate the data on the last unlock,
1102          * but leave it intact if persist_refs is non-zero.  The persist-data
1103          * user modifies persist_refs only while holding the chain locked
1104          * so there should be no race on the last unlock here.
1105          *
1106          * NOTE: If this was a shared lock we have to temporarily upgrade it
1107          *       to prevent data load races.  We can only do this non-blocking,
1108          *       and unlock/relock-excl can deadlock.  If the try fails it
1109          *       means someone else got a shared or exclusive lock while we
1110          *       we bandying about.
1111          */
1112         if (chain->persist_refs == 0) {
1113                 hammer2_io_t *dio;
1114
1115                 if (hammer2_mtx_upgrade_try(&chain->lock) == 0 &&
1116                     chain->lockcnt == 0) {
1117                         dio = hammer2_chain_drop_data(chain, 0);
1118                         if (dio)
1119                                 hammer2_io_bqrelse(&dio);
1120                 }
1121         }
1122         hammer2_mtx_unlock(&chain->lock);
1123 }
1124
1125 /*
1126  * Helper to obtain the blockref[] array base and count for a chain.
1127  *
1128  * XXX Not widely used yet, various use cases need to be validated and
1129  *     converted to use this function.
1130  */
1131 static
1132 hammer2_blockref_t *
1133 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1134 {
1135         hammer2_blockref_t *base;
1136         int count;
1137
1138         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1139                 base = NULL;
1140
1141                 switch(parent->bref.type) {
1142                 case HAMMER2_BREF_TYPE_INODE:
1143                         count = HAMMER2_SET_COUNT;
1144                         break;
1145                 case HAMMER2_BREF_TYPE_INDIRECT:
1146                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1147                         count = parent->bytes / sizeof(hammer2_blockref_t);
1148                         break;
1149                 case HAMMER2_BREF_TYPE_VOLUME:
1150                         count = HAMMER2_SET_COUNT;
1151                         break;
1152                 case HAMMER2_BREF_TYPE_FREEMAP:
1153                         count = HAMMER2_SET_COUNT;
1154                         break;
1155                 default:
1156                         panic("hammer2_chain_create_indirect: "
1157                               "unrecognized blockref type: %d",
1158                               parent->bref.type);
1159                         count = 0;
1160                         break;
1161                 }
1162         } else {
1163                 switch(parent->bref.type) {
1164                 case HAMMER2_BREF_TYPE_INODE:
1165                         base = &parent->data->ipdata.u.blockset.blockref[0];
1166                         count = HAMMER2_SET_COUNT;
1167                         break;
1168                 case HAMMER2_BREF_TYPE_INDIRECT:
1169                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1170                         base = &parent->data->npdata[0];
1171                         count = parent->bytes / sizeof(hammer2_blockref_t);
1172                         break;
1173                 case HAMMER2_BREF_TYPE_VOLUME:
1174                         base = &parent->data->voldata.
1175                                         sroot_blockset.blockref[0];
1176                         count = HAMMER2_SET_COUNT;
1177                         break;
1178                 case HAMMER2_BREF_TYPE_FREEMAP:
1179                         base = &parent->data->blkset.blockref[0];
1180                         count = HAMMER2_SET_COUNT;
1181                         break;
1182                 default:
1183                         panic("hammer2_chain_create_indirect: "
1184                               "unrecognized blockref type: %d",
1185                               parent->bref.type);
1186                         count = 0;
1187                         break;
1188                 }
1189         }
1190         *countp = count;
1191
1192         return base;
1193 }
1194
1195 /*
1196  * This counts the number of live blockrefs in a block array and
1197  * also calculates the point at which all remaining blockrefs are empty.
1198  * This routine can only be called on a live chain (DUPLICATED flag not set).
1199  *
1200  * NOTE: Flag is not set until after the count is complete, allowing
1201  *       callers to test the flag without holding the spinlock.
1202  *
1203  * NOTE: If base is NULL the related chain is still in the INITIAL
1204  *       state and there are no blockrefs to count.
1205  *
1206  * NOTE: live_count may already have some counts accumulated due to
1207  *       creation and deletion and could even be initially negative.
1208  */
1209 void
1210 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1211                          hammer2_blockref_t *base, int count)
1212 {
1213         hammer2_spin_ex(&chain->core.spin);
1214         if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1215                 if (base) {
1216                         while (--count >= 0) {
1217                                 if (base[count].type)
1218                                         break;
1219                         }
1220                         chain->core.live_zero = count + 1;
1221                         while (count >= 0) {
1222                                 if (base[count].type)
1223                                         atomic_add_int(&chain->core.live_count,
1224                                                        1);
1225                                 --count;
1226                         }
1227                 } else {
1228                         chain->core.live_zero = 0;
1229                 }
1230                 /* else do not modify live_count */
1231                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1232         }
1233         hammer2_spin_unex(&chain->core.spin);
1234 }
1235
1236 /*
1237  * Resize the chain's physical storage allocation in-place.  This function does
1238  * not adjust the data pointer and must be followed by (typically) a
1239  * hammer2_chain_modify() call to copy any old data over and adjust the
1240  * data pointer.
1241  *
1242  * Chains can be resized smaller without reallocating the storage.  Resizing
1243  * larger will reallocate the storage.  Excess or prior storage is reclaimed
1244  * asynchronously at a later time.
1245  *
1246  * Must be passed an exclusively locked parent and chain.
1247  *
1248  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1249  * to avoid instantiating a device buffer that conflicts with the vnode data
1250  * buffer.  However, because H2 can compress or encrypt data, the chain may
1251  * have a dio assigned to it in those situations, and they do not conflict.
1252  *
1253  * XXX return error if cannot resize.
1254  */
1255 void
1256 hammer2_chain_resize(hammer2_inode_t *ip,
1257                      hammer2_chain_t *parent, hammer2_chain_t *chain,
1258                      hammer2_tid_t mtid, hammer2_off_t dedup_off,
1259                      int nradix, int flags)
1260 {
1261         hammer2_dev_t *hmp;
1262         size_t obytes;
1263         size_t nbytes;
1264
1265         hmp = chain->hmp;
1266
1267         /*
1268          * Only data and indirect blocks can be resized for now.
1269          * (The volu root, inodes, and freemap elements use a fixed size).
1270          */
1271         KKASSERT(chain != &hmp->vchain);
1272         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1273                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1274         KKASSERT(chain->parent == parent);
1275
1276         /*
1277          * Nothing to do if the element is already the proper size
1278          */
1279         obytes = chain->bytes;
1280         nbytes = 1U << nradix;
1281         if (obytes == nbytes)
1282                 return;
1283
1284         /*
1285          * Make sure the old data is instantiated so we can copy it.  If this
1286          * is a data block, the device data may be superfluous since the data
1287          * might be in a logical block, but compressed or encrypted data is
1288          * another matter.
1289          *
1290          * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1291          */
1292         hammer2_chain_modify(chain, mtid, dedup_off, 0);
1293
1294         /*
1295          * Relocate the block, even if making it smaller (because different
1296          * block sizes may be in different regions).
1297          *
1298          * (data blocks only, we aren't copying the storage here).
1299          */
1300         hammer2_freemap_alloc(chain, nbytes);
1301         chain->bytes = nbytes;
1302         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1303
1304         /*
1305          * We don't want the followup chain_modify() to try to copy data
1306          * from the old (wrong-sized) buffer.  It won't know how much to
1307          * copy.  This case should only occur during writes when the
1308          * originator already has the data to write in-hand.
1309          */
1310         if (chain->dio) {
1311                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA);
1312                 hammer2_io_brelse(&chain->dio);
1313                 chain->data = NULL;
1314         }
1315 }
1316
1317 /*
1318  * Set the chain modified so its data can be changed by the caller.
1319  *
1320  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1321  * is a CLC (cluster level change) field and is not updated by parent
1322  * propagation during a flush.
1323  *
1324  * If the caller passes a non-zero dedup_off we assign data_off to that
1325  * instead of allocating a ne block.  Caller must not modify the data already
1326  * present at the target offset.
1327  */
1328 void
1329 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1330                      hammer2_off_t dedup_off, int flags)
1331 {
1332         hammer2_blockref_t obref;
1333         hammer2_dev_t *hmp;
1334         hammer2_io_t *dio;
1335         int error;
1336         int wasinitial;
1337         int newmod;
1338         char *bdata;
1339
1340         hmp = chain->hmp;
1341         obref = chain->bref;
1342         KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1343
1344         /*
1345          * Data is not optional for freemap chains (we must always be sure
1346          * to copy the data on COW storage allocations).
1347          */
1348         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1349             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1350                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1351                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1352         }
1353
1354         /*
1355          * Data must be resolved if already assigned, unless explicitly
1356          * flagged otherwise.
1357          */
1358         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1359             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1360                 hammer2_chain_load_data(chain);
1361         }
1362
1363         /*
1364          * Set MODIFIED to indicate that the chain has been modified.
1365          * Set UPDATE to ensure that the blockref is updated in the parent.
1366          */
1367         if ((chain->flags & (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) ==
1368             (HAMMER2_CHAIN_DEDUP | HAMMER2_CHAIN_MODIFIED)) {
1369                 /*
1370                  * Modified already set but a new allocation is needed
1371                  * anyway because we recorded this data_off for possible
1372                  * dedup operation.
1373                  */
1374                 newmod = 1;
1375         } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1376                 /*
1377                  * Must set modified bit.
1378                  */
1379                 atomic_add_long(&hammer2_count_modified_chains, 1);
1380                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1381                 hammer2_pfs_memory_inc(chain->pmp);     /* can be NULL */
1382                 newmod = 1;
1383         } else {
1384                 /*
1385                  * Already flagged modified, no new allocation is needed.
1386                  */
1387                 newmod = 0;
1388         }
1389
1390         /*
1391          * Flag parent update required, clear DEDUP flag (already processed
1392          * above).
1393          */
1394         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1395                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1396         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DEDUP);
1397
1398         /*
1399          * The modification or re-modification requires an allocation and
1400          * possible COW.
1401          *
1402          * If dedup_off is non-zero, caller already has a data offset
1403          * containing the caller's desired data.  The dedup offset is
1404          * allowed to be in a partially free state and we must be sure
1405          * to reset it to a fully allocated state to force two bulkfree
1406          * passes to free it again.
1407          *
1408          * XXX can a chain already be marked MODIFIED without a data
1409          * assignment?  If not, assert here instead of testing the case.
1410          */
1411         if (chain != &hmp->vchain && chain != &hmp->fchain) {
1412                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1413                      newmod
1414                 ) {
1415                         if (dedup_off) {
1416                                 chain->bref.data_off = dedup_off;
1417                                 chain->bytes = 1 << (dedup_off &
1418                                                      HAMMER2_OFF_MASK_RADIX);
1419                                 atomic_set_int(&chain->flags,
1420                                                HAMMER2_CHAIN_DEDUP);
1421                                 hammer2_freemap_adjust(hmp, &chain->bref,
1422                                                 HAMMER2_FREEMAP_DORECOVER);
1423                         } else {
1424                                 hammer2_freemap_alloc(chain, chain->bytes);
1425                         }
1426                         /* XXX failed allocation */
1427                 }
1428         }
1429
1430         /*
1431          * Update mirror_tid and modify_tid.  modify_tid is only updated
1432          * if not passed as zero (during flushes, parent propagation passes
1433          * the value 0).
1434          *
1435          * NOTE: chain->pmp could be the device spmp.
1436          */
1437         chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1438         if (mtid)
1439                 chain->bref.modify_tid = mtid;
1440
1441         /*
1442          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1443          * requires updating as well as to tell the delete code that the
1444          * chain's blockref might not exactly match (in terms of physical size
1445          * or block offset) the one in the parent's blocktable.  The base key
1446          * of course will still match.
1447          */
1448         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1449                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1450
1451         /*
1452          * Short-cut data blocks which the caller does not need an actual
1453          * data reference to (aka OPTDATA), as long as the chain does not
1454          * already have a data pointer to the data.  This generally means
1455          * that the modifications are being done via the logical buffer cache.
1456          * The INITIAL flag relates only to the device data buffer and thus
1457          * remains unchange in this situation.
1458          */
1459         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1460             (flags & HAMMER2_MODIFY_OPTDATA) &&
1461             chain->data == NULL) {
1462                 goto skip2;
1463         }
1464
1465         /*
1466          * Clearing the INITIAL flag (for indirect blocks) indicates that
1467          * we've processed the uninitialized storage allocation.
1468          *
1469          * If this flag is already clear we are likely in a copy-on-write
1470          * situation but we have to be sure NOT to bzero the storage if
1471          * no data is present.
1472          */
1473         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1474                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1475                 wasinitial = 1;
1476         } else {
1477                 wasinitial = 0;
1478         }
1479
1480         /*
1481          * Instantiate data buffer and possibly execute COW operation
1482          */
1483         switch(chain->bref.type) {
1484         case HAMMER2_BREF_TYPE_VOLUME:
1485         case HAMMER2_BREF_TYPE_FREEMAP:
1486                 /*
1487                  * The data is embedded, no copy-on-write operation is
1488                  * needed.
1489                  */
1490                 KKASSERT(chain->dio == NULL);
1491                 break;
1492         case HAMMER2_BREF_TYPE_INODE:
1493         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1494         case HAMMER2_BREF_TYPE_DATA:
1495         case HAMMER2_BREF_TYPE_INDIRECT:
1496         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1497                 /*
1498                  * Perform the copy-on-write operation
1499                  *
1500                  * zero-fill or copy-on-write depending on whether
1501                  * chain->data exists or not and set the dirty state for
1502                  * the new buffer.  hammer2_io_new() will handle the
1503                  * zero-fill.
1504                  *
1505                  * If a dedup_off was supplied this is an existing block
1506                  * and no COW, copy, or further modification is required.
1507                  */
1508                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1509
1510                 if (wasinitial && dedup_off == 0) {
1511                         error = hammer2_io_new(hmp, chain->bref.type,
1512                                                chain->bref.data_off,
1513                                                chain->bytes, &dio);
1514                 } else {
1515                         error = hammer2_io_bread(hmp, chain->bref.type,
1516                                                  chain->bref.data_off,
1517                                                  chain->bytes, &dio);
1518                 }
1519                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1520
1521                 /*
1522                  * If an I/O error occurs make sure callers cannot accidently
1523                  * modify the old buffer's contents and corrupt the filesystem.
1524                  */
1525                 if (error) {
1526                         kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1527                                 hmp);
1528                         chain->error = HAMMER2_ERROR_IO;
1529                         hammer2_io_brelse(&dio);
1530                         hammer2_io_brelse(&chain->dio);
1531                         chain->data = NULL;
1532                         break;
1533                 }
1534                 chain->error = 0;
1535                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1536
1537                 if (chain->data) {
1538                         /*
1539                          * COW (unless a dedup).
1540                          */
1541                         KKASSERT(chain->dio != NULL);
1542                         if (chain->data != (void *)bdata && dedup_off == 0) {
1543                                 bcopy(chain->data, bdata, chain->bytes);
1544                         }
1545                 } else if (wasinitial == 0) {
1546                         /*
1547                          * We have a problem.  We were asked to COW but
1548                          * we don't have any data to COW with!
1549                          */
1550                         panic("hammer2_chain_modify: having a COW %p\n",
1551                               chain);
1552                 }
1553
1554                 /*
1555                  * Retire the old buffer, replace with the new.  Dirty or
1556                  * redirty the new buffer.
1557                  *
1558                  * WARNING! The system buffer cache may have already flushed
1559                  *          the buffer, so we must be sure to [re]dirty it
1560                  *          for further modification.
1561                  *
1562                  *          If dedup_off was supplied, the caller is not
1563                  *          expected to make any further modification to the
1564                  *          buffer.
1565                  */
1566                 if (chain->dio)
1567                         hammer2_io_bqrelse(&chain->dio);
1568                 chain->data = (void *)bdata;
1569                 chain->dio = dio;
1570                 if (dedup_off == 0)
1571                         hammer2_io_setdirty(dio);
1572                 break;
1573         default:
1574                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1575                       chain->bref.type);
1576                 break;
1577
1578         }
1579 skip2:
1580         /*
1581          * setflush on parent indicating that the parent must recurse down
1582          * to us.  Do not call on chain itself which might already have it
1583          * set.
1584          */
1585         if (chain->parent)
1586                 hammer2_chain_setflush(chain->parent);
1587 }
1588
1589 /*
1590  * Modify the chain associated with an inode.
1591  */
1592 void
1593 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1594                         hammer2_tid_t mtid, int flags)
1595 {
1596         hammer2_inode_modify(ip);
1597         hammer2_chain_modify(chain, mtid, 0, flags);
1598 }
1599
1600 /*
1601  * Volume header data locks
1602  */
1603 void
1604 hammer2_voldata_lock(hammer2_dev_t *hmp)
1605 {
1606         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1607 }
1608
1609 void
1610 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1611 {
1612         lockmgr(&hmp->vollk, LK_RELEASE);
1613 }
1614
1615 void
1616 hammer2_voldata_modify(hammer2_dev_t *hmp)
1617 {
1618         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1619                 atomic_add_long(&hammer2_count_modified_chains, 1);
1620                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1621                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1622         }
1623 }
1624
1625 /*
1626  * This function returns the chain at the nearest key within the specified
1627  * range.  The returned chain will be referenced but not locked.
1628  *
1629  * This function will recurse through chain->rbtree as necessary and will
1630  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1631  * the iteration value is less than the current value of *key_nextp.
1632  *
1633  * The caller should use (*key_nextp) to calculate the actual range of
1634  * the returned element, which will be (key_beg to *key_nextp - 1), because
1635  * there might be another element which is superior to the returned element
1636  * and overlaps it.
1637  *
1638  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1639  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1640  * it will wind up being (key_end + 1).
1641  *
1642  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1643  *           held through the operation.
1644  */
1645 struct hammer2_chain_find_info {
1646         hammer2_chain_t         *best;
1647         hammer2_key_t           key_beg;
1648         hammer2_key_t           key_end;
1649         hammer2_key_t           key_next;
1650 };
1651
1652 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1653 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1654
1655 static
1656 hammer2_chain_t *
1657 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1658                           hammer2_key_t key_beg, hammer2_key_t key_end)
1659 {
1660         struct hammer2_chain_find_info info;
1661
1662         info.best = NULL;
1663         info.key_beg = key_beg;
1664         info.key_end = key_end;
1665         info.key_next = *key_nextp;
1666
1667         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1668                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1669                 &info);
1670         *key_nextp = info.key_next;
1671 #if 0
1672         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1673                 parent, key_beg, key_end, *key_nextp);
1674 #endif
1675
1676         return (info.best);
1677 }
1678
1679 static
1680 int
1681 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1682 {
1683         struct hammer2_chain_find_info *info = data;
1684         hammer2_key_t child_beg;
1685         hammer2_key_t child_end;
1686
1687         child_beg = child->bref.key;
1688         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1689
1690         if (child_end < info->key_beg)
1691                 return(-1);
1692         if (child_beg > info->key_end)
1693                 return(1);
1694         return(0);
1695 }
1696
1697 static
1698 int
1699 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1700 {
1701         struct hammer2_chain_find_info *info = data;
1702         hammer2_chain_t *best;
1703         hammer2_key_t child_end;
1704
1705         /*
1706          * WARNING! Do not discard DUPLICATED chains, it is possible that
1707          *          we are catching an insertion half-way done.  If a
1708          *          duplicated chain turns out to be the best choice the
1709          *          caller will re-check its flags after locking it.
1710          *
1711          * WARNING! Layerq is scanned forwards, exact matches should keep
1712          *          the existing info->best.
1713          */
1714         if ((best = info->best) == NULL) {
1715                 /*
1716                  * No previous best.  Assign best
1717                  */
1718                 info->best = child;
1719         } else if (best->bref.key <= info->key_beg &&
1720                    child->bref.key <= info->key_beg) {
1721                 /*
1722                  * Illegal overlap.
1723                  */
1724                 KKASSERT(0);
1725                 /*info->best = child;*/
1726         } else if (child->bref.key < best->bref.key) {
1727                 /*
1728                  * Child has a nearer key and best is not flush with key_beg.
1729                  * Set best to child.  Truncate key_next to the old best key.
1730                  */
1731                 info->best = child;
1732                 if (info->key_next > best->bref.key || info->key_next == 0)
1733                         info->key_next = best->bref.key;
1734         } else if (child->bref.key == best->bref.key) {
1735                 /*
1736                  * If our current best is flush with the child then this
1737                  * is an illegal overlap.
1738                  *
1739                  * key_next will automatically be limited to the smaller of
1740                  * the two end-points.
1741                  */
1742                 KKASSERT(0);
1743                 info->best = child;
1744         } else {
1745                 /*
1746                  * Keep the current best but truncate key_next to the child's
1747                  * base.
1748                  *
1749                  * key_next will also automatically be limited to the smaller
1750                  * of the two end-points (probably not necessary for this case
1751                  * but we do it anyway).
1752                  */
1753                 if (info->key_next > child->bref.key || info->key_next == 0)
1754                         info->key_next = child->bref.key;
1755         }
1756
1757         /*
1758          * Always truncate key_next based on child's end-of-range.
1759          */
1760         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1761         if (child_end && (info->key_next > child_end || info->key_next == 0))
1762                 info->key_next = child_end;
1763
1764         return(0);
1765 }
1766
1767 /*
1768  * Retrieve the specified chain from a media blockref, creating the
1769  * in-memory chain structure which reflects it.
1770  *
1771  * To handle insertion races pass the INSERT_RACE flag along with the
1772  * generation number of the core.  NULL will be returned if the generation
1773  * number changes before we have a chance to insert the chain.  Insert
1774  * races can occur because the parent might be held shared.
1775  *
1776  * Caller must hold the parent locked shared or exclusive since we may
1777  * need the parent's bref array to find our block.
1778  *
1779  * WARNING! chain->pmp is always set to NULL for any chain representing
1780  *          part of the super-root topology.
1781  */
1782 hammer2_chain_t *
1783 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1784                   hammer2_blockref_t *bref)
1785 {
1786         hammer2_dev_t *hmp = parent->hmp;
1787         hammer2_chain_t *chain;
1788         int error;
1789
1790         /*
1791          * Allocate a chain structure representing the existing media
1792          * entry.  Resulting chain has one ref and is not locked.
1793          */
1794         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1795                 chain = hammer2_chain_alloc(hmp, NULL, bref);
1796         else
1797                 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1798         /* ref'd chain returned */
1799
1800         /*
1801          * Flag that the chain is in the parent's blockmap so delete/flush
1802          * knows what to do with it.
1803          */
1804         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1805
1806         /*
1807          * Link the chain into its parent.  A spinlock is required to safely
1808          * access the RBTREE, and it is possible to collide with another
1809          * hammer2_chain_get() operation because the caller might only hold
1810          * a shared lock on the parent.
1811          *
1812          * NOTE: Get races can occur quite often when we distribute
1813          *       asynchronous read-aheads across multiple threads.
1814          */
1815         KKASSERT(parent->refs > 0);
1816         error = hammer2_chain_insert(parent, chain,
1817                                      HAMMER2_CHAIN_INSERT_SPIN |
1818                                      HAMMER2_CHAIN_INSERT_RACE,
1819                                      generation);
1820         if (error) {
1821                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1822                 /*kprintf("chain %p get race\n", chain);*/
1823                 hammer2_chain_drop(chain);
1824                 chain = NULL;
1825         } else {
1826                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1827         }
1828
1829         /*
1830          * Return our new chain referenced but not locked, or NULL if
1831          * a race occurred.
1832          */
1833         return (chain);
1834 }
1835
1836 /*
1837  * Lookup initialization/completion API
1838  */
1839 hammer2_chain_t *
1840 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1841 {
1842         hammer2_chain_ref(parent);
1843         if (flags & HAMMER2_LOOKUP_SHARED) {
1844                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1845                                            HAMMER2_RESOLVE_SHARED);
1846         } else {
1847                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1848         }
1849         return (parent);
1850 }
1851
1852 void
1853 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1854 {
1855         if (parent) {
1856                 hammer2_chain_unlock(parent);
1857                 hammer2_chain_drop(parent);
1858         }
1859 }
1860
1861 hammer2_chain_t *
1862 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1863 {
1864         hammer2_chain_t *oparent;
1865         hammer2_chain_t *nparent;
1866
1867         /*
1868          * Be careful of order, oparent must be unlocked before nparent
1869          * is locked below to avoid a deadlock.
1870          */
1871         oparent = *parentp;
1872         hammer2_spin_ex(&oparent->core.spin);
1873         nparent = oparent->parent;
1874         hammer2_chain_ref(nparent);
1875         hammer2_spin_unex(&oparent->core.spin);
1876         if (oparent) {
1877                 hammer2_chain_unlock(oparent);
1878                 hammer2_chain_drop(oparent);
1879                 oparent = NULL;
1880         }
1881
1882         hammer2_chain_lock(nparent, how);
1883         *parentp = nparent;
1884
1885         return (nparent);
1886 }
1887
1888 /*
1889  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1890  * (*parentp) typically points to an inode but can also point to a related
1891  * indirect block and this function will recurse upwards and find the inode
1892  * again.
1893  *
1894  * (*parentp) must be exclusively locked and referenced and can be an inode
1895  * or an existing indirect block within the inode.
1896  *
1897  * On return (*parentp) will be modified to point at the deepest parent chain
1898  * element encountered during the search, as a helper for an insertion or
1899  * deletion.   The new (*parentp) will be locked and referenced and the old
1900  * will be unlocked and dereferenced (no change if they are both the same).
1901  *
1902  * The matching chain will be returned exclusively locked.  If NOLOCK is
1903  * requested the chain will be returned only referenced.  Note that the
1904  * parent chain must always be locked shared or exclusive, matching the
1905  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
1906  * when NOLOCK is specified but that complicates matters if *parentp must
1907  * inherit the chain.
1908  *
1909  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1910  * data pointer or can otherwise be in flux.
1911  *
1912  * NULL is returned if no match was found, but (*parentp) will still
1913  * potentially be adjusted.
1914  *
1915  * If a fatal error occurs (typically an I/O error), a dummy chain is
1916  * returned with chain->error and error-identifying information set.  This
1917  * chain will assert if you try to do anything fancy with it.
1918  *
1919  * XXX Depending on where the error occurs we should allow continued iteration.
1920  *
1921  * On return (*key_nextp) will point to an iterative value for key_beg.
1922  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1923  *
1924  * This function will also recurse up the chain if the key is not within the
1925  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1926  * can simply allow (*parentp) to float inside the loop.
1927  *
1928  * NOTE!  chain->data is not always resolved.  By default it will not be
1929  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1930  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1931  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1932  *        buffer).
1933  */
1934
1935 hammer2_chain_t *
1936 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1937                      hammer2_key_t key_beg, hammer2_key_t key_end,
1938                      int *cache_indexp, int flags)
1939 {
1940         hammer2_dev_t *hmp;
1941         hammer2_chain_t *parent;
1942         hammer2_chain_t *chain;
1943         hammer2_blockref_t *base;
1944         hammer2_blockref_t *bref;
1945         hammer2_blockref_t bcopy;
1946         hammer2_key_t scan_beg;
1947         hammer2_key_t scan_end;
1948         int count = 0;
1949         int how_always = HAMMER2_RESOLVE_ALWAYS;
1950         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1951         int how;
1952         int generation;
1953         int maxloops = 300000;
1954
1955         TIMER(8);
1956
1957         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1958                 how_maybe = how_always;
1959                 how = HAMMER2_RESOLVE_ALWAYS;
1960         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1961                 how = HAMMER2_RESOLVE_NEVER;
1962         } else {
1963                 how = HAMMER2_RESOLVE_MAYBE;
1964         }
1965         if (flags & HAMMER2_LOOKUP_SHARED) {
1966                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1967                 how_always |= HAMMER2_RESOLVE_SHARED;
1968                 how |= HAMMER2_RESOLVE_SHARED;
1969         }
1970
1971         /*
1972          * Recurse (*parentp) upward if necessary until the parent completely
1973          * encloses the key range or we hit the inode.
1974          *
1975          * This function handles races against the flusher doing a delete-
1976          * duplicate above us and re-homes the parent to the duplicate in
1977          * that case, otherwise we'd wind up recursing down a stale chain.
1978          */
1979         parent = *parentp;
1980         hmp = parent->hmp;
1981
1982         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1983                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1984                 scan_beg = parent->bref.key;
1985                 scan_end = scan_beg +
1986                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1987                 if (key_beg >= scan_beg && key_end <= scan_end)
1988                         break;
1989                 parent = hammer2_chain_getparent(parentp, how_maybe);
1990         }
1991
1992 again:
1993         TIMER(9);
1994         if (--maxloops == 0)
1995                 panic("hammer2_chain_lookup: maxloops");
1996         /*
1997          * Locate the blockref array.  Currently we do a fully associative
1998          * search through the array.
1999          */
2000         switch(parent->bref.type) {
2001         case HAMMER2_BREF_TYPE_INODE:
2002                 /*
2003                  * Special shortcut for embedded data returns the inode
2004                  * itself.  Callers must detect this condition and access
2005                  * the embedded data (the strategy code does this for us).
2006                  *
2007                  * This is only applicable to regular files and softlinks.
2008                  */
2009                 if (parent->data->ipdata.meta.op_flags &
2010                     HAMMER2_OPFLAG_DIRECTDATA) {
2011                         if (flags & HAMMER2_LOOKUP_NODIRECT) {
2012                                 chain = NULL;
2013                                 *key_nextp = key_end + 1;
2014                                 goto done;
2015                         }
2016                         hammer2_chain_ref(parent);
2017                         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2018                                 hammer2_chain_lock(parent, how_always);
2019                         *key_nextp = key_end + 1;
2020                         return (parent);
2021                 }
2022                 base = &parent->data->ipdata.u.blockset.blockref[0];
2023                 count = HAMMER2_SET_COUNT;
2024                 break;
2025         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2026         case HAMMER2_BREF_TYPE_INDIRECT:
2027                 /*
2028                  * Handle MATCHIND on the parent
2029                  */
2030                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2031                         scan_beg = parent->bref.key;
2032                         scan_end = scan_beg +
2033                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2034                         if (key_beg == scan_beg && key_end == scan_end) {
2035                                 chain = parent;
2036                                 hammer2_chain_ref(chain);
2037                                 hammer2_chain_lock(chain, how_maybe);
2038                                 *key_nextp = scan_end + 1;
2039                                 goto done;
2040                         }
2041                 }
2042                 /*
2043                  * Optimize indirect blocks in the INITIAL state to avoid
2044                  * I/O.
2045                  */
2046                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2047                         base = NULL;
2048                 } else {
2049                         if (parent->data == NULL) {
2050                                 kprintf("parent->data is NULL %p\n", parent);
2051                                 while (1)
2052                                         tsleep(parent, 0, "xxx", 0);
2053                         }
2054                         base = &parent->data->npdata[0];
2055                 }
2056                 count = parent->bytes / sizeof(hammer2_blockref_t);
2057                 break;
2058         case HAMMER2_BREF_TYPE_VOLUME:
2059                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2060                 count = HAMMER2_SET_COUNT;
2061                 break;
2062         case HAMMER2_BREF_TYPE_FREEMAP:
2063                 base = &parent->data->blkset.blockref[0];
2064                 count = HAMMER2_SET_COUNT;
2065                 break;
2066         default:
2067                 kprintf("hammer2_chain_lookup: unrecognized "
2068                         "blockref(B) type: %d",
2069                         parent->bref.type);
2070                 while (1)
2071                         tsleep(&base, 0, "dead", 0);
2072                 panic("hammer2_chain_lookup: unrecognized "
2073                       "blockref(B) type: %d",
2074                       parent->bref.type);
2075                 base = NULL;    /* safety */
2076                 count = 0;      /* safety */
2077         }
2078         TIMER(10);
2079
2080         /*
2081          * Merged scan to find next candidate.
2082          *
2083          * hammer2_base_*() functions require the parent->core.live_* fields
2084          * to be synchronized.
2085          *
2086          * We need to hold the spinlock to access the block array and RB tree
2087          * and to interlock chain creation.
2088          */
2089         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2090                 hammer2_chain_countbrefs(parent, base, count);
2091
2092         TIMER(11);
2093
2094         /*
2095          * Combined search
2096          */
2097         hammer2_spin_ex(&parent->core.spin);
2098         chain = hammer2_combined_find(parent, base, count,
2099                                       cache_indexp, key_nextp,
2100                                       key_beg, key_end,
2101                                       &bref);
2102         generation = parent->core.generation;
2103
2104         TIMER(12);
2105
2106         /*
2107          * Exhausted parent chain, iterate.
2108          */
2109         if (bref == NULL) {
2110                 TIMER(13);
2111                 hammer2_spin_unex(&parent->core.spin);
2112                 if (key_beg == key_end) /* short cut single-key case */
2113                         return (NULL);
2114
2115                 /*
2116                  * Stop if we reached the end of the iteration.
2117                  */
2118                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2119                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2120                         return (NULL);
2121                 }
2122
2123                 /*
2124                  * Calculate next key, stop if we reached the end of the
2125                  * iteration, otherwise go up one level and loop.
2126                  */
2127                 key_beg = parent->bref.key +
2128                           ((hammer2_key_t)1 << parent->bref.keybits);
2129                 if (key_beg == 0 || key_beg > key_end)
2130                         return (NULL);
2131                 parent = hammer2_chain_getparent(parentp, how_maybe);
2132                 goto again;
2133         }
2134
2135         /*
2136          * Selected from blockref or in-memory chain.
2137          */
2138         if (chain == NULL) {
2139                 TIMER(14);
2140                 bcopy = *bref;
2141                 hammer2_spin_unex(&parent->core.spin);
2142                 chain = hammer2_chain_get(parent, generation,
2143                                           &bcopy);
2144                 if (chain == NULL) {
2145                         /*
2146                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2147                                 parent, key_beg, key_end);
2148                         */
2149                         goto again;
2150                 }
2151                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2152                         hammer2_chain_drop(chain);
2153                         goto again;
2154                 }
2155         } else {
2156                 TIMER(15);
2157                 hammer2_chain_ref(chain);
2158                 hammer2_spin_unex(&parent->core.spin);
2159         }
2160
2161         TIMER(16);
2162         /*
2163          * chain is referenced but not locked.  We must lock the chain
2164          * to obtain definitive DUPLICATED/DELETED state
2165          */
2166         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2167             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2168                 hammer2_chain_lock(chain, how_maybe);
2169         } else {
2170                 hammer2_chain_lock(chain, how);
2171         }
2172         TIMER(17);
2173
2174         /*
2175          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2176          *
2177          * NOTE: Chain's key range is not relevant as there might be
2178          *       one-offs within the range that are not deleted.
2179          *
2180          * NOTE: Lookups can race delete-duplicate because
2181          *       delete-duplicate does not lock the parent's core
2182          *       (they just use the spinlock on the core).  We must
2183          *       check for races by comparing the DUPLICATED flag before
2184          *       releasing the spinlock with the flag after locking the
2185          *       chain.
2186          */
2187         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2188                 hammer2_chain_unlock(chain);
2189                 hammer2_chain_drop(chain);
2190                 key_beg = *key_nextp;
2191                 if (key_beg == 0 || key_beg > key_end)
2192                         return(NULL);
2193                 goto again;
2194         }
2195         TIMER(18);
2196
2197         /*
2198          * If the chain element is an indirect block it becomes the new
2199          * parent and we loop on it.  We must maintain our top-down locks
2200          * to prevent the flusher from interfering (i.e. doing a
2201          * delete-duplicate and leaving us recursing down a deleted chain).
2202          *
2203          * The parent always has to be locked with at least RESOLVE_MAYBE
2204          * so we can access its data.  It might need a fixup if the caller
2205          * passed incompatible flags.  Be careful not to cause a deadlock
2206          * as a data-load requires an exclusive lock.
2207          *
2208          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2209          * range is within the requested key range we return the indirect
2210          * block and do NOT loop.  This is usually only used to acquire
2211          * freemap nodes.
2212          */
2213         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2214             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2215                 hammer2_chain_unlock(parent);
2216                 hammer2_chain_drop(parent);
2217                 *parentp = parent = chain;
2218                 goto again;
2219         }
2220         TIMER(19);
2221 done:
2222         /*
2223          * All done, return the chain.
2224          *
2225          * If the caller does not want a locked chain, replace the lock with
2226          * a ref.  Perhaps this can eventually be optimized to not obtain the
2227          * lock in the first place for situations where the data does not
2228          * need to be resolved.
2229          */
2230         if (chain) {
2231                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2232                         hammer2_chain_unlock(chain);
2233         }
2234         TIMER(20);
2235
2236         return (chain);
2237 }
2238
2239 /*
2240  * After having issued a lookup we can iterate all matching keys.
2241  *
2242  * If chain is non-NULL we continue the iteration from just after it's index.
2243  *
2244  * If chain is NULL we assume the parent was exhausted and continue the
2245  * iteration at the next parent.
2246  *
2247  * If a fatal error occurs (typically an I/O error), a dummy chain is
2248  * returned with chain->error and error-identifying information set.  This
2249  * chain will assert if you try to do anything fancy with it.
2250  *
2251  * XXX Depending on where the error occurs we should allow continued iteration.
2252  *
2253  * parent must be locked on entry and remains locked throughout.  chain's
2254  * lock status must match flags.  Chain is always at least referenced.
2255  *
2256  * WARNING!  The MATCHIND flag does not apply to this function.
2257  */
2258 hammer2_chain_t *
2259 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2260                    hammer2_key_t *key_nextp,
2261                    hammer2_key_t key_beg, hammer2_key_t key_end,
2262                    int *cache_indexp, int flags)
2263 {
2264         hammer2_chain_t *parent;
2265         int how_maybe;
2266
2267         /*
2268          * Calculate locking flags for upward recursion.
2269          */
2270         how_maybe = HAMMER2_RESOLVE_MAYBE;
2271         if (flags & HAMMER2_LOOKUP_SHARED)
2272                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2273
2274         parent = *parentp;
2275
2276         /*
2277          * Calculate the next index and recalculate the parent if necessary.
2278          */
2279         if (chain) {
2280                 key_beg = chain->bref.key +
2281                           ((hammer2_key_t)1 << chain->bref.keybits);
2282                 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2283                               HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2284                         hammer2_chain_unlock(chain);
2285                 }
2286                 hammer2_chain_drop(chain);
2287
2288                 /*
2289                  * chain invalid past this point, but we can still do a
2290                  * pointer comparison w/parent.
2291                  *
2292                  * Any scan where the lookup returned degenerate data embedded
2293                  * in the inode has an invalid index and must terminate.
2294                  */
2295                 if (chain == parent)
2296                         return(NULL);
2297                 if (key_beg == 0 || key_beg > key_end)
2298                         return(NULL);
2299                 chain = NULL;
2300         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2301                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2302                 /*
2303                  * We reached the end of the iteration.
2304                  */
2305                 return (NULL);
2306         } else {
2307                 /*
2308                  * Continue iteration with next parent unless the current
2309                  * parent covers the range.
2310                  */
2311                 key_beg = parent->bref.key +
2312                           ((hammer2_key_t)1 << parent->bref.keybits);
2313                 if (key_beg == 0 || key_beg > key_end)
2314                         return (NULL);
2315                 parent = hammer2_chain_getparent(parentp, how_maybe);
2316         }
2317
2318         /*
2319          * And execute
2320          */
2321         return (hammer2_chain_lookup(parentp, key_nextp,
2322                                      key_beg, key_end,
2323                                      cache_indexp, flags));
2324 }
2325
2326 /*
2327  * The raw scan function is similar to lookup/next but does not seek to a key.
2328  * Blockrefs are iterated via first_bref = (parent, NULL) and
2329  * next_chain = (parent, bref).
2330  *
2331  * The passed-in parent must be locked and its data resolved.  The function
2332  * nominally returns a locked and referenced *chainp != NULL for chains
2333  * the caller might need to recurse on (and will dipose of any *chainp passed
2334  * in).  The caller must check the chain->bref.type either way.
2335  *
2336  * *chainp is not set for leaf elements.
2337  *
2338  * This function takes a pointer to a stack-based bref structure whos
2339  * contents is updated for each iteration.  The same pointer is returned,
2340  * or NULL when the iteration is complete.  *firstp must be set to 1 for
2341  * the first ieration.  This function will set it to 0.
2342  */
2343 hammer2_blockref_t *
2344 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2345                    hammer2_blockref_t *bref, int *firstp,
2346                    int *cache_indexp, int flags)
2347 {
2348         hammer2_dev_t *hmp;
2349         hammer2_blockref_t *base;
2350         hammer2_blockref_t *bref_ptr;
2351         hammer2_key_t key;
2352         hammer2_key_t next_key;
2353         hammer2_chain_t *chain = NULL;
2354         int count = 0;
2355         int how_always = HAMMER2_RESOLVE_ALWAYS;
2356         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2357         int how;
2358         int generation;
2359         int maxloops = 300000;
2360
2361         hmp = parent->hmp;
2362
2363         /*
2364          * Scan flags borrowed from lookup.
2365          */
2366         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2367                 how_maybe = how_always;
2368                 how = HAMMER2_RESOLVE_ALWAYS;
2369         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2370                 how = HAMMER2_RESOLVE_NEVER;
2371         } else {
2372                 how = HAMMER2_RESOLVE_MAYBE;
2373         }
2374         if (flags & HAMMER2_LOOKUP_SHARED) {
2375                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2376                 how_always |= HAMMER2_RESOLVE_SHARED;
2377                 how |= HAMMER2_RESOLVE_SHARED;
2378         }
2379
2380         /*
2381          * Calculate key to locate first/next element, unlocking the previous
2382          * element as we go.  Be careful, the key calculation can overflow.
2383          *
2384          * (also reset bref to NULL)
2385          */
2386         if (*firstp) {
2387                 key = 0;
2388                 *firstp = 0;
2389         } else {
2390                 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2391                 if ((chain = *chainp) != NULL) {
2392                         *chainp = NULL;
2393                         hammer2_chain_unlock(chain);
2394                         hammer2_chain_drop(chain);
2395                         chain = NULL;
2396                 }
2397                 if (key == 0) {
2398                         bref = NULL;
2399                         goto done;
2400                 }
2401         }
2402
2403 again:
2404         KKASSERT(parent->error == 0);   /* XXX case not handled yet */
2405         if (--maxloops == 0)
2406                 panic("hammer2_chain_scan: maxloops");
2407         /*
2408          * Locate the blockref array.  Currently we do a fully associative
2409          * search through the array.
2410          */
2411         switch(parent->bref.type) {
2412         case HAMMER2_BREF_TYPE_INODE:
2413                 /*
2414                  * An inode with embedded data has no sub-chains.
2415                  *
2416                  * WARNING! Bulk scan code may pass a static chain marked
2417                  *          as BREF_TYPE_INODE with a copy of the volume
2418                  *          root blockset to snapshot the volume.
2419                  */
2420                 if (parent->data->ipdata.meta.op_flags &
2421                     HAMMER2_OPFLAG_DIRECTDATA) {
2422                         bref = NULL;
2423                         goto done;
2424                 }
2425                 base = &parent->data->ipdata.u.blockset.blockref[0];
2426                 count = HAMMER2_SET_COUNT;
2427                 break;
2428         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2429         case HAMMER2_BREF_TYPE_INDIRECT:
2430                 /*
2431                  * Optimize indirect blocks in the INITIAL state to avoid
2432                  * I/O.
2433                  */
2434                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2435                         base = NULL;
2436                 } else {
2437                         if (parent->data == NULL)
2438                                 panic("parent->data is NULL");
2439                         base = &parent->data->npdata[0];
2440                 }
2441                 count = parent->bytes / sizeof(hammer2_blockref_t);
2442                 break;
2443         case HAMMER2_BREF_TYPE_VOLUME:
2444                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2445                 count = HAMMER2_SET_COUNT;
2446                 break;
2447         case HAMMER2_BREF_TYPE_FREEMAP:
2448                 base = &parent->data->blkset.blockref[0];
2449                 count = HAMMER2_SET_COUNT;
2450                 break;
2451         default:
2452                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2453                       parent->bref.type);
2454                 base = NULL;    /* safety */
2455                 count = 0;      /* safety */
2456         }
2457
2458         /*
2459          * Merged scan to find next candidate.
2460          *
2461          * hammer2_base_*() functions require the parent->core.live_* fields
2462          * to be synchronized.
2463          *
2464          * We need to hold the spinlock to access the block array and RB tree
2465          * and to interlock chain creation.
2466          */
2467         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2468                 hammer2_chain_countbrefs(parent, base, count);
2469
2470         next_key = 0;
2471         bref_ptr = NULL;
2472         hammer2_spin_ex(&parent->core.spin);
2473         chain = hammer2_combined_find(parent, base, count,
2474                                       cache_indexp, &next_key,
2475                                       key, HAMMER2_KEY_MAX,
2476                                       &bref_ptr);
2477         generation = parent->core.generation;
2478
2479         /*
2480          * Exhausted parent chain, we're done.
2481          */
2482         if (bref_ptr == NULL) {
2483                 hammer2_spin_unex(&parent->core.spin);
2484                 KKASSERT(chain == NULL);
2485                 bref = NULL;
2486                 goto done;
2487         }
2488
2489         /*
2490          * Copy into the supplied stack-based blockref.
2491          */
2492         *bref = *bref_ptr;
2493
2494         /*
2495          * Selected from blockref or in-memory chain.
2496          */
2497         if (chain == NULL) {
2498                 switch(bref->type) {
2499                 case HAMMER2_BREF_TYPE_INODE:
2500                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2501                 case HAMMER2_BREF_TYPE_INDIRECT:
2502                 case HAMMER2_BREF_TYPE_VOLUME:
2503                 case HAMMER2_BREF_TYPE_FREEMAP:
2504                         /*
2505                          * Recursion, always get the chain
2506                          */
2507                         hammer2_spin_unex(&parent->core.spin);
2508                         chain = hammer2_chain_get(parent, generation, bref);
2509                         if (chain == NULL) {
2510                                 kprintf("retry scan parent %p keys %016jx\n",
2511                                         parent, key);
2512                                 goto again;
2513                         }
2514                         if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2515                                 hammer2_chain_drop(chain);
2516                                 chain = NULL;
2517                                 goto again;
2518                         }
2519                         break;
2520                 default:
2521                         /*
2522                          * No recursion, do not waste time instantiating
2523                          * a chain, just iterate using the bref.
2524                          */
2525                         hammer2_spin_unex(&parent->core.spin);
2526                         break;
2527                 }
2528         } else {
2529                 /*
2530                  * Recursion or not we need the chain in order to supply
2531                  * the bref.
2532                  */
2533                 hammer2_chain_ref(chain);
2534                 hammer2_spin_unex(&parent->core.spin);
2535         }
2536
2537         /*
2538          * chain is referenced but not locked.  We must lock the chain
2539          * to obtain definitive DUPLICATED/DELETED state
2540          */
2541         if (chain)
2542                 hammer2_chain_lock(chain, how);
2543
2544         /*
2545          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2546          *
2547          * NOTE: chain's key range is not relevant as there might be
2548          *       one-offs within the range that are not deleted.
2549          *
2550          * NOTE: XXX this could create problems with scans used in
2551          *       situations other than mount-time recovery.
2552          *
2553          * NOTE: Lookups can race delete-duplicate because
2554          *       delete-duplicate does not lock the parent's core
2555          *       (they just use the spinlock on the core).  We must
2556          *       check for races by comparing the DUPLICATED flag before
2557          *       releasing the spinlock with the flag after locking the
2558          *       chain.
2559          */
2560         if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2561                 hammer2_chain_unlock(chain);
2562                 hammer2_chain_drop(chain);
2563                 chain = NULL;
2564
2565                 key = next_key;
2566                 if (key == 0) {
2567                         bref = NULL;
2568                         goto done;
2569                 }
2570                 goto again;
2571         }
2572
2573 done:
2574         /*
2575          * All done, return the bref or NULL, supply chain if necessary.
2576          */
2577         if (chain)
2578                 *chainp = chain;
2579         return (bref);
2580 }
2581
2582 /*
2583  * Create and return a new hammer2 system memory structure of the specified
2584  * key, type and size and insert it under (*parentp).  This is a full
2585  * insertion, based on the supplied key/keybits, and may involve creating
2586  * indirect blocks and moving other chains around via delete/duplicate.
2587  *
2588  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2589  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2590  * FULL.  This typically means that the caller is creating the chain after
2591  * doing a hammer2_chain_lookup().
2592  *
2593  * (*parentp) must be exclusive locked and may be replaced on return
2594  * depending on how much work the function had to do.
2595  *
2596  * (*parentp) must not be errored or this function will assert.
2597  *
2598  * (*chainp) usually starts out NULL and returns the newly created chain,
2599  * but if the caller desires the caller may allocate a disconnected chain
2600  * and pass it in instead.
2601  *
2602  * This function should NOT be used to insert INDIRECT blocks.  It is
2603  * typically used to create/insert inodes and data blocks.
2604  *
2605  * Caller must pass-in an exclusively locked parent the new chain is to
2606  * be inserted under, and optionally pass-in a disconnected, exclusively
2607  * locked chain to insert (else we create a new chain).  The function will
2608  * adjust (*parentp) as necessary, create or connect the chain, and
2609  * return an exclusively locked chain in *chainp.
2610  *
2611  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2612  * and will be reassigned.
2613  */
2614 int
2615 hammer2_chain_create(hammer2_chain_t **parentp,
2616                      hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2617                      hammer2_key_t key, int keybits, int type, size_t bytes,
2618                      hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2619 {
2620         hammer2_dev_t *hmp;
2621         hammer2_chain_t *chain;
2622         hammer2_chain_t *parent;
2623         hammer2_blockref_t *base;
2624         hammer2_blockref_t dummy;
2625         int allocated = 0;
2626         int error = 0;
2627         int count;
2628         int maxloops = 300000;
2629
2630         /*
2631          * Topology may be crossing a PFS boundary.
2632          */
2633         parent = *parentp;
2634         KKASSERT(hammer2_mtx_owned(&parent->lock));
2635         KKASSERT(parent->error == 0);
2636         hmp = parent->hmp;
2637         chain = *chainp;
2638
2639         if (chain == NULL) {
2640                 /*
2641                  * First allocate media space and construct the dummy bref,
2642                  * then allocate the in-memory chain structure.  Set the
2643                  * INITIAL flag for fresh chains which do not have embedded
2644                  * data.
2645                  *
2646                  * XXX for now set the check mode of the child based on
2647                  *     the parent or, if the parent is an inode, the
2648                  *     specification in the inode.
2649                  */
2650                 bzero(&dummy, sizeof(dummy));
2651                 dummy.type = type;
2652                 dummy.key = key;
2653                 dummy.keybits = keybits;
2654                 dummy.data_off = hammer2_getradix(bytes);
2655                 dummy.methods = parent->bref.methods;
2656                 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2657                     parent->data) {
2658                         dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2659                         dummy.methods |= HAMMER2_ENC_CHECK(
2660                                           parent->data->ipdata.meta.check_algo);
2661                 }
2662
2663                 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2664
2665                 /*
2666                  * Lock the chain manually, chain_lock will load the chain
2667                  * which we do NOT want to do.  (note: chain->refs is set
2668                  * to 1 by chain_alloc() for us, but lockcnt is not).
2669                  */
2670                 chain->lockcnt = 1;
2671                 hammer2_mtx_ex(&chain->lock);
2672                 allocated = 1;
2673                 ++curthread->td_tracker;
2674
2675                 /*
2676                  * Set INITIAL to optimize I/O.  The flag will generally be
2677                  * processed when we call hammer2_chain_modify().
2678                  *
2679                  * Recalculate bytes to reflect the actual media block
2680                  * allocation.
2681                  */
2682                 bytes = (hammer2_off_t)1 <<
2683                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2684                 chain->bytes = bytes;
2685
2686                 switch(type) {
2687                 case HAMMER2_BREF_TYPE_VOLUME:
2688                 case HAMMER2_BREF_TYPE_FREEMAP:
2689                         panic("hammer2_chain_create: called with volume type");
2690                         break;
2691                 case HAMMER2_BREF_TYPE_INDIRECT:
2692                         panic("hammer2_chain_create: cannot be used to"
2693                               "create indirect block");
2694                         break;
2695                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2696                         panic("hammer2_chain_create: cannot be used to"
2697                               "create freemap root or node");
2698                         break;
2699                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2700                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2701                         /* fall through */
2702                 case HAMMER2_BREF_TYPE_INODE:
2703                 case HAMMER2_BREF_TYPE_DATA:
2704                 default:
2705                         /*
2706                          * leave chain->data NULL, set INITIAL
2707                          */
2708                         KKASSERT(chain->data == NULL);
2709                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2710                         break;
2711                 }
2712         } else {
2713                 /*
2714                  * We are reattaching a previously deleted chain, possibly
2715                  * under a new parent and possibly with a new key/keybits.
2716                  * The chain does not have to be in a modified state.  The
2717                  * UPDATE flag will be set later on in this routine.
2718                  *
2719                  * Do NOT mess with the current state of the INITIAL flag.
2720                  */
2721                 chain->bref.key = key;
2722                 chain->bref.keybits = keybits;
2723                 if (chain->flags & HAMMER2_CHAIN_DELETED)
2724                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2725                 KKASSERT(chain->parent == NULL);
2726         }
2727         if (flags & HAMMER2_INSERT_PFSROOT)
2728                 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2729         else
2730                 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2731
2732         /*
2733          * Calculate how many entries we have in the blockref array and
2734          * determine if an indirect block is required.
2735          */
2736 again:
2737         if (--maxloops == 0)
2738                 panic("hammer2_chain_create: maxloops");
2739
2740         switch(parent->bref.type) {
2741         case HAMMER2_BREF_TYPE_INODE:
2742                 if ((parent->data->ipdata.meta.op_flags &
2743                      HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2744                         kprintf("hammer2: parent set for direct-data! "
2745                                 "pkey=%016jx ckey=%016jx\n",
2746                                 parent->bref.key,
2747                                 chain->bref.key);
2748                 }
2749                 KKASSERT((parent->data->ipdata.meta.op_flags &
2750                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2751                 KKASSERT(parent->data != NULL);
2752                 base = &parent->data->ipdata.u.blockset.blockref[0];
2753                 count = HAMMER2_SET_COUNT;
2754                 break;
2755         case HAMMER2_BREF_TYPE_INDIRECT:
2756         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2757                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2758                         base = NULL;
2759                 else
2760                         base = &parent->data->npdata[0];
2761                 count = parent->bytes / sizeof(hammer2_blockref_t);
2762                 break;
2763         case HAMMER2_BREF_TYPE_VOLUME:
2764                 KKASSERT(parent->data != NULL);
2765                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2766                 count = HAMMER2_SET_COUNT;
2767                 break;
2768         case HAMMER2_BREF_TYPE_FREEMAP:
2769                 KKASSERT(parent->data != NULL);
2770                 base = &parent->data->blkset.blockref[0];
2771                 count = HAMMER2_SET_COUNT;
2772                 break;
2773         default:
2774                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2775                       parent->bref.type);
2776                 base = NULL;
2777                 count = 0;
2778                 break;
2779         }
2780
2781         /*
2782          * Make sure we've counted the brefs
2783          */
2784         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2785                 hammer2_chain_countbrefs(parent, base, count);
2786
2787         KKASSERT(parent->core.live_count >= 0 &&
2788                  parent->core.live_count <= count);
2789
2790         /*
2791          * If no free blockref could be found we must create an indirect
2792          * block and move a number of blockrefs into it.  With the parent
2793          * locked we can safely lock each child in order to delete+duplicate
2794          * it without causing a deadlock.
2795          *
2796          * This may return the new indirect block or the old parent depending
2797          * on where the key falls.  NULL is returned on error.
2798          */
2799         if (parent->core.live_count == count) {
2800                 hammer2_chain_t *nparent;
2801
2802                 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2803                                                         mtid, type, &error);
2804                 if (nparent == NULL) {
2805                         if (allocated)
2806                                 hammer2_chain_drop(chain);
2807                         chain = NULL;
2808                         goto done;
2809                 }
2810                 if (parent != nparent) {
2811                         hammer2_chain_unlock(parent);
2812                         hammer2_chain_drop(parent);
2813                         parent = *parentp = nparent;
2814                 }
2815                 goto again;
2816         }
2817
2818         /*
2819          * Link the chain into its parent.
2820          */
2821         if (chain->parent != NULL)
2822                 panic("hammer2: hammer2_chain_create: chain already connected");
2823         KKASSERT(chain->parent == NULL);
2824         hammer2_chain_insert(parent, chain,
2825                              HAMMER2_CHAIN_INSERT_SPIN |
2826                              HAMMER2_CHAIN_INSERT_LIVE,
2827                              0);
2828
2829         if (allocated) {
2830                 /*
2831                  * Mark the newly created chain modified.  This will cause
2832                  * UPDATE to be set and process the INITIAL flag.
2833                  *
2834                  * Device buffers are not instantiated for DATA elements
2835                  * as these are handled by logical buffers.
2836                  *
2837                  * Indirect and freemap node indirect blocks are handled
2838                  * by hammer2_chain_create_indirect() and not by this
2839                  * function.
2840                  *
2841                  * Data for all other bref types is expected to be
2842                  * instantiated (INODE, LEAF).
2843                  */
2844                 switch(chain->bref.type) {
2845                 case HAMMER2_BREF_TYPE_DATA:
2846                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2847                 case HAMMER2_BREF_TYPE_INODE:
2848                         hammer2_chain_modify(chain, mtid, dedup_off,
2849                                              HAMMER2_MODIFY_OPTDATA);
2850                         break;
2851                 default:
2852                         /*
2853                          * Remaining types are not supported by this function.
2854                          * In particular, INDIRECT and LEAF_NODE types are
2855                          * handled by create_indirect().
2856                          */
2857                         panic("hammer2_chain_create: bad type: %d",
2858                               chain->bref.type);
2859                         /* NOT REACHED */
2860                         break;
2861                 }
2862         } else {
2863                 /*
2864                  * When reconnecting a chain we must set UPDATE and
2865                  * setflush so the flush recognizes that it must update
2866                  * the bref in the parent.
2867                  */
2868                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
2869                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2870         }
2871
2872         /*
2873          * We must setflush(parent) to ensure that it recurses through to
2874          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2875          * already set in the chain (so it won't recurse up to set it in the
2876          * parent).
2877          */
2878         hammer2_chain_setflush(parent);
2879
2880 done:
2881         *chainp = chain;
2882
2883         return (error);
2884 }
2885
2886 /*
2887  * Move the chain from its old parent to a new parent.  The chain must have
2888  * already been deleted or already disconnected (or never associated) with
2889  * a parent.  The chain is reassociated with the new parent and the deleted
2890  * flag will be cleared (no longer deleted).  The chain's modification state
2891  * is not altered.
2892  *
2893  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2894  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2895  * FULL.  This typically means that the caller is creating the chain after
2896  * doing a hammer2_chain_lookup().
2897  *
2898  * A non-NULL bref is typically passed when key and keybits must be overridden.
2899  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2900  * from a passed-in bref and uses the old chain's bref for everything else.
2901  *
2902  * Neither (parent) or (chain) can be errored.
2903  *
2904  * If (parent) is non-NULL then the new duplicated chain is inserted under
2905  * the parent.
2906  *
2907  * If (parent) is NULL then the newly duplicated chain is not inserted
2908  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2909  * passing into hammer2_chain_create() after this function returns).
2910  *
2911  * WARNING! This function calls create which means it can insert indirect
2912  *          blocks.  This can cause other unrelated chains in the parent to
2913  *          be moved to a newly inserted indirect block in addition to the
2914  *          specific chain.
2915  */
2916 void
2917 hammer2_chain_rename(hammer2_blockref_t *bref,
2918                      hammer2_chain_t **parentp, hammer2_chain_t *chain,
2919                      hammer2_tid_t mtid, int flags)
2920 {
2921         hammer2_dev_t *hmp;
2922         hammer2_chain_t *parent;
2923         size_t bytes;
2924
2925         /*
2926          * WARNING!  We should never resolve DATA to device buffers
2927          *           (XXX allow it if the caller did?), and since
2928          *           we currently do not have the logical buffer cache
2929          *           buffer in-hand to fix its cached physical offset
2930          *           we also force the modify code to not COW it. XXX
2931          */
2932         hmp = chain->hmp;
2933         KKASSERT(chain->parent == NULL);
2934         KKASSERT(chain->error == 0);
2935
2936         /*
2937          * Now create a duplicate of the chain structure, associating
2938          * it with the same core, making it the same size, pointing it
2939          * to the same bref (the same media block).
2940          */
2941         if (bref == NULL)
2942                 bref = &chain->bref;
2943         bytes = (hammer2_off_t)1 <<
2944                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2945
2946         /*
2947          * If parent is not NULL the duplicated chain will be entered under
2948          * the parent and the UPDATE bit set to tell flush to update
2949          * the blockref.
2950          *
2951          * We must setflush(parent) to ensure that it recurses through to
2952          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2953          * already set in the chain (so it won't recurse up to set it in the
2954          * parent).
2955          *
2956          * Having both chains locked is extremely important for atomicy.
2957          */
2958         if (parentp && (parent = *parentp) != NULL) {
2959                 KKASSERT(hammer2_mtx_owned(&parent->lock));
2960                 KKASSERT(parent->refs > 0);
2961                 KKASSERT(parent->error == 0);
2962
2963                 hammer2_chain_create(parentp, &chain, chain->pmp,
2964                                      bref->key, bref->keybits, bref->type,
2965                                      chain->bytes, mtid, 0, flags);
2966                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2967                 hammer2_chain_setflush(*parentp);
2968         }
2969 }
2970
2971 /*
2972  * Helper function for deleting chains.
2973  *
2974  * The chain is removed from the live view (the RBTREE) as well as the parent's
2975  * blockmap.  Both chain and its parent must be locked.
2976  *
2977  * parent may not be errored.  chain can be errored.
2978  */
2979 static void
2980 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2981                              hammer2_tid_t mtid, int flags)
2982 {
2983         hammer2_dev_t *hmp;
2984
2985         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2986                                   HAMMER2_CHAIN_FICTITIOUS)) == 0);
2987         KKASSERT(chain->parent == parent);
2988         hmp = chain->hmp;
2989
2990         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2991                 /*
2992                  * Chain is blockmapped, so there must be a parent.
2993                  * Atomically remove the chain from the parent and remove
2994                  * the blockmap entry.  The parent must be set modified
2995                  * to remove the blockmap entry.
2996                  */
2997                 hammer2_blockref_t *base;
2998                 int count;
2999
3000                 KKASSERT(parent != NULL);
3001                 KKASSERT(parent->error == 0);
3002                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3003                 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3004
3005                 /*
3006                  * Calculate blockmap pointer
3007                  */
3008                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3009                 hammer2_spin_ex(&parent->core.spin);
3010
3011                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3012                 atomic_add_int(&parent->core.live_count, -1);
3013                 ++parent->core.generation;
3014                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3015                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3016                 --parent->core.chain_count;
3017                 chain->parent = NULL;
3018
3019                 switch(parent->bref.type) {
3020                 case HAMMER2_BREF_TYPE_INODE:
3021                         /*
3022                          * Access the inode's block array.  However, there
3023                          * is no block array if the inode is flagged
3024                          * DIRECTDATA.  The DIRECTDATA case typicaly only
3025                          * occurs when a hardlink has been shifted up the
3026                          * tree and the original inode gets replaced with
3027                          * an OBJTYPE_HARDLINK placeholding inode.
3028                          */
3029                         if (parent->data &&
3030                             (parent->data->ipdata.meta.op_flags &
3031                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3032                                 base =
3033                                    &parent->data->ipdata.u.blockset.blockref[0];
3034                         } else {
3035                                 base = NULL;
3036                         }
3037                         count = HAMMER2_SET_COUNT;
3038                         break;
3039                 case HAMMER2_BREF_TYPE_INDIRECT:
3040                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3041                         if (parent->data)
3042                                 base = &parent->data->npdata[0];
3043                         else
3044                                 base = NULL;
3045                         count = parent->bytes / sizeof(hammer2_blockref_t);
3046                         break;
3047                 case HAMMER2_BREF_TYPE_VOLUME:
3048                         base = &parent->data->voldata.
3049                                         sroot_blockset.blockref[0];
3050                         count = HAMMER2_SET_COUNT;
3051                         break;
3052                 case HAMMER2_BREF_TYPE_FREEMAP:
3053                         base = &parent->data->blkset.blockref[0];
3054                         count = HAMMER2_SET_COUNT;
3055                         break;
3056                 default:
3057                         base = NULL;
3058                         count = 0;
3059                         panic("hammer2_flush_pass2: "
3060                               "unrecognized blockref type: %d",
3061                               parent->bref.type);
3062                 }
3063
3064                 /*
3065                  * delete blockmapped chain from its parent.
3066                  *
3067                  * The parent is not affected by any statistics in chain
3068                  * which are pending synchronization.  That is, there is
3069                  * nothing to undo in the parent since they have not yet
3070                  * been incorporated into the parent.
3071                  *
3072                  * The parent is affected by statistics stored in inodes.
3073                  * Those have already been synchronized, so they must be
3074                  * undone.  XXX split update possible w/delete in middle?
3075                  */
3076                 if (base) {
3077                         int cache_index = -1;
3078                         hammer2_base_delete(parent, base, count,
3079                                             &cache_index, chain);
3080                 }
3081                 hammer2_spin_unex(&parent->core.spin);
3082         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3083                 /*
3084                  * Chain is not blockmapped but a parent is present.
3085                  * Atomically remove the chain from the parent.  There is
3086                  * no blockmap entry to remove.
3087                  *
3088                  * Because chain was associated with a parent but not
3089                  * synchronized, the chain's *_count_up fields contain
3090                  * inode adjustment statistics which must be undone.
3091                  */
3092                 hammer2_spin_ex(&parent->core.spin);
3093                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3094                 atomic_add_int(&parent->core.live_count, -1);
3095                 ++parent->core.generation;
3096                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3097                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3098                 --parent->core.chain_count;
3099                 chain->parent = NULL;
3100                 hammer2_spin_unex(&parent->core.spin);
3101         } else {
3102                 /*
3103                  * Chain is not blockmapped and has no parent.  This
3104                  * is a degenerate case.
3105                  */
3106                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3107         }
3108 }
3109
3110 /*
3111  * Create an indirect block that covers one or more of the elements in the
3112  * current parent.  Either returns the existing parent with no locking or
3113  * ref changes or returns the new indirect block locked and referenced
3114  * and leaving the original parent lock/ref intact as well.
3115  *
3116  * If an error occurs, NULL is returned and *errorp is set to the error.
3117  *
3118  * The returned chain depends on where the specified key falls.
3119  *
3120  * The key/keybits for the indirect mode only needs to follow three rules:
3121  *
3122  * (1) That all elements underneath it fit within its key space and
3123  *
3124  * (2) That all elements outside it are outside its key space.
3125  *
3126  * (3) When creating the new indirect block any elements in the current
3127  *     parent that fit within the new indirect block's keyspace must be
3128  *     moved into the new indirect block.
3129  *
3130  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3131  *     keyspace the the current parent, but lookup/iteration rules will
3132  *     ensure (and must ensure) that rule (2) for all parents leading up
3133  *     to the nearest inode or the root volume header is adhered to.  This
3134  *     is accomplished by always recursing through matching keyspaces in
3135  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3136  *
3137  * The current implementation calculates the current worst-case keyspace by
3138  * iterating the current parent and then divides it into two halves, choosing
3139  * whichever half has the most elements (not necessarily the half containing
3140  * the requested key).
3141  *
3142  * We can also opt to use the half with the least number of elements.  This
3143  * causes lower-numbered keys (aka logical file offsets) to recurse through
3144  * fewer indirect blocks and higher-numbered keys to recurse through more.
3145  * This also has the risk of not moving enough elements to the new indirect
3146  * block and being forced to create several indirect blocks before the element
3147  * can be inserted.
3148  *
3149  * Must be called with an exclusively locked parent.
3150  */
3151 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3152                                 hammer2_key_t *keyp, int keybits,
3153                                 hammer2_blockref_t *base, int count);
3154 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3155                                 hammer2_key_t *keyp, int keybits,
3156                                 hammer2_blockref_t *base, int count);
3157 static
3158 hammer2_chain_t *
3159 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3160                               hammer2_key_t create_key, int create_bits,
3161                               hammer2_tid_t mtid, int for_type, int *errorp)
3162 {
3163         hammer2_dev_t *hmp;
3164         hammer2_blockref_t *base;
3165         hammer2_blockref_t *bref;
3166         hammer2_blockref_t bcopy;
3167         hammer2_chain_t *chain;
3168         hammer2_chain_t *ichain;
3169         hammer2_chain_t dummy;
3170         hammer2_key_t key = create_key;
3171         hammer2_key_t key_beg;
3172         hammer2_key_t key_end;
3173         hammer2_key_t key_next;
3174         int keybits = create_bits;
3175         int count;
3176         int nbytes;
3177         int cache_index;
3178         int loops;
3179         int reason;
3180         int generation;
3181         int maxloops = 300000;
3182
3183         /*
3184          * Calculate the base blockref pointer or NULL if the chain
3185          * is known to be empty.  We need to calculate the array count
3186          * for RB lookups either way.
3187          */
3188         hmp = parent->hmp;
3189         *errorp = 0;
3190         KKASSERT(hammer2_mtx_owned(&parent->lock));
3191
3192         /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3193         base = hammer2_chain_base_and_count(parent, &count);
3194
3195         /*
3196          * dummy used in later chain allocation (no longer used for lookups).
3197          */
3198         bzero(&dummy, sizeof(dummy));
3199
3200         /*
3201          * When creating an indirect block for a freemap node or leaf
3202          * the key/keybits must be fitted to static radix levels because
3203          * particular radix levels use particular reserved blocks in the
3204          * related zone.
3205          *
3206          * This routine calculates the key/radix of the indirect block
3207          * we need to create, and whether it is on the high-side or the
3208          * low-side.
3209          */
3210         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3211             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3212                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3213                                                        base, count);
3214         } else {
3215                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3216                                                       base, count);
3217         }
3218
3219         /*
3220          * Normalize the key for the radix being represented, keeping the
3221          * high bits and throwing away the low bits.
3222          */
3223         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3224
3225         /*
3226          * How big should our new indirect block be?  It has to be at least
3227          * as large as its parent.
3228          *
3229          * The freemap uses a specific indirect block size.
3230          *
3231          * The first indirect block level down from an inode typically
3232          * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3233          */
3234         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3235             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3236                 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3237         } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3238                 nbytes = HAMMER2_IND_BYTES_MIN;
3239         } else {
3240                 nbytes = HAMMER2_IND_BYTES_MAX;
3241         }
3242         if (nbytes < count * sizeof(hammer2_blockref_t)) {
3243                 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3244                          for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3245                 nbytes = count * sizeof(hammer2_blockref_t);
3246         }
3247
3248         /*
3249          * Ok, create our new indirect block
3250          */
3251         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3252             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3253                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3254         } else {
3255                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3256         }
3257         dummy.bref.key = key;
3258         dummy.bref.keybits = keybits;
3259         dummy.bref.data_off = hammer2_getradix(nbytes);
3260         dummy.bref.methods = parent->bref.methods;
3261
3262         ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3263         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3264         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3265         /* ichain has one ref at this point */
3266
3267         /*
3268          * We have to mark it modified to allocate its block, but use
3269          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3270          * it won't be acted upon by the flush code.
3271          */
3272         hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3273
3274         /*
3275          * Iterate the original parent and move the matching brefs into
3276          * the new indirect block.
3277          *
3278          * XXX handle flushes.
3279          */
3280         key_beg = 0;
3281         key_end = HAMMER2_KEY_MAX;
3282         cache_index = 0;
3283         hammer2_spin_ex(&parent->core.spin);
3284         loops = 0;
3285         reason = 0;
3286
3287         for (;;) {
3288                 /*
3289                  * Parent may have been modified, relocating its block array.
3290                  * Reload the base pointer.
3291                  */
3292                 base = hammer2_chain_base_and_count(parent, &count);
3293
3294                 if (++loops > 100000) {
3295                     hammer2_spin_unex(&parent->core.spin);
3296                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3297                           reason, parent, base, count, key_next);
3298                 }
3299
3300                 /*
3301                  * NOTE: spinlock stays intact, returned chain (if not NULL)
3302                  *       is not referenced or locked which means that we
3303                  *       cannot safely check its flagged / deletion status
3304                  *       until we lock it.
3305                  */
3306                 chain = hammer2_combined_find(parent, base, count,
3307                                               &cache_index, &key_next,
3308                                               key_beg, key_end,
3309                                               &bref);
3310                 generation = parent->core.generation;
3311                 if (bref == NULL)
3312                         break;
3313                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3314
3315                 /*
3316                  * Skip keys that are not within the key/radix of the new
3317                  * indirect block.  They stay in the parent.
3318                  */
3319                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3320                     (key ^ bref->key)) != 0) {
3321                         goto next_key_spinlocked;
3322                 }
3323
3324                 /*
3325                  * Load the new indirect block by acquiring the related
3326                  * chains (potentially from media as it might not be
3327                  * in-memory).  Then move it to the new parent (ichain)
3328                  * via DELETE-DUPLICATE.
3329                  *
3330                  * chain is referenced but not locked.  We must lock the
3331                  * chain to obtain definitive DUPLICATED/DELETED state
3332                  */
3333                 if (chain) {
3334                         /*
3335                          * Use chain already present in the RBTREE
3336                          */
3337                         hammer2_chain_ref(chain);
3338                         hammer2_spin_unex(&parent->core.spin);
3339                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3340                 } else {
3341                         /*
3342                          * Get chain for blockref element.  _get returns NULL
3343                          * on insertion race.
3344                          */
3345                         bcopy = *bref;
3346                         hammer2_spin_unex(&parent->core.spin);
3347                         chain = hammer2_chain_get(parent, generation, &bcopy);
3348                         if (chain == NULL) {
3349                                 reason = 1;
3350                                 hammer2_spin_ex(&parent->core.spin);
3351                                 continue;
3352                         }
3353                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3354                                 kprintf("REASON 2\n");
3355                                 reason = 2;
3356                                 hammer2_chain_drop(chain);
3357                                 hammer2_spin_ex(&parent->core.spin);
3358                                 continue;
3359                         }
3360                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3361                 }
3362
3363                 /*
3364                  * This is always live so if the chain has been deleted
3365                  * we raced someone and we have to retry.
3366                  *
3367                  * NOTE: Lookups can race delete-duplicate because
3368                  *       delete-duplicate does not lock the parent's core
3369                  *       (they just use the spinlock on the core).  We must
3370                  *       check for races by comparing the DUPLICATED flag before
3371                  *       releasing the spinlock with the flag after locking the
3372                  *       chain.
3373                  *
3374                  *       (note reversed logic for this one)
3375                  */
3376                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3377                         hammer2_chain_unlock(chain);
3378                         hammer2_chain_drop(chain);
3379                         goto next_key;
3380                 }
3381
3382                 /*
3383                  * Shift the chain to the indirect block.
3384                  *
3385                  * WARNING! No reason for us to load chain data, pass NOSTATS
3386                  *          to prevent delete/insert from trying to access
3387                  *          inode stats (and thus asserting if there is no
3388                  *          chain->data loaded).
3389                  *
3390                  * WARNING! The (parent, chain) deletion may modify the parent
3391                  *          and invalidate the base pointer.
3392                  */
3393                 hammer2_chain_delete(parent, chain, mtid, 0);
3394                 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3395                 hammer2_chain_unlock(chain);
3396                 hammer2_chain_drop(chain);
3397                 KKASSERT(parent->refs > 0);
3398                 chain = NULL;
3399                 base = NULL;    /* safety */
3400 next_key:
3401                 hammer2_spin_ex(&parent->core.spin);
3402 next_key_spinlocked:
3403                 if (--maxloops == 0)
3404                         panic("hammer2_chain_create_indirect: maxloops");
3405                 reason = 4;
3406                 if (key_next == 0 || key_next > key_end)
3407                         break;
3408                 key_beg = key_next;
3409                 /* loop */
3410         }
3411         hammer2_spin_unex(&parent->core.spin);
3412
3413         /*
3414          * Insert the new indirect block into the parent now that we've
3415          * cleared out some entries in the parent.  We calculated a good
3416          * insertion index in the loop above (ichain->index).
3417          *
3418          * We don't have to set UPDATE here because we mark ichain
3419          * modified down below (so the normal modified -> flush -> set-moved
3420          * sequence applies).
3421          *
3422          * The insertion shouldn't race as this is a completely new block
3423          * and the parent is locked.
3424          */
3425         base = NULL;    /* safety, parent modify may change address */
3426         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3427         hammer2_chain_insert(parent, ichain,
3428                              HAMMER2_CHAIN_INSERT_SPIN |
3429                              HAMMER2_CHAIN_INSERT_LIVE,
3430                              0);
3431
3432         /*
3433          * Make sure flushes propogate after our manual insertion.
3434          */
3435         hammer2_chain_setflush(ichain);
3436         hammer2_chain_setflush(parent);
3437
3438         /*
3439          * Figure out what to return.
3440          */
3441         if (~(((hammer2_key_t)1 << keybits) - 1) &
3442                    (create_key ^ key)) {
3443                 /*
3444                  * Key being created is outside the key range,
3445                  * return the original parent.
3446                  */
3447                 hammer2_chain_unlock(ichain);
3448                 hammer2_chain_drop(ichain);
3449         } else {
3450                 /*
3451                  * Otherwise its in the range, return the new parent.
3452                  * (leave both the new and old parent locked).
3453                  */
3454                 parent = ichain;
3455         }
3456
3457         return(parent);
3458 }
3459
3460 /*
3461  * Calculate the keybits and highside/lowside of the freemap node the
3462  * caller is creating.
3463  *
3464  * This routine will specify the next higher-level freemap key/radix
3465  * representing the lowest-ordered set.  By doing so, eventually all
3466  * low-ordered sets will be moved one level down.
3467  *
3468  * We have to be careful here because the freemap reserves a limited
3469  * number of blocks for a limited number of levels.  So we can't just
3470  * push indiscriminately.
3471  */
3472 int
3473 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3474                              int keybits, hammer2_blockref_t *base, int count)
3475 {
3476         hammer2_chain_t *chain;
3477         hammer2_blockref_t *bref;
3478         hammer2_key_t key;
3479         hammer2_key_t key_beg;
3480         hammer2_key_t key_end;
3481         hammer2_key_t key_next;
3482         int cache_index;
3483         int locount;
3484         int hicount;
3485         int maxloops = 300000;
3486
3487         key = *keyp;
3488         locount = 0;
3489         hicount = 0;
3490         keybits = 64;
3491
3492         /*
3493          * Calculate the range of keys in the array being careful to skip
3494          * slots which are overridden with a deletion.
3495          */
3496         key_beg = 0;
3497         key_end = HAMMER2_KEY_MAX;
3498         cache_index = 0;
3499         hammer2_spin_ex(&parent->core.spin);
3500
3501         for (;;) {
3502                 if (--maxloops == 0) {
3503                         panic("indkey_freemap shit %p %p:%d\n",
3504                               parent, base, count);
3505                 }
3506                 chain = hammer2_combined_find(parent, base, count,
3507                                               &cache_index, &key_next,
3508                                               key_beg, key_end,
3509                                               &bref);
3510
3511                 /*
3512                  * Exhausted search
3513                  */
3514                 if (bref == NULL)
3515                         break;
3516
3517                 /*
3518                  * Skip deleted chains.
3519                  */
3520                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3521                         if (key_next == 0 || key_next > key_end)
3522                                 break;
3523                         key_beg = key_next;
3524                         continue;
3525                 }
3526
3527                 /*
3528                  * Use the full live (not deleted) element for the scan
3529                  * iteration.  HAMMER2 does not allow partial replacements.
3530                  *
3531                  * XXX should be built into hammer2_combined_find().
3532                  */
3533                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3534
3535                 if (keybits > bref->keybits) {
3536                         key = bref->key;
3537                         keybits = bref->keybits;
3538                 } else if (keybits == bref->keybits && bref->key < key) {
3539                         key = bref->key;
3540                 }
3541                 if (key_next == 0)
3542                         break;
3543                 key_beg = key_next;
3544         }
3545         hammer2_spin_unex(&parent->core.spin);
3546
3547         /*
3548          * Return the keybits for a higher-level FREEMAP_NODE covering
3549          * this node.
3550          */
3551         switch(keybits) {
3552         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3553                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3554                 break;
3555         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3556                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3557                 break;
3558         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3559                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3560                 break;
3561         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3562                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3563                 break;
3564         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3565                 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3566                 break;
3567         case HAMMER2_FREEMAP_LEVEL5_RADIX:
3568                 panic("hammer2_chain_indkey_freemap: level too high");
3569                 break;
3570         default:
3571                 panic("hammer2_chain_indkey_freemap: bad radix");
3572                 break;
3573         }
3574         *keyp = key;
3575
3576         return (keybits);
3577 }
3578
3579 /*
3580  * Calculate the keybits and highside/lowside of the indirect block the
3581  * caller is creating.
3582  */
3583 static int
3584 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3585                             int keybits, hammer2_blockref_t *base, int count)
3586 {
3587         hammer2_blockref_t *bref;
3588         hammer2_chain_t *chain;
3589         hammer2_key_t key_beg;
3590         hammer2_key_t key_end;
3591         hammer2_key_t key_next;
3592         hammer2_key_t key;
3593         int nkeybits;
3594         int locount;
3595         int hicount;
3596         int cache_index;
3597         int maxloops = 300000;
3598
3599         key = *keyp;
3600         locount = 0;
3601         hicount = 0;
3602
3603         /*
3604          * Calculate the range of keys in the array being careful to skip
3605          * slots which are overridden with a deletion.  Once the scan
3606          * completes we will cut the key range in half and shift half the
3607          * range into the new indirect block.
3608          */
3609         key_beg = 0;
3610         key_end = HAMMER2_KEY_MAX;
3611         cache_index = 0;
3612         hammer2_spin_ex(&parent->core.spin);
3613
3614         for (;;) {
3615                 if (--maxloops == 0) {
3616                         panic("indkey_freemap shit %p %p:%d\n",
3617                               parent, base, count);
3618                 }
3619                 chain = hammer2_combined_find(parent, base, count,
3620                                               &cache_index, &key_next,
3621                                               key_beg, key_end,
3622                                               &bref);
3623
3624                 /*
3625                  * Exhausted search
3626                  */
3627                 if (bref == NULL)
3628                         break;
3629
3630                 /*
3631                  * NOTE: No need to check DUPLICATED here because we do
3632                  *       not release the spinlock.
3633                  */
3634                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3635                         if (key_next == 0 || key_next > key_end)
3636                                 break;
3637                         key_beg = key_next;
3638                         continue;
3639                 }
3640
3641                 /*
3642                  * Use the full live (not deleted) element for the scan
3643                  * iteration.  HAMMER2 does not allow partial replacements.
3644                  *
3645                  * XXX should be built into hammer2_combined_find().
3646                  */
3647                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3648
3649                 /*
3650                  * Expand our calculated key range (key, keybits) to fit
3651                  * the scanned key.  nkeybits represents the full range
3652                  * that we will later cut in half (two halves @ nkeybits - 1).
3653                  */
3654                 nkeybits = keybits;
3655                 if (nkeybits < bref->keybits) {
3656                         if (bref->keybits > 64) {
3657                                 kprintf("bad bref chain %p bref %p\n",
3658                                         chain, bref);
3659                                 Debugger("fubar");
3660                         }
3661                         nkeybits = bref->keybits;
3662                 }
3663                 while (nkeybits < 64 &&
3664                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3665                         (key ^ bref->key)) != 0) {
3666                         ++nkeybits;
3667                 }
3668
3669                 /*
3670                  * If the new key range is larger we have to determine
3671                  * which side of the new key range the existing keys fall
3672                  * under by checking the high bit, then collapsing the
3673                  * locount into the hicount or vise-versa.
3674                  */
3675                 if (keybits != nkeybits) {
3676                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3677                                 hicount += locount;
3678                                 locount = 0;
3679                         } else {
3680                                 locount += hicount;
3681                                 hicount = 0;
3682                         }
3683                         keybits = nkeybits;
3684                 }
3685
3686                 /*
3687                  * The newly scanned key will be in the lower half or the
3688                  * upper half of the (new) key range.
3689                  */
3690                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3691                         ++hicount;
3692                 else
3693                         ++locount;
3694
3695                 if (key_next == 0)
3696                         break;
3697                 key_beg = key_next;
3698         }
3699         hammer2_spin_unex(&parent->core.spin);
3700         bref = NULL;    /* now invalid (safety) */
3701
3702         /*
3703          * Adjust keybits to represent half of the full range calculated
3704          * above (radix 63 max)
3705          */
3706         --keybits;
3707
3708         /*
3709          * Select whichever half contains the most elements.  Theoretically
3710          * we can select either side as long as it contains at least one
3711          * element (in order to ensure that a free slot is present to hold
3712          * the indirect block).
3713          */
3714         if (hammer2_indirect_optimize) {
3715                 /*
3716                  * Insert node for least number of keys, this will arrange
3717                  * the first few blocks of a large file or the first few
3718                  * inodes in a directory with fewer indirect blocks when
3719                  * created linearly.
3720                  */
3721                 if (hicount < locount && hicount != 0)
3722                         key |= (hammer2_key_t)1 << keybits;
3723                 else
3724                         key &= ~(hammer2_key_t)1 << keybits;
3725         } else {
3726                 /*
3727                  * Insert node for most number of keys, best for heavily
3728                  * fragmented files.
3729                  */
3730                 if (hicount > locount)
3731                         key |= (hammer2_key_t)1 << keybits;
3732                 else
3733                         key &= ~(hammer2_key_t)1 << keybits;
3734         }
3735         *keyp = key;
3736
3737         return (keybits);
3738 }
3739
3740 /*
3741  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3742  * it exists.
3743  *
3744  * Both parent and chain must be locked exclusively.
3745  *
3746  * This function will modify the parent if the blockref requires removal
3747  * from the parent's block table.
3748  *
3749  * This function is NOT recursive.  Any entity already pushed into the
3750  * chain (such as an inode) may still need visibility into its contents,
3751  * as well as the ability to read and modify the contents.  For example,
3752  * for an unlinked file which is still open.
3753  */
3754 void
3755 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3756                      hammer2_tid_t mtid, int flags)
3757 {
3758         KKASSERT(hammer2_mtx_owned(&chain->lock));
3759
3760         /*
3761          * Nothing to do if already marked.
3762          *
3763          * We need the spinlock on the core whos RBTREE contains chain
3764          * to protect against races.
3765          */
3766         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3767                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3768                          chain->parent == parent);
3769                 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3770         }
3771
3772         /*
3773          * Permanent deletions mark the chain as destroyed.
3774          */
3775         if (flags & HAMMER2_DELETE_PERMANENT) {
3776                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3777         } else {
3778                 /* XXX might not be needed */
3779                 hammer2_chain_setflush(chain);
3780         }
3781 }
3782
3783 /*
3784  * Returns the index of the nearest element in the blockref array >= elm.
3785  * Returns (count) if no element could be found.
3786  *
3787  * Sets *key_nextp to the next key for loop purposes but does not modify
3788  * it if the next key would be higher than the current value of *key_nextp.
3789  * Note that *key_nexp can overflow to 0, which should be tested by the
3790  * caller.
3791  *
3792  * (*cache_indexp) is a heuristic and can be any value without effecting
3793  * the result.
3794  *
3795  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3796  *           held through the operation.
3797  */
3798 static int
3799 hammer2_base_find(hammer2_chain_t *parent,
3800                   hammer2_blockref_t *base, int count,
3801                   int *cache_indexp, hammer2_key_t *key_nextp,
3802                   hammer2_key_t key_beg, hammer2_key_t key_end)
3803 {
3804         hammer2_blockref_t *scan;
3805         hammer2_key_t scan_end;
3806         int i;
3807         int limit;
3808
3809         /*
3810          * Require the live chain's already have their core's counted
3811          * so we can optimize operations.
3812          */
3813         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3814
3815         /*
3816          * Degenerate case
3817          */
3818         if (count == 0 || base == NULL)
3819                 return(count);
3820
3821         /*
3822          * Sequential optimization using *cache_indexp.  This is the most
3823          * likely scenario.
3824          *
3825          * We can avoid trailing empty entries on live chains, otherwise
3826          * we might have to check the whole block array.
3827          */
3828         i = *cache_indexp;
3829         cpu_ccfence();
3830         limit = parent->core.live_zero;
3831         if (i >= limit)
3832                 i = limit - 1;
3833         if (i < 0)
3834                 i = 0;
3835         KKASSERT(i < count);
3836
3837         /*
3838          * Search backwards
3839          */
3840         scan = &base[i];
3841         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3842                 --scan;
3843                 --i;
3844         }
3845         *cache_indexp = i;
3846
3847         /*
3848          * Search forwards, stop when we find a scan element which
3849          * encloses the key or until we know that there are no further
3850          * elements.
3851          */
3852         while (i < count) {
3853                 if (scan->type != 0) {
3854                         scan_end = scan->key +
3855                                    ((hammer2_key_t)1 << scan->keybits) - 1;
3856                         if (scan->key > key_beg || scan_end >= key_beg)
3857                                 break;
3858                 }
3859                 if (i >= limit)
3860                         return (count);
3861                 ++scan;
3862                 ++i;
3863         }
3864         if (i != count) {
3865                 *cache_indexp = i;
3866                 if (i >= limit) {
3867                         i = count;
3868                 } else {
3869                         scan_end = scan->key +
3870                                    ((hammer2_key_t)1 << scan->keybits);
3871                         if (scan_end && (*key_nextp > scan_end ||
3872                                          *key_nextp == 0)) {
3873                                 *key_nextp = scan_end;
3874                         }
3875                 }
3876         }
3877         return (i);
3878 }
3879
3880 /*
3881  * Do a combined search and return the next match either from the blockref
3882  * array or from the in-memory chain.  Sets *bresp to the returned bref in
3883  * both cases, or sets it to NULL if the search exhausted.  Only returns
3884  * a non-NULL chain if the search matched from the in-memory chain.
3885  *
3886  * When no in-memory chain has been found and a non-NULL bref is returned
3887  * in *bresp.
3888  *
3889  *
3890  * The returned chain is not locked or referenced.  Use the returned bref
3891  * to determine if the search exhausted or not.  Iterate if the base find
3892  * is chosen but matches a deleted chain.
3893  *
3894  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3895  *           held through the operation.
3896  */
3897 static hammer2_chain_t *
3898 hammer2_combined_find(hammer2_chain_t *parent,
3899                       hammer2_blockref_t *base, int count,
3900                       int *cache_indexp, hammer2_key_t *key_nextp,
3901                       hammer2_key_t key_beg, hammer2_key_t key_end,
3902                       hammer2_blockref_t **bresp)
3903 {
3904         hammer2_blockref_t *bref;
3905         hammer2_chain_t *chain;
3906         int i;
3907
3908         /*
3909          * Lookup in block array and in rbtree.
3910          */
3911         *key_nextp = key_end + 1;
3912         i = hammer2_base_find(parent, base, count, cache_indexp,
3913                               key_nextp, key_beg, key_end);
3914         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3915
3916         /*
3917          * Neither matched
3918          */
3919         if (i == count && chain == NULL) {
3920                 *bresp = NULL;
3921                 return(NULL);
3922         }
3923
3924         /*
3925          * Only chain matched.
3926          */
3927         if (i == count) {
3928                 bref = &chain->bref;
3929                 goto found;
3930         }
3931
3932         /*
3933          * Only blockref matched.
3934          */
3935         if (chain == NULL) {
3936                 bref = &base[i];
3937                 goto found;
3938         }
3939
3940         /*
3941          * Both in-memory and blockref matched, select the nearer element.
3942          *
3943          * If both are flush with the left-hand side or both are the
3944          * same distance away, select the chain.  In this situation the
3945          * chain must have been loaded from the matching blockmap.
3946          */
3947         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3948             chain->bref.key == base[i].key) {
3949                 KKASSERT(chain->bref.key == base[i].key);
3950                 bref = &chain->bref;
3951                 goto found;
3952         }
3953
3954         /*
3955          * Select the nearer key
3956          */
3957         if (chain->bref.key < base[i].key) {
3958                 bref = &chain->bref;
3959         } else {
3960                 bref = &base[i];
3961                 chain = NULL;
3962         }
3963
3964         /*
3965          * If the bref is out of bounds we've exhausted our search.
3966          */
3967 found:
3968         if (bref->key > key_end) {
3969                 *bresp = NULL;
3970                 chain = NULL;
3971         } else {
3972                 *bresp = bref;
3973         }
3974         return(chain);
3975 }
3976
3977 /*
3978  * Locate the specified block array element and delete it.  The element
3979  * must exist.
3980  *
3981  * The spin lock on the related chain must be held.
3982  *
3983  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3984  *       need to be adjusted when we commit the media change.
3985  */
3986 void
3987 hammer2_base_delete(hammer2_chain_t *parent,
3988                     hammer2_blockref_t *base, int count,
3989                     int *cache_indexp, hammer2_chain_t *chain)
3990 {
3991         hammer2_blockref_t *elm = &chain->bref;
3992         hammer2_key_t key_next;
3993         int i;
3994
3995         /*
3996          * Delete element.  Expect the element to exist.
3997          *
3998          * XXX see caller, flush code not yet sophisticated enough to prevent
3999          *     re-flushed in some cases.
4000          */
4001         key_next = 0; /* max range */
4002         i = hammer2_base_find(parent, base, count, cache_indexp,
4003                               &key_next, elm->key, elm->key);
4004         if (i == count || base[i].type == 0 ||
4005             base[i].key != elm->key ||
4006             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4007              base[i].keybits != elm->keybits)) {
4008                 hammer2_spin_unex(&parent->core.spin);
4009                 panic("delete base %p element not found at %d/%d elm %p\n",
4010                       base, i, count, elm);
4011                 return;
4012         }
4013
4014         /*
4015          * Update stats and zero the entry
4016          */
4017         parent->bref.data_count -= base[i].data_count;
4018         parent->bref.data_count -= (hammer2_off_t)1 <<
4019                         (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
4020         parent->bref.inode_count -= base[i].inode_count;
4021         if (base[i].type == HAMMER2_BREF_TYPE_INODE)
4022                 parent->bref.inode_count -= 1;
4023
4024         bzero(&base[i], sizeof(*base));
4025
4026         /*
4027          * We can only optimize parent->core.live_zero for live chains.
4028          */
4029         if (parent->core.live_zero == i + 1) {
4030                 while (--i >= 0 && base[i].type == 0)
4031                         ;
4032                 parent->core.live_zero = i + 1;
4033         }
4034
4035         /*
4036          * Clear appropriate blockmap flags in chain.
4037          */
4038         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4039                                         HAMMER2_CHAIN_BMAPUPD);
4040 }
4041
4042 /*
4043  * Insert the specified element.  The block array must not already have the
4044  * element and must have space available for the insertion.
4045  *
4046  * The spin lock on the related chain must be held.
4047  *
4048  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4049  *       need to be adjusted when we commit the media change.
4050  */
4051 void
4052 hammer2_base_insert(hammer2_chain_t *parent,
4053                     hammer2_blockref_t *base, int count,
4054                     int *cache_indexp, hammer2_chain_t *chain)
4055 {
4056         hammer2_blockref_t *elm = &chain->bref;
4057         hammer2_key_t key_next;
4058         hammer2_key_t xkey;
4059         int i;
4060         int j;
4061         int k;
4062         int l;
4063         int u = 1;
4064
4065         /*
4066          * Insert new element.  Expect the element to not already exist
4067          * unless we are replacing it.
4068          *
4069          * XXX see caller, flush code not yet sophisticated enough to prevent
4070          *     re-flushed in some cases.
4071          */
4072         key_next = 0; /* max range */
4073         i = hammer2_base_find(parent, base, count, cache_indexp,
4074                               &key_next, elm->key, elm->key);
4075
4076         /*
4077          * Shortcut fill optimization, typical ordered insertion(s) may not
4078          * require a search.
4079          */
4080         KKASSERT(i >= 0 && i <= count);
4081
4082         /*
4083          * Set appropriate blockmap flags in chain.
4084          */
4085         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4086
4087         /*
4088          * Update stats and zero the entry
4089          */
4090         parent->bref.data_count += elm->data_count;
4091         parent->bref.data_count += (hammer2_off_t)1 <<
4092                         (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4093         parent->bref.inode_count += elm->inode_count;
4094         if (elm->type == HAMMER2_BREF_TYPE_INODE)
4095                 parent->bref.inode_count += 1;
4096
4097
4098         /*
4099          * We can only optimize parent->core.live_zero for live chains.
4100          */
4101         if (i == count && parent->core.live_zero < count) {
4102                 i = parent->core.live_zero++;
4103                 base[i] = *elm;
4104                 return;
4105         }
4106
4107         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4108         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4109                 hammer2_spin_unex(&parent->core.spin);
4110                 panic("insert base %p overlapping elements at %d elm %p\n",
4111                       base, i, elm);
4112         }
4113
4114         /*
4115          * Try to find an empty slot before or after.
4116          */
4117         j = i;
4118         k = i;
4119         while (j > 0 || k < count) {
4120                 --j;
4121                 if (j >= 0 && base[j].type == 0) {
4122                         if (j == i - 1) {
4123                                 base[j] = *elm;
4124                         } else {
4125                                 bcopy(&base[j+1], &base[j],
4126                                       (i - j - 1) * sizeof(*base));
4127                                 base[i - 1] = *elm;
4128                         }
4129                         goto validate;
4130                 }
4131                 ++k;
4132                 if (k < count && base[k].type == 0) {
4133                         bcopy(&base[i], &base[i+1],
4134                               (k - i) * sizeof(hammer2_blockref_t));
4135                         base[i] = *elm;
4136
4137                         /*
4138                          * We can only update parent->core.live_zero for live
4139                          * chains.
4140                          */
4141                         if (parent->core.live_zero <= k)
4142                                 parent->core.live_zero = k + 1;
4143                         u = 2;
4144                         goto validate;
4145                 }
4146         }
4147         panic("hammer2_base_insert: no room!");
4148
4149         /*
4150          * Debugging
4151          */
4152 validate:
4153         key_next = 0;
4154         for (l = 0; l < count; ++l) {
4155                 if (base[l].type) {
4156                         key_next = base[l].key +
4157                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4158                         break;
4159                 }
4160         }
4161         while (++l < count) {
4162                 if (base[l].type) {
4163                         if (base[l].key <= key_next)
4164                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4165                         key_next = base[l].key +
4166                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4167
4168                 }
4169         }
4170
4171 }
4172
4173 #if 0
4174
4175 /*
4176  * Sort the blockref array for the chain.  Used by the flush code to
4177  * sort the blockref[] array.
4178  *
4179  * The chain must be exclusively locked AND spin-locked.
4180  */
4181 typedef hammer2_blockref_t *hammer2_blockref_p;
4182
4183 static
4184 int
4185 hammer2_base_sort_callback(const void *v1, const void *v2)
4186 {
4187         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4188         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4189
4190         /*
4191          * Make sure empty elements are placed at the end of the array
4192          */
4193         if (bref1->type == 0) {
4194                 if (bref2->type == 0)
4195                         return(0);
4196                 return(1);
4197         } else if (bref2->type == 0) {
4198                 return(-1);
4199         }
4200
4201         /*
4202          * Sort by key
4203          */
4204         if (bref1->key < bref2->key)
4205                 return(-1);
4206         if (bref1->key > bref2->key)
4207                 return(1);
4208         return(0);
4209 }
4210
4211 void
4212 hammer2_base_sort(hammer2_chain_t *chain)
4213 {
4214         hammer2_blockref_t *base;
4215         int count;
4216
4217         switch(chain->bref.type) {
4218         case HAMMER2_BREF_TYPE_INODE:
4219                 /*
4220                  * Special shortcut for embedded data returns the inode
4221                  * itself.  Callers must detect this condition and access
4222                  * the embedded data (the strategy code does this for us).
4223                  *
4224                  * This is only applicable to regular files and softlinks.
4225                  */
4226                 if (chain->data->ipdata.meta.op_flags &
4227                     HAMMER2_OPFLAG_DIRECTDATA) {
4228                         return;
4229                 }
4230                 base = &chain->data->ipdata.u.blockset.blockref[0];
4231                 count = HAMMER2_SET_COUNT;
4232                 break;
4233         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4234         case HAMMER2_BREF_TYPE_INDIRECT:
4235                 /*
4236                  * Optimize indirect blocks in the INITIAL state to avoid
4237                  * I/O.
4238                  */
4239                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4240                 base = &chain->data->npdata[0];
4241                 count = chain->bytes / sizeof(hammer2_blockref_t);
4242                 break;
4243         case HAMMER2_BREF_TYPE_VOLUME:
4244                 base = &chain->data->voldata.sroot_blockset.blockref[0];
4245                 count = HAMMER2_SET_COUNT;
4246                 break;
4247         case HAMMER2_BREF_TYPE_FREEMAP:
4248                 base = &chain->data->blkset.blockref[0];
4249                 count = HAMMER2_SET_COUNT;
4250                 break;
4251         default:
4252                 kprintf("hammer2_chain_lookup: unrecognized "
4253                         "blockref(A) type: %d",
4254                         chain->bref.type);
4255                 while (1)
4256                         tsleep(&base, 0, "dead", 0);
4257                 panic("hammer2_chain_lookup: unrecognized "
4258                       "blockref(A) type: %d",
4259                       chain->bref.type);
4260                 base = NULL;    /* safety */
4261                 count = 0;      /* safety */
4262         }
4263         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4264 }
4265
4266 #endif
4267
4268 /*
4269  * Chain memory management
4270  */
4271 void
4272 hammer2_chain_wait(hammer2_chain_t *chain)
4273 {
4274         tsleep(chain, 0, "chnflw", 1);
4275 }
4276
4277 const hammer2_media_data_t *
4278 hammer2_chain_rdata(hammer2_chain_t *chain)
4279 {
4280         KKASSERT(chain->data != NULL);
4281         return (chain->data);
4282 }
4283
4284 hammer2_media_data_t *
4285 hammer2_chain_wdata(hammer2_chain_t *chain)
4286 {
4287         KKASSERT(chain->data != NULL);
4288         return (chain->data);
4289 }
4290
4291 /*
4292  * Set the check data for a chain.  This can be a heavy-weight operation
4293  * and typically only runs on-flush.  For file data check data is calculated
4294  * when the logical buffers are flushed.
4295  */
4296 void
4297 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4298 {
4299         chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4300
4301         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4302         case HAMMER2_CHECK_NONE:
4303                 break;
4304         case HAMMER2_CHECK_DISABLED:
4305                 break;
4306         case HAMMER2_CHECK_ISCSI32:
4307                 chain->bref.check.iscsi32.value =
4308                         hammer2_icrc32(bdata, chain->bytes);
4309                 break;
4310         case HAMMER2_CHECK_XXHASH64:
4311                 chain->bref.check.xxhash64.value =
4312                         XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4313                 break;
4314         case HAMMER2_CHECK_SHA192:
4315                 {
4316                         SHA256_CTX hash_ctx;
4317                         union {
4318                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4319                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4320                         } u;
4321
4322                         SHA256_Init(&hash_ctx);
4323                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4324                         SHA256_Final(u.digest, &hash_ctx);
4325                         u.digest64[2] ^= u.digest64[3];
4326                         bcopy(u.digest,
4327                               chain->bref.check.sha192.data,
4328                               sizeof(chain->bref.check.sha192.data));
4329                 }
4330                 break;
4331         case HAMMER2_CHECK_FREEMAP:
4332                 chain->bref.check.freemap.icrc32 =
4333                         hammer2_icrc32(bdata, chain->bytes);
4334                 break;
4335         default:
4336                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4337                         chain->bref.methods);
4338                 break;
4339         }
4340 }
4341
4342 int
4343 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4344 {
4345         int r;
4346
4347         if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4348                 return 1;
4349
4350         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4351         case HAMMER2_CHECK_NONE:
4352                 r = 1;
4353                 break;
4354         case HAMMER2_CHECK_DISABLED:
4355                 r = 1;
4356                 break;
4357         case HAMMER2_CHECK_ISCSI32:
4358                 r = (chain->bref.check.iscsi32.value ==
4359                      hammer2_icrc32(bdata, chain->bytes));
4360                 hammer2_check_icrc32 += chain->bytes;
4361                 break;
4362         case HAMMER2_CHECK_XXHASH64:
4363                 r = (chain->bref.check.xxhash64.value ==
4364                      XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED));
4365                 hammer2_check_xxhash64 += chain->bytes;
4366                 break;
4367         case HAMMER2_CHECK_SHA192:
4368                 {
4369                         SHA256_CTX hash_ctx;
4370                         union {
4371                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4372                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4373                         } u;
4374
4375                         SHA256_Init(&hash_ctx);
4376                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4377                         SHA256_Final(u.digest, &hash_ctx);
4378                         u.digest64[2] ^= u.digest64[3];
4379                         if (bcmp(u.digest,
4380                                  chain->bref.check.sha192.data,
4381                                  sizeof(chain->bref.check.sha192.data)) == 0) {
4382                                 r = 1;
4383                         } else {
4384                                 r = 0;
4385                         }
4386                 }
4387                 break;
4388         case HAMMER2_CHECK_FREEMAP:
4389                 r = (chain->bref.check.freemap.icrc32 ==
4390                      hammer2_icrc32(bdata, chain->bytes));
4391                 if (r == 0) {
4392                         kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4393                                 chain->bref.check.freemap.icrc32,
4394                                 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4395                         if (chain->dio)
4396                                 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4397                                         chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4398                 }
4399
4400                 break;
4401         default:
4402                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4403                         chain->bref.methods);
4404                 r = 1;
4405                 break;
4406         }
4407         return r;
4408 }
4409
4410 /*
4411  * The caller presents a shared-locked (parent, chain) where the chain
4412  * is of type HAMMER2_OBJTYPE_HARDLINK.  The caller must hold the ip
4413  * structure representing the inode locked to prevent
4414  * consolidation/deconsolidation races.
4415  *
4416  * The flags passed in are LOOKUP flags, not RESOLVE flags.  Only
4417  * HAMMER2_LOOKUP_SHARED is supported.
4418  *
4419  * We locate the hardlink in the current or a common parent directory.
4420  *
4421  * If we are unable to locate the hardlink, EIO is returned and
4422  * (*chainp) is unlocked and dropped.
4423  */
4424 int
4425 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4426                         hammer2_chain_t **parentp,
4427                         hammer2_chain_t **chainp,
4428                         int flags)
4429 {
4430         hammer2_chain_t *parent;
4431         hammer2_chain_t *rchain;
4432         hammer2_key_t key_dummy;
4433         hammer2_key_t lhc;
4434         int cache_index = -1;
4435         int resolve_flags;
4436
4437         resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
4438                         HAMMER2_RESOLVE_SHARED : 0;
4439
4440         /*
4441          * Obtain the key for the hardlink from *chainp.
4442          */
4443         rchain = *chainp;
4444         lhc = rchain->data->ipdata.meta.inum;
4445         hammer2_chain_unlock(rchain);
4446         hammer2_chain_drop(rchain);
4447         rchain = NULL;
4448
4449         for (;;) {
4450                 int again;
4451
4452                 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4453                                               lhc, lhc,
4454                                               &cache_index, flags);
4455                 if (rchain)
4456                         break;
4457
4458                 /*
4459                  * Iterate parents, handle parent rename races by retrying
4460                  * the operation.
4461                  */
4462                 again = 0;
4463                 for (;;) {
4464                         parent = *parentp;
4465                         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4466                                 if (again == 1)
4467                                         break;
4468                                 ++again;
4469                         }
4470                         if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4471                                 goto done;
4472                         for (;;) {
4473                                 if (parent->parent == NULL)
4474                                         goto done;
4475                                 parent = parent->parent;
4476                                 hammer2_chain_ref(parent);
4477                                 hammer2_chain_unlock(*parentp);
4478                                 hammer2_chain_lock(parent,
4479                                                    HAMMER2_RESOLVE_ALWAYS |
4480                                                    resolve_flags);
4481                                 if ((*parentp)->parent == parent) {
4482                                         hammer2_chain_drop(*parentp);
4483                                         *parentp = parent;
4484                                         break;
4485                                 }
4486                                 hammer2_chain_unlock(parent);
4487                                 hammer2_chain_drop(parent);
4488                                 hammer2_chain_lock(*parentp,
4489                                                    HAMMER2_RESOLVE_ALWAYS |
4490                                                    resolve_flags);
4491                                 parent = *parentp;
4492                         }
4493                 }
4494         }
4495 done:
4496
4497         *chainp = rchain;
4498         return (rchain ? 0 : EINVAL);
4499 }
4500
4501 /*
4502  * Used by the bulkscan code to snapshot the synchronized storage for
4503  * a volume, allowing it to be scanned concurrently against normal
4504  * operation.
4505  */
4506 hammer2_chain_t *
4507 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4508 {
4509         hammer2_chain_t *copy;
4510
4511         copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4512         switch(chain->bref.type) {
4513         case HAMMER2_BREF_TYPE_VOLUME:
4514                 copy->data = kmalloc(sizeof(copy->data->voldata),
4515                                      chain->hmp->mchain,
4516                                      M_WAITOK | M_ZERO);
4517                 hammer2_spin_ex(&chain->core.spin);
4518                 copy->data->voldata = chain->data->voldata;
4519                 hammer2_spin_unex(&chain->core.spin);
4520                 break;
4521         case HAMMER2_BREF_TYPE_FREEMAP:
4522                 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4523                                      chain->hmp->mchain,
4524                                      M_WAITOK | M_ZERO);
4525                 hammer2_spin_ex(&chain->core.spin);
4526                 copy->data->blkset = chain->data->blkset;
4527                 hammer2_spin_unex(&chain->core.spin);
4528                 break;
4529         default:
4530                 break;
4531         }
4532         return copy;
4533 }
4534
4535 void
4536 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4537 {
4538         switch(copy->bref.type) {
4539         case HAMMER2_BREF_TYPE_VOLUME:
4540         case HAMMER2_BREF_TYPE_FREEMAP:
4541                 KKASSERT(copy->data);
4542                 kfree(copy->data, copy->hmp->mchain);
4543                 copy->data = NULL;
4544                 atomic_add_long(&hammer2_chain_allocs, -1);
4545                 break;
4546         default:
4547                 break;
4548         }
4549         hammer2_chain_drop(copy);
4550 }
4551
4552 /*
4553  * Create a snapshot of the specified {parent, ochain} with the specified
4554  * label.  The originating hammer2_inode must be exclusively locked for
4555  * safety.
4556  *
4557  * The ioctl code has already synced the filesystem.
4558  */
4559 int
4560 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4561                        hammer2_tid_t mtid)
4562 {
4563         hammer2_dev_t *hmp;
4564         const hammer2_inode_data_t *ripdata;
4565         hammer2_inode_data_t *wipdata;
4566         hammer2_chain_t *nchain;
4567         hammer2_inode_t *nip;
4568         size_t name_len;
4569         hammer2_key_t lhc;
4570         struct vattr vat;
4571 #if 0
4572         uuid_t opfs_clid;
4573 #endif
4574         int error;
4575
4576         kprintf("snapshot %s\n", pmp->name);
4577
4578         name_len = strlen(pmp->name);
4579         lhc = hammer2_dirhash(pmp->name, name_len);
4580
4581         /*
4582          * Get the clid
4583          */
4584         ripdata = &chain->data->ipdata;
4585 #if 0
4586         opfs_clid = ripdata->meta.pfs_clid;
4587 #endif
4588         hmp = chain->hmp;
4589
4590         /*
4591          * Create the snapshot directory under the super-root
4592          *
4593          * Set PFS type, generate a unique filesystem id, and generate
4594          * a cluster id.  Use the same clid when snapshotting a PFS root,
4595          * which theoretically allows the snapshot to be used as part of
4596          * the same cluster (perhaps as a cache).
4597          *
4598          * Copy the (flushed) blockref array.  Theoretically we could use
4599          * chain_duplicate() but it becomes difficult to disentangle
4600          * the shared core so for now just brute-force it.
4601          */
4602         VATTR_NULL(&vat);
4603         vat.va_type = VDIR;
4604         vat.va_mode = 0755;
4605         nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4606                                    pmp->name, name_len, 0,
4607                                    1, 0, 0,
4608                                    HAMMER2_INSERT_PFSROOT, &error);
4609
4610         if (nip) {
4611                 hammer2_inode_modify(nip);
4612                 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4613                 hammer2_chain_modify(nchain, mtid, 0, 0);
4614                 wipdata = &nchain->data->ipdata;
4615
4616                 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4617                 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4618                 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4619                 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4620
4621                 /*
4622                  * Give the snapshot its own private cluster id.  As a
4623                  * snapshot no further synchronization with the original
4624                  * cluster will be done.
4625                  */
4626 #if 0
4627                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4628                         nip->meta.pfs_clid = opfs_clid;
4629                 else
4630                         kern_uuidgen(&nip->meta.pfs_clid, 1);
4631 #endif
4632                 kern_uuidgen(&nip->meta.pfs_clid, 1);
4633                 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4634
4635                 /* XXX hack blockset copy */
4636                 /* XXX doesn't work with real cluster */
4637                 wipdata->meta = nip->meta;
4638                 wipdata->u.blockset = ripdata->u.blockset;
4639                 hammer2_flush(nchain, 1);
4640                 hammer2_chain_unlock(nchain);
4641                 hammer2_chain_drop(nchain);
4642                 hammer2_inode_unlock(nip);
4643         }
4644         return (error);
4645 }