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