hammer2 - stabilization, sequencing
[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 void
1063 hammer2_chain_modify(hammer2_chain_t *chain,
1064                      hammer2_tid_t mtid, int flags)
1065 {
1066         hammer2_blockref_t obref;
1067         hammer2_dev_t *hmp;
1068         hammer2_io_t *dio;
1069         int error;
1070         int wasinitial;
1071         int newmod;
1072         char *bdata;
1073
1074         hmp = chain->hmp;
1075         obref = chain->bref;
1076         KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1077
1078         /*
1079          * Data is not optional for freemap chains (we must always be sure
1080          * to copy the data on COW storage allocations).
1081          */
1082         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1083             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1084                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1085                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1086         }
1087
1088         /*
1089          * Data must be resolved if already assigned, unless explicitly
1090          * flagged otherwise.
1091          */
1092         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1093             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1094                 hammer2_chain_load_data(chain);
1095         }
1096
1097         /*
1098          * Set MODIFIED to indicate that the chain has been modified.
1099          * Set UPDATE to ensure that the blockref is updated in the parent.
1100          */
1101         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1102                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1103                 hammer2_chain_ref(chain);
1104                 hammer2_pfs_memory_inc(chain->pmp);     /* can be NULL */
1105                 newmod = 1;
1106         } else {
1107                 newmod = 0;
1108         }
1109         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1110                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1111                 hammer2_chain_ref(chain);
1112         }
1113
1114         /*
1115          * The modification or re-modification requires an allocation and
1116          * possible COW.
1117          *
1118          * We normally always allocate new storage here.  If storage exists
1119          * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1120          */
1121         if (chain != &hmp->vchain && chain != &hmp->fchain) {
1122                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1123                      ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1124                 ) {
1125                         hammer2_freemap_alloc(chain, chain->bytes);
1126                         /* XXX failed allocation */
1127                 }
1128         }
1129
1130         /*
1131          * Update mirror_tid and modify_tid.  modify_tid is only updated
1132          * automatically by this function when used from the frontend.
1133          * Flushes and synchronization adjust the flag manually.
1134          *
1135          * NOTE: chain->pmp could be the device spmp.
1136          */
1137         KKASSERT(mtid != 0);
1138         chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1139         chain->bref.modify_tid = mtid;
1140
1141         /*
1142          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1143          * requires updating as well as to tell the delete code that the
1144          * chain's blockref might not exactly match (in terms of physical size
1145          * or block offset) the one in the parent's blocktable.  The base key
1146          * of course will still match.
1147          */
1148         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1149                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1150
1151         /*
1152          * Short-cut data blocks which the caller does not need an actual
1153          * data reference to (aka OPTDATA), as long as the chain does not
1154          * already have a data pointer to the data.  This generally means
1155          * that the modifications are being done via the logical buffer cache.
1156          * The INITIAL flag relates only to the device data buffer and thus
1157          * remains unchange in this situation.
1158          */
1159         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1160             (flags & HAMMER2_MODIFY_OPTDATA) &&
1161             chain->data == NULL) {
1162                 goto skip2;
1163         }
1164
1165         /*
1166          * Clearing the INITIAL flag (for indirect blocks) indicates that
1167          * we've processed the uninitialized storage allocation.
1168          *
1169          * If this flag is already clear we are likely in a copy-on-write
1170          * situation but we have to be sure NOT to bzero the storage if
1171          * no data is present.
1172          */
1173         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1174                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1175                 wasinitial = 1;
1176         } else {
1177                 wasinitial = 0;
1178         }
1179
1180         /*
1181          * Instantiate data buffer and possibly execute COW operation
1182          */
1183         switch(chain->bref.type) {
1184         case HAMMER2_BREF_TYPE_VOLUME:
1185         case HAMMER2_BREF_TYPE_FREEMAP:
1186                 /*
1187                  * The data is embedded, no copy-on-write operation is
1188                  * needed.
1189                  */
1190                 KKASSERT(chain->dio == NULL);
1191                 break;
1192         case HAMMER2_BREF_TYPE_INODE:
1193         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1194         case HAMMER2_BREF_TYPE_DATA:
1195         case HAMMER2_BREF_TYPE_INDIRECT:
1196         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1197                 /*
1198                  * Perform the copy-on-write operation
1199                  *
1200                  * zero-fill or copy-on-write depending on whether
1201                  * chain->data exists or not and set the dirty state for
1202                  * the new buffer.  hammer2_io_new() will handle the
1203                  * zero-fill.
1204                  */
1205                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1206
1207                 if (wasinitial) {
1208                         error = hammer2_io_new(hmp, chain->bref.data_off,
1209                                                chain->bytes, &dio);
1210                 } else {
1211                         error = hammer2_io_bread(hmp, chain->bref.data_off,
1212                                                  chain->bytes, &dio);
1213                 }
1214                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1215
1216                 /*
1217                  * If an I/O error occurs make sure callers cannot accidently
1218                  * modify the old buffer's contents and corrupt the filesystem.
1219                  */
1220                 if (error) {
1221                         kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1222                                 hmp);
1223                         chain->error = HAMMER2_ERROR_IO;
1224                         hammer2_io_brelse(&dio);
1225                         hammer2_io_brelse(&chain->dio);
1226                         chain->data = NULL;
1227                         break;
1228                 }
1229                 chain->error = 0;
1230                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1231
1232                 if (chain->data) {
1233                         KKASSERT(chain->dio != NULL);
1234                         if (chain->data != (void *)bdata) {
1235                                 bcopy(chain->data, bdata, chain->bytes);
1236                         }
1237                 } else if (wasinitial == 0) {
1238                         /*
1239                          * We have a problem.  We were asked to COW but
1240                          * we don't have any data to COW with!
1241                          */
1242                         panic("hammer2_chain_modify: having a COW %p\n",
1243                               chain);
1244                 }
1245
1246                 /*
1247                  * Retire the old buffer, replace with the new.  Dirty or
1248                  * redirty the new buffer.
1249                  *
1250                  * WARNING! The system buffer cache may have already flushed
1251                  *          the buffer, so we must be sure to [re]dirty it
1252                  *          for further modification.
1253                  */
1254                 if (chain->dio)
1255                         hammer2_io_brelse(&chain->dio);
1256                 chain->data = (void *)bdata;
1257                 chain->dio = dio;
1258                 hammer2_io_setdirty(dio);       /* modified by bcopy above */
1259                 break;
1260         default:
1261                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1262                       chain->bref.type);
1263                 break;
1264
1265         }
1266 skip2:
1267         /*
1268          * setflush on parent indicating that the parent must recurse down
1269          * to us.  Do not call on chain itself which might already have it
1270          * set.
1271          */
1272         if (chain->parent)
1273                 hammer2_chain_setflush(chain->parent);
1274 }
1275
1276 /*
1277  * Modify the chain associated with an inode.
1278  */
1279 void
1280 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1281                         hammer2_tid_t mtid, int flags)
1282 {
1283         hammer2_inode_modify(ip);
1284         hammer2_chain_modify(chain, mtid, flags);
1285 }
1286
1287 /*
1288  * Volume header data locks
1289  */
1290 void
1291 hammer2_voldata_lock(hammer2_dev_t *hmp)
1292 {
1293         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1294 }
1295
1296 void
1297 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1298 {
1299         lockmgr(&hmp->vollk, LK_RELEASE);
1300 }
1301
1302 void
1303 hammer2_voldata_modify(hammer2_dev_t *hmp)
1304 {
1305         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1306                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1307                 hammer2_chain_ref(&hmp->vchain);
1308                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1309         }
1310 }
1311
1312 /*
1313  * This function returns the chain at the nearest key within the specified
1314  * range.  The returned chain will be referenced but not locked.
1315  *
1316  * This function will recurse through chain->rbtree as necessary and will
1317  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1318  * the iteration value is less than the current value of *key_nextp.
1319  *
1320  * The caller should use (*key_nextp) to calculate the actual range of
1321  * the returned element, which will be (key_beg to *key_nextp - 1), because
1322  * there might be another element which is superior to the returned element
1323  * and overlaps it.
1324  *
1325  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1326  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1327  * it will wind up being (key_end + 1).
1328  *
1329  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1330  *           held through the operation.
1331  */
1332 struct hammer2_chain_find_info {
1333         hammer2_chain_t         *best;
1334         hammer2_key_t           key_beg;
1335         hammer2_key_t           key_end;
1336         hammer2_key_t           key_next;
1337 };
1338
1339 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1340 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1341
1342 static
1343 hammer2_chain_t *
1344 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1345                           hammer2_key_t key_beg, hammer2_key_t key_end)
1346 {
1347         struct hammer2_chain_find_info info;
1348
1349         info.best = NULL;
1350         info.key_beg = key_beg;
1351         info.key_end = key_end;
1352         info.key_next = *key_nextp;
1353
1354         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1355                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1356                 &info);
1357         *key_nextp = info.key_next;
1358 #if 0
1359         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1360                 parent, key_beg, key_end, *key_nextp);
1361 #endif
1362
1363         return (info.best);
1364 }
1365
1366 static
1367 int
1368 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1369 {
1370         struct hammer2_chain_find_info *info = data;
1371         hammer2_key_t child_beg;
1372         hammer2_key_t child_end;
1373
1374         child_beg = child->bref.key;
1375         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1376
1377         if (child_end < info->key_beg)
1378                 return(-1);
1379         if (child_beg > info->key_end)
1380                 return(1);
1381         return(0);
1382 }
1383
1384 static
1385 int
1386 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1387 {
1388         struct hammer2_chain_find_info *info = data;
1389         hammer2_chain_t *best;
1390         hammer2_key_t child_end;
1391
1392         /*
1393          * WARNING! Do not discard DUPLICATED chains, it is possible that
1394          *          we are catching an insertion half-way done.  If a
1395          *          duplicated chain turns out to be the best choice the
1396          *          caller will re-check its flags after locking it.
1397          *
1398          * WARNING! Layerq is scanned forwards, exact matches should keep
1399          *          the existing info->best.
1400          */
1401         if ((best = info->best) == NULL) {
1402                 /*
1403                  * No previous best.  Assign best
1404                  */
1405                 info->best = child;
1406         } else if (best->bref.key <= info->key_beg &&
1407                    child->bref.key <= info->key_beg) {
1408                 /*
1409                  * Illegal overlap.
1410                  */
1411                 KKASSERT(0);
1412                 /*info->best = child;*/
1413         } else if (child->bref.key < best->bref.key) {
1414                 /*
1415                  * Child has a nearer key and best is not flush with key_beg.
1416                  * Set best to child.  Truncate key_next to the old best key.
1417                  */
1418                 info->best = child;
1419                 if (info->key_next > best->bref.key || info->key_next == 0)
1420                         info->key_next = best->bref.key;
1421         } else if (child->bref.key == best->bref.key) {
1422                 /*
1423                  * If our current best is flush with the child then this
1424                  * is an illegal overlap.
1425                  *
1426                  * key_next will automatically be limited to the smaller of
1427                  * the two end-points.
1428                  */
1429                 KKASSERT(0);
1430                 info->best = child;
1431         } else {
1432                 /*
1433                  * Keep the current best but truncate key_next to the child's
1434                  * base.
1435                  *
1436                  * key_next will also automatically be limited to the smaller
1437                  * of the two end-points (probably not necessary for this case
1438                  * but we do it anyway).
1439                  */
1440                 if (info->key_next > child->bref.key || info->key_next == 0)
1441                         info->key_next = child->bref.key;
1442         }
1443
1444         /*
1445          * Always truncate key_next based on child's end-of-range.
1446          */
1447         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1448         if (child_end && (info->key_next > child_end || info->key_next == 0))
1449                 info->key_next = child_end;
1450
1451         return(0);
1452 }
1453
1454 /*
1455  * Retrieve the specified chain from a media blockref, creating the
1456  * in-memory chain structure which reflects it.
1457  *
1458  * To handle insertion races pass the INSERT_RACE flag along with the
1459  * generation number of the core.  NULL will be returned if the generation
1460  * number changes before we have a chance to insert the chain.  Insert
1461  * races can occur because the parent might be held shared.
1462  *
1463  * Caller must hold the parent locked shared or exclusive since we may
1464  * need the parent's bref array to find our block.
1465  *
1466  * WARNING! chain->pmp is always set to NULL for any chain representing
1467  *          part of the super-root topology.
1468  */
1469 hammer2_chain_t *
1470 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1471                   hammer2_blockref_t *bref)
1472 {
1473         hammer2_dev_t *hmp = parent->hmp;
1474         hammer2_chain_t *chain;
1475         int error;
1476
1477         /*
1478          * Allocate a chain structure representing the existing media
1479          * entry.  Resulting chain has one ref and is not locked.
1480          */
1481         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1482                 chain = hammer2_chain_alloc(hmp, NULL, bref);
1483         else
1484                 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1485         /* ref'd chain returned */
1486
1487         /*
1488          * Flag that the chain is in the parent's blockmap so delete/flush
1489          * knows what to do with it.
1490          */
1491         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1492
1493         /*
1494          * Link the chain into its parent.  A spinlock is required to safely
1495          * access the RBTREE, and it is possible to collide with another
1496          * hammer2_chain_get() operation because the caller might only hold
1497          * a shared lock on the parent.
1498          */
1499         KKASSERT(parent->refs > 0);
1500         error = hammer2_chain_insert(parent, chain,
1501                                      HAMMER2_CHAIN_INSERT_SPIN |
1502                                      HAMMER2_CHAIN_INSERT_RACE,
1503                                      generation);
1504         if (error) {
1505                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1506                 kprintf("chain %p get race\n", chain);
1507                 hammer2_chain_drop(chain);
1508                 chain = NULL;
1509         } else {
1510                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1511         }
1512
1513         /*
1514          * Return our new chain referenced but not locked, or NULL if
1515          * a race occurred.
1516          */
1517         return (chain);
1518 }
1519
1520 /*
1521  * Lookup initialization/completion API
1522  */
1523 hammer2_chain_t *
1524 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1525 {
1526         hammer2_chain_ref(parent);
1527         if (flags & HAMMER2_LOOKUP_SHARED) {
1528                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1529                                            HAMMER2_RESOLVE_SHARED);
1530         } else {
1531                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1532         }
1533         return (parent);
1534 }
1535
1536 void
1537 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1538 {
1539         if (parent) {
1540                 hammer2_chain_unlock(parent);
1541                 hammer2_chain_drop(parent);
1542         }
1543 }
1544
1545 hammer2_chain_t *
1546 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1547 {
1548         hammer2_chain_t *oparent;
1549         hammer2_chain_t *nparent;
1550
1551         /*
1552          * Be careful of order, oparent must be unlocked before nparent
1553          * is locked below to avoid a deadlock.
1554          */
1555         oparent = *parentp;
1556         hammer2_spin_ex(&oparent->core.spin);
1557         nparent = oparent->parent;
1558         hammer2_chain_ref(nparent);
1559         hammer2_spin_unex(&oparent->core.spin);
1560         if (oparent) {
1561                 hammer2_chain_unlock(oparent);
1562                 hammer2_chain_drop(oparent);
1563                 oparent = NULL;
1564         }
1565
1566         hammer2_chain_lock(nparent, how);
1567         *parentp = nparent;
1568
1569         return (nparent);
1570 }
1571
1572 /*
1573  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1574  * (*parentp) typically points to an inode but can also point to a related
1575  * indirect block and this function will recurse upwards and find the inode
1576  * again.
1577  *
1578  * (*parentp) must be exclusively locked and referenced and can be an inode
1579  * or an existing indirect block within the inode.
1580  *
1581  * On return (*parentp) will be modified to point at the deepest parent chain
1582  * element encountered during the search, as a helper for an insertion or
1583  * deletion.   The new (*parentp) will be locked and referenced and the old
1584  * will be unlocked and dereferenced (no change if they are both the same).
1585  *
1586  * The matching chain will be returned exclusively locked.  If NOLOCK is
1587  * requested the chain will be returned only referenced.  Note that the
1588  * parent chain must always be locked shared or exclusive, matching the
1589  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
1590  * when NOLOCK is specified but that complicates matters if *parentp must
1591  * inherit the chain.
1592  *
1593  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
1594  * data pointer or can otherwise be in flux.
1595  *
1596  * NULL is returned if no match was found, but (*parentp) will still
1597  * potentially be adjusted.
1598  *
1599  * If a fatal error occurs (typically an I/O error), a dummy chain is
1600  * returned with chain->error and error-identifying information set.  This
1601  * chain will assert if you try to do anything fancy with it.
1602  *
1603  * XXX Depending on where the error occurs we should allow continued iteration.
1604  *
1605  * On return (*key_nextp) will point to an iterative value for key_beg.
1606  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
1607  *
1608  * This function will also recurse up the chain if the key is not within the
1609  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1610  * can simply allow (*parentp) to float inside the loop.
1611  *
1612  * NOTE!  chain->data is not always resolved.  By default it will not be
1613  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1614  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1615  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1616  *        buffer).
1617  */
1618 hammer2_chain_t *
1619 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1620                      hammer2_key_t key_beg, hammer2_key_t key_end,
1621                      int *cache_indexp, int flags)
1622 {
1623         hammer2_dev_t *hmp;
1624         hammer2_chain_t *parent;
1625         hammer2_chain_t *chain;
1626         hammer2_blockref_t *base;
1627         hammer2_blockref_t *bref;
1628         hammer2_blockref_t bcopy;
1629         hammer2_key_t scan_beg;
1630         hammer2_key_t scan_end;
1631         int count = 0;
1632         int how_always = HAMMER2_RESOLVE_ALWAYS;
1633         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1634         int how;
1635         int generation;
1636         int maxloops = 300000;
1637
1638         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1639                 how_maybe = how_always;
1640                 how = HAMMER2_RESOLVE_ALWAYS;
1641         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1642                 how = HAMMER2_RESOLVE_NEVER;
1643         } else {
1644                 how = HAMMER2_RESOLVE_MAYBE;
1645         }
1646         if (flags & HAMMER2_LOOKUP_SHARED) {
1647                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1648                 how_always |= HAMMER2_RESOLVE_SHARED;
1649                 how |= HAMMER2_RESOLVE_SHARED;
1650         }
1651
1652         /*
1653          * Recurse (*parentp) upward if necessary until the parent completely
1654          * encloses the key range or we hit the inode.
1655          *
1656          * This function handles races against the flusher doing a delete-
1657          * duplicate above us and re-homes the parent to the duplicate in
1658          * that case, otherwise we'd wind up recursing down a stale chain.
1659          */
1660         parent = *parentp;
1661         hmp = parent->hmp;
1662
1663         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1664                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1665                 scan_beg = parent->bref.key;
1666                 scan_end = scan_beg +
1667                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1668                 if (key_beg >= scan_beg && key_end <= scan_end)
1669                         break;
1670                 parent = hammer2_chain_getparent(parentp, how_maybe);
1671         }
1672
1673 again:
1674         if (--maxloops == 0)
1675                 panic("hammer2_chain_lookup: maxloops");
1676         /*
1677          * Locate the blockref array.  Currently we do a fully associative
1678          * search through the array.
1679          */
1680         switch(parent->bref.type) {
1681         case HAMMER2_BREF_TYPE_INODE:
1682                 /*
1683                  * Special shortcut for embedded data returns the inode
1684                  * itself.  Callers must detect this condition and access
1685                  * the embedded data (the strategy code does this for us).
1686                  *
1687                  * This is only applicable to regular files and softlinks.
1688                  */
1689                 if (parent->data->ipdata.meta.op_flags &
1690                     HAMMER2_OPFLAG_DIRECTDATA) {
1691                         if (flags & HAMMER2_LOOKUP_NODIRECT) {
1692                                 chain = NULL;
1693                                 *key_nextp = key_end + 1;
1694                                 goto done;
1695                         }
1696                         hammer2_chain_ref(parent);
1697                         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
1698                                 hammer2_chain_lock(parent, how_always);
1699                         *key_nextp = key_end + 1;
1700                         return (parent);
1701                 }
1702                 base = &parent->data->ipdata.u.blockset.blockref[0];
1703                 count = HAMMER2_SET_COUNT;
1704                 break;
1705         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1706         case HAMMER2_BREF_TYPE_INDIRECT:
1707                 /*
1708                  * Handle MATCHIND on the parent
1709                  */
1710                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1711                         scan_beg = parent->bref.key;
1712                         scan_end = scan_beg +
1713                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1714                         if (key_beg == scan_beg && key_end == scan_end) {
1715                                 chain = parent;
1716                                 hammer2_chain_ref(chain);
1717                                 hammer2_chain_lock(chain, how_maybe);
1718                                 *key_nextp = scan_end + 1;
1719                                 goto done;
1720                         }
1721                 }
1722                 /*
1723                  * Optimize indirect blocks in the INITIAL state to avoid
1724                  * I/O.
1725                  */
1726                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1727                         base = NULL;
1728                 } else {
1729                         if (parent->data == NULL)
1730                                 panic("parent->data is NULL");
1731                         base = &parent->data->npdata[0];
1732                 }
1733                 count = parent->bytes / sizeof(hammer2_blockref_t);
1734                 break;
1735         case HAMMER2_BREF_TYPE_VOLUME:
1736                 base = &parent->data->voldata.sroot_blockset.blockref[0];
1737                 count = HAMMER2_SET_COUNT;
1738                 break;
1739         case HAMMER2_BREF_TYPE_FREEMAP:
1740                 base = &parent->data->blkset.blockref[0];
1741                 count = HAMMER2_SET_COUNT;
1742                 break;
1743         default:
1744                 kprintf("hammer2_chain_lookup: unrecognized "
1745                         "blockref(B) type: %d",
1746                         parent->bref.type);
1747                 while (1)
1748                         tsleep(&base, 0, "dead", 0);
1749                 panic("hammer2_chain_lookup: unrecognized "
1750                       "blockref(B) type: %d",
1751                       parent->bref.type);
1752                 base = NULL;    /* safety */
1753                 count = 0;      /* safety */
1754         }
1755
1756         /*
1757          * Merged scan to find next candidate.
1758          *
1759          * hammer2_base_*() functions require the parent->core.live_* fields
1760          * to be synchronized.
1761          *
1762          * We need to hold the spinlock to access the block array and RB tree
1763          * and to interlock chain creation.
1764          */
1765         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
1766                 hammer2_chain_countbrefs(parent, base, count);
1767
1768         /*
1769          * Combined search
1770          */
1771         hammer2_spin_ex(&parent->core.spin);
1772         chain = hammer2_combined_find(parent, base, count,
1773                                       cache_indexp, key_nextp,
1774                                       key_beg, key_end,
1775                                       &bref);
1776         generation = parent->core.generation;
1777
1778         /*
1779          * Exhausted parent chain, iterate.
1780          */
1781         if (bref == NULL) {
1782                 hammer2_spin_unex(&parent->core.spin);
1783                 if (key_beg == key_end) /* short cut single-key case */
1784                         return (NULL);
1785
1786                 /*
1787                  * Stop if we reached the end of the iteration.
1788                  */
1789                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1790                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1791                         return (NULL);
1792                 }
1793
1794                 /*
1795                  * Calculate next key, stop if we reached the end of the
1796                  * iteration, otherwise go up one level and loop.
1797                  */
1798                 key_beg = parent->bref.key +
1799                           ((hammer2_key_t)1 << parent->bref.keybits);
1800                 if (key_beg == 0 || key_beg > key_end)
1801                         return (NULL);
1802                 parent = hammer2_chain_getparent(parentp, how_maybe);
1803                 goto again;
1804         }
1805
1806         /*
1807          * Selected from blockref or in-memory chain.
1808          */
1809         if (chain == NULL) {
1810                 bcopy = *bref;
1811                 hammer2_spin_unex(&parent->core.spin);
1812                 chain = hammer2_chain_get(parent, generation,
1813                                           &bcopy);
1814                 if (chain == NULL) {
1815                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1816                                 parent, key_beg, key_end);
1817                         goto again;
1818                 }
1819                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1820                         hammer2_chain_drop(chain);
1821                         goto again;
1822                 }
1823         } else {
1824                 hammer2_chain_ref(chain);
1825                 hammer2_spin_unex(&parent->core.spin);
1826         }
1827
1828         /*
1829          * chain is referenced but not locked.  We must lock the chain
1830          * to obtain definitive DUPLICATED/DELETED state
1831          */
1832         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1833             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1834                 hammer2_chain_lock(chain, how_maybe);
1835         } else {
1836                 hammer2_chain_lock(chain, how);
1837         }
1838
1839         /*
1840          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1841          *
1842          * NOTE: Chain's key range is not relevant as there might be
1843          *       one-offs within the range that are not deleted.
1844          *
1845          * NOTE: Lookups can race delete-duplicate because
1846          *       delete-duplicate does not lock the parent's core
1847          *       (they just use the spinlock on the core).  We must
1848          *       check for races by comparing the DUPLICATED flag before
1849          *       releasing the spinlock with the flag after locking the
1850          *       chain.
1851          */
1852         if (chain->flags & HAMMER2_CHAIN_DELETED) {
1853                 hammer2_chain_unlock(chain);
1854                 hammer2_chain_drop(chain);
1855                 key_beg = *key_nextp;
1856                 if (key_beg == 0 || key_beg > key_end)
1857                         return(NULL);
1858                 goto again;
1859         }
1860
1861         /*
1862          * If the chain element is an indirect block it becomes the new
1863          * parent and we loop on it.  We must maintain our top-down locks
1864          * to prevent the flusher from interfering (i.e. doing a
1865          * delete-duplicate and leaving us recursing down a deleted chain).
1866          *
1867          * The parent always has to be locked with at least RESOLVE_MAYBE
1868          * so we can access its data.  It might need a fixup if the caller
1869          * passed incompatible flags.  Be careful not to cause a deadlock
1870          * as a data-load requires an exclusive lock.
1871          *
1872          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1873          * range is within the requested key range we return the indirect
1874          * block and do NOT loop.  This is usually only used to acquire
1875          * freemap nodes.
1876          */
1877         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1878             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1879                 hammer2_chain_unlock(parent);
1880                 hammer2_chain_drop(parent);
1881                 *parentp = parent = chain;
1882                 goto again;
1883         }
1884 done:
1885         /*
1886          * All done, return the chain.
1887          *
1888          * If the caller does not want a locked chain, replace the lock with
1889          * a ref.  Perhaps this can eventually be optimized to not obtain the
1890          * lock in the first place for situations where the data does not
1891          * need to be resolved.
1892          */
1893         if (chain) {
1894                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1895                         hammer2_chain_unlock(chain);
1896         }
1897
1898         return (chain);
1899 }
1900
1901 /*
1902  * After having issued a lookup we can iterate all matching keys.
1903  *
1904  * If chain is non-NULL we continue the iteration from just after it's index.
1905  *
1906  * If chain is NULL we assume the parent was exhausted and continue the
1907  * iteration at the next parent.
1908  *
1909  * If a fatal error occurs (typically an I/O error), a dummy chain is
1910  * returned with chain->error and error-identifying information set.  This
1911  * chain will assert if you try to do anything fancy with it.
1912  *
1913  * XXX Depending on where the error occurs we should allow continued iteration.
1914  *
1915  * parent must be locked on entry and remains locked throughout.  chain's
1916  * lock status must match flags.  Chain is always at least referenced.
1917  *
1918  * WARNING!  The MATCHIND flag does not apply to this function.
1919  */
1920 hammer2_chain_t *
1921 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1922                    hammer2_key_t *key_nextp,
1923                    hammer2_key_t key_beg, hammer2_key_t key_end,
1924                    int *cache_indexp, int flags)
1925 {
1926         hammer2_chain_t *parent;
1927         int how_maybe;
1928
1929         /*
1930          * Calculate locking flags for upward recursion.
1931          */
1932         how_maybe = HAMMER2_RESOLVE_MAYBE;
1933         if (flags & HAMMER2_LOOKUP_SHARED)
1934                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1935
1936         parent = *parentp;
1937
1938         /*
1939          * Calculate the next index and recalculate the parent if necessary.
1940          */
1941         if (chain) {
1942                 key_beg = chain->bref.key +
1943                           ((hammer2_key_t)1 << chain->bref.keybits);
1944                 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
1945                               HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
1946                         hammer2_chain_unlock(chain);
1947                 }
1948                 hammer2_chain_drop(chain);
1949
1950                 /*
1951                  * chain invalid past this point, but we can still do a
1952                  * pointer comparison w/parent.
1953                  *
1954                  * Any scan where the lookup returned degenerate data embedded
1955                  * in the inode has an invalid index and must terminate.
1956                  */
1957                 if (chain == parent)
1958                         return(NULL);
1959                 if (key_beg == 0 || key_beg > key_end)
1960                         return(NULL);
1961                 chain = NULL;
1962         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1963                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1964                 /*
1965                  * We reached the end of the iteration.
1966                  */
1967                 return (NULL);
1968         } else {
1969                 /*
1970                  * Continue iteration with next parent unless the current
1971                  * parent covers the range.
1972                  */
1973                 key_beg = parent->bref.key +
1974                           ((hammer2_key_t)1 << parent->bref.keybits);
1975                 if (key_beg == 0 || key_beg > key_end)
1976                         return (NULL);
1977                 parent = hammer2_chain_getparent(parentp, how_maybe);
1978         }
1979
1980         /*
1981          * And execute
1982          */
1983         return (hammer2_chain_lookup(parentp, key_nextp,
1984                                      key_beg, key_end,
1985                                      cache_indexp, flags));
1986 }
1987
1988 /*
1989  * The raw scan function is similar to lookup/next but does not seek to a key.
1990  * Blockrefs are iterated via first_chain = (parent, NULL) and
1991  * next_chain = (parent, chain).
1992  *
1993  * The passed-in parent must be locked and its data resolved.  The returned
1994  * chain will be locked.  Pass chain == NULL to acquire the first sub-chain
1995  * under parent and then iterate with the passed-in chain (which this
1996  * function will unlock).
1997  */
1998 hammer2_chain_t *
1999 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2000                    int *cache_indexp, int flags)
2001 {
2002         hammer2_dev_t *hmp;
2003         hammer2_blockref_t *base;
2004         hammer2_blockref_t *bref;
2005         hammer2_blockref_t bcopy;
2006         hammer2_key_t key;
2007         hammer2_key_t next_key;
2008         int count = 0;
2009         int how_always = HAMMER2_RESOLVE_ALWAYS;
2010         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2011         int how;
2012         int generation;
2013         int maxloops = 300000;
2014
2015         hmp = parent->hmp;
2016
2017         /*
2018          * Scan flags borrowed from lookup.
2019          */
2020         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2021                 how_maybe = how_always;
2022                 how = HAMMER2_RESOLVE_ALWAYS;
2023         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2024                 how = HAMMER2_RESOLVE_NEVER;
2025         } else {
2026                 how = HAMMER2_RESOLVE_MAYBE;
2027         }
2028         if (flags & HAMMER2_LOOKUP_SHARED) {
2029                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2030                 how_always |= HAMMER2_RESOLVE_SHARED;
2031                 how |= HAMMER2_RESOLVE_SHARED;
2032         }
2033
2034         /*
2035          * Calculate key to locate first/next element, unlocking the previous
2036          * element as we go.  Be careful, the key calculation can overflow.
2037          */
2038         if (chain) {
2039                 key = chain->bref.key +
2040                       ((hammer2_key_t)1 << chain->bref.keybits);
2041                 hammer2_chain_unlock(chain);
2042                 hammer2_chain_drop(chain);
2043                 chain = NULL;
2044                 if (key == 0)
2045                         goto done;
2046         } else {
2047                 key = 0;
2048         }
2049
2050 again:
2051         KKASSERT(parent->error == 0);   /* XXX case not handled yet */
2052         if (--maxloops == 0)
2053                 panic("hammer2_chain_scan: maxloops");
2054         /*
2055          * Locate the blockref array.  Currently we do a fully associative
2056          * search through the array.
2057          */
2058         switch(parent->bref.type) {
2059         case HAMMER2_BREF_TYPE_INODE:
2060                 /*
2061                  * An inode with embedded data has no sub-chains.
2062                  *
2063                  * WARNING! Bulk scan code may pass a static chain marked
2064                  *          as BREF_TYPE_INODE with a copy of the volume
2065                  *          root blockset to snapshot the volume.
2066                  */
2067                 if (parent->data->ipdata.meta.op_flags &
2068                     HAMMER2_OPFLAG_DIRECTDATA) {
2069                         goto done;
2070                 }
2071                 base = &parent->data->ipdata.u.blockset.blockref[0];
2072                 count = HAMMER2_SET_COUNT;
2073                 break;
2074         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2075         case HAMMER2_BREF_TYPE_INDIRECT:
2076                 /*
2077                  * Optimize indirect blocks in the INITIAL state to avoid
2078                  * I/O.
2079                  */
2080                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2081                         base = NULL;
2082                 } else {
2083                         if (parent->data == NULL)
2084                                 panic("parent->data is NULL");
2085                         base = &parent->data->npdata[0];
2086                 }
2087                 count = parent->bytes / sizeof(hammer2_blockref_t);
2088                 break;
2089         case HAMMER2_BREF_TYPE_VOLUME:
2090                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2091                 count = HAMMER2_SET_COUNT;
2092                 break;
2093         case HAMMER2_BREF_TYPE_FREEMAP:
2094                 base = &parent->data->blkset.blockref[0];
2095                 count = HAMMER2_SET_COUNT;
2096                 break;
2097         default:
2098                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2099                       parent->bref.type);
2100                 base = NULL;    /* safety */
2101                 count = 0;      /* safety */
2102         }
2103
2104         /*
2105          * Merged scan to find next candidate.
2106          *
2107          * hammer2_base_*() functions require the parent->core.live_* fields
2108          * to be synchronized.
2109          *
2110          * We need to hold the spinlock to access the block array and RB tree
2111          * and to interlock chain creation.
2112          */
2113         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2114                 hammer2_chain_countbrefs(parent, base, count);
2115
2116         next_key = 0;
2117         hammer2_spin_ex(&parent->core.spin);
2118         chain = hammer2_combined_find(parent, base, count,
2119                                       cache_indexp, &next_key,
2120                                       key, HAMMER2_KEY_MAX,
2121                                       &bref);
2122         generation = parent->core.generation;
2123
2124         /*
2125          * Exhausted parent chain, we're done.
2126          */
2127         if (bref == NULL) {
2128                 hammer2_spin_unex(&parent->core.spin);
2129                 KKASSERT(chain == NULL);
2130                 goto done;
2131         }
2132
2133         /*
2134          * Selected from blockref or in-memory chain.
2135          */
2136         if (chain == NULL) {
2137                 bcopy = *bref;
2138                 hammer2_spin_unex(&parent->core.spin);
2139                 chain = hammer2_chain_get(parent, generation, &bcopy);
2140                 if (chain == NULL) {
2141                         kprintf("retry scan parent %p keys %016jx\n",
2142                                 parent, key);
2143                         goto again;
2144                 }
2145                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2146                         hammer2_chain_drop(chain);
2147                         chain = NULL;
2148                         goto again;
2149                 }
2150         } else {
2151                 hammer2_chain_ref(chain);
2152                 hammer2_spin_unex(&parent->core.spin);
2153         }
2154
2155         /*
2156          * chain is referenced but not locked.  We must lock the chain
2157          * to obtain definitive DUPLICATED/DELETED state
2158          */
2159         hammer2_chain_lock(chain, how);
2160
2161         /*
2162          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2163          *
2164          * NOTE: chain's key range is not relevant as there might be
2165          *       one-offs within the range that are not deleted.
2166          *
2167          * NOTE: XXX this could create problems with scans used in
2168          *       situations other than mount-time recovery.
2169          *
2170          * NOTE: Lookups can race delete-duplicate because
2171          *       delete-duplicate does not lock the parent's core
2172          *       (they just use the spinlock on the core).  We must
2173          *       check for races by comparing the DUPLICATED flag before
2174          *       releasing the spinlock with the flag after locking the
2175          *       chain.
2176          */
2177         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2178                 hammer2_chain_unlock(chain);
2179                 hammer2_chain_drop(chain);
2180                 chain = NULL;
2181
2182                 key = next_key;
2183                 if (key == 0)
2184                         goto done;
2185                 goto again;
2186         }
2187
2188 done:
2189         /*
2190          * All done, return the chain or NULL
2191          */
2192         return (chain);
2193 }
2194
2195 /*
2196  * Create and return a new hammer2 system memory structure of the specified
2197  * key, type and size and insert it under (*parentp).  This is a full
2198  * insertion, based on the supplied key/keybits, and may involve creating
2199  * indirect blocks and moving other chains around via delete/duplicate.
2200  *
2201  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2202  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2203  * FULL.  This typically means that the caller is creating the chain after
2204  * doing a hammer2_chain_lookup().
2205  *
2206  * (*parentp) must be exclusive locked and may be replaced on return
2207  * depending on how much work the function had to do.
2208  *
2209  * (*parentp) must not be errored or this function will assert.
2210  *
2211  * (*chainp) usually starts out NULL and returns the newly created chain,
2212  * but if the caller desires the caller may allocate a disconnected chain
2213  * and pass it in instead.
2214  *
2215  * This function should NOT be used to insert INDIRECT blocks.  It is
2216  * typically used to create/insert inodes and data blocks.
2217  *
2218  * Caller must pass-in an exclusively locked parent the new chain is to
2219  * be inserted under, and optionally pass-in a disconnected, exclusively
2220  * locked chain to insert (else we create a new chain).  The function will
2221  * adjust (*parentp) as necessary, create or connect the chain, and
2222  * return an exclusively locked chain in *chainp.
2223  *
2224  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2225  * and will be reassigned.
2226  */
2227 int
2228 hammer2_chain_create(hammer2_chain_t **parentp,
2229                      hammer2_chain_t **chainp, hammer2_pfs_t *pmp,
2230                      hammer2_key_t key, int keybits, int type, size_t bytes,
2231                      hammer2_tid_t mtid, int flags)
2232 {
2233         hammer2_dev_t *hmp;
2234         hammer2_chain_t *chain;
2235         hammer2_chain_t *parent;
2236         hammer2_blockref_t *base;
2237         hammer2_blockref_t dummy;
2238         int allocated = 0;
2239         int error = 0;
2240         int count;
2241         int maxloops = 300000;
2242
2243         /*
2244          * Topology may be crossing a PFS boundary.
2245          */
2246         parent = *parentp;
2247         KKASSERT(hammer2_mtx_owned(&parent->lock));
2248         KKASSERT(parent->error == 0);
2249         hmp = parent->hmp;
2250         chain = *chainp;
2251
2252         if (chain == NULL) {
2253                 /*
2254                  * First allocate media space and construct the dummy bref,
2255                  * then allocate the in-memory chain structure.  Set the
2256                  * INITIAL flag for fresh chains which do not have embedded
2257                  * data.
2258                  *
2259                  * XXX for now set the check mode of the child based on
2260                  *     the parent or, if the parent is an inode, the
2261                  *     specification in the inode.
2262                  */
2263                 bzero(&dummy, sizeof(dummy));
2264                 dummy.type = type;
2265                 dummy.key = key;
2266                 dummy.keybits = keybits;
2267                 dummy.data_off = hammer2_getradix(bytes);
2268                 dummy.methods = parent->bref.methods;
2269                 if (parent->bref.type == HAMMER2_BREF_TYPE_INODE &&
2270                     parent->data) {
2271                         dummy.methods &= ~HAMMER2_ENC_CHECK(-1);
2272                         dummy.methods |= HAMMER2_ENC_CHECK(
2273                                           parent->data->ipdata.meta.check_algo);
2274                 }
2275
2276                 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2277
2278                 /*
2279                  * Lock the chain manually, chain_lock will load the chain
2280                  * which we do NOT want to do.  (note: chain->refs is set
2281                  * to 1 by chain_alloc() for us, but lockcnt is not).
2282                  */
2283                 chain->lockcnt = 1;
2284                 hammer2_mtx_ex(&chain->lock);
2285                 allocated = 1;
2286
2287                 /*
2288                  * Set INITIAL to optimize I/O.  The flag will generally be
2289                  * processed when we call hammer2_chain_modify().
2290                  *
2291                  * Recalculate bytes to reflect the actual media block
2292                  * allocation.
2293                  */
2294                 bytes = (hammer2_off_t)1 <<
2295                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2296                 chain->bytes = bytes;
2297
2298                 switch(type) {
2299                 case HAMMER2_BREF_TYPE_VOLUME:
2300                 case HAMMER2_BREF_TYPE_FREEMAP:
2301                         panic("hammer2_chain_create: called with volume type");
2302                         break;
2303                 case HAMMER2_BREF_TYPE_INDIRECT:
2304                         panic("hammer2_chain_create: cannot be used to"
2305                               "create indirect block");
2306                         break;
2307                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2308                         panic("hammer2_chain_create: cannot be used to"
2309                               "create freemap root or node");
2310                         break;
2311                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2312                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2313                         /* fall through */
2314                 case HAMMER2_BREF_TYPE_INODE:
2315                 case HAMMER2_BREF_TYPE_DATA:
2316                 default:
2317                         /*
2318                          * leave chain->data NULL, set INITIAL
2319                          */
2320                         KKASSERT(chain->data == NULL);
2321                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2322                         break;
2323                 }
2324         } else {
2325                 /*
2326                  * We are reattaching a previously deleted chain, possibly
2327                  * under a new parent and possibly with a new key/keybits.
2328                  * The chain does not have to be in a modified state.  The
2329                  * UPDATE flag will be set later on in this routine.
2330                  *
2331                  * Do NOT mess with the current state of the INITIAL flag.
2332                  */
2333                 chain->bref.key = key;
2334                 chain->bref.keybits = keybits;
2335                 if (chain->flags & HAMMER2_CHAIN_DELETED)
2336                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2337                 KKASSERT(chain->parent == NULL);
2338         }
2339         if (flags & HAMMER2_INSERT_PFSROOT)
2340                 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2341         else
2342                 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2343
2344         /*
2345          * Calculate how many entries we have in the blockref array and
2346          * determine if an indirect block is required.
2347          */
2348 again:
2349         if (--maxloops == 0)
2350                 panic("hammer2_chain_create: maxloops");
2351
2352         switch(parent->bref.type) {
2353         case HAMMER2_BREF_TYPE_INODE:
2354                 KKASSERT((parent->data->ipdata.meta.op_flags &
2355                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2356                 KKASSERT(parent->data != NULL);
2357                 base = &parent->data->ipdata.u.blockset.blockref[0];
2358                 count = HAMMER2_SET_COUNT;
2359                 break;
2360         case HAMMER2_BREF_TYPE_INDIRECT:
2361         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2362                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2363                         base = NULL;
2364                 else
2365                         base = &parent->data->npdata[0];
2366                 count = parent->bytes / sizeof(hammer2_blockref_t);
2367                 break;
2368         case HAMMER2_BREF_TYPE_VOLUME:
2369                 KKASSERT(parent->data != NULL);
2370                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2371                 count = HAMMER2_SET_COUNT;
2372                 break;
2373         case HAMMER2_BREF_TYPE_FREEMAP:
2374                 KKASSERT(parent->data != NULL);
2375                 base = &parent->data->blkset.blockref[0];
2376                 count = HAMMER2_SET_COUNT;
2377                 break;
2378         default:
2379                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2380                       parent->bref.type);
2381                 base = NULL;
2382                 count = 0;
2383                 break;
2384         }
2385
2386         /*
2387          * Make sure we've counted the brefs
2388          */
2389         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2390                 hammer2_chain_countbrefs(parent, base, count);
2391
2392         KKASSERT(parent->core.live_count >= 0 &&
2393                  parent->core.live_count <= count);
2394
2395         /*
2396          * If no free blockref could be found we must create an indirect
2397          * block and move a number of blockrefs into it.  With the parent
2398          * locked we can safely lock each child in order to delete+duplicate
2399          * it without causing a deadlock.
2400          *
2401          * This may return the new indirect block or the old parent depending
2402          * on where the key falls.  NULL is returned on error.
2403          */
2404         if (parent->core.live_count == count) {
2405                 hammer2_chain_t *nparent;
2406
2407                 nparent = hammer2_chain_create_indirect(parent, key, keybits,
2408                                                         mtid, type, &error);
2409                 if (nparent == NULL) {
2410                         if (allocated)
2411                                 hammer2_chain_drop(chain);
2412                         chain = NULL;
2413                         goto done;
2414                 }
2415                 if (parent != nparent) {
2416                         hammer2_chain_unlock(parent);
2417                         hammer2_chain_drop(parent);
2418                         parent = *parentp = nparent;
2419                 }
2420                 goto again;
2421         }
2422
2423         /*
2424          * Link the chain into its parent.
2425          */
2426         if (chain->parent != NULL)
2427                 panic("hammer2: hammer2_chain_create: chain already connected");
2428         KKASSERT(chain->parent == NULL);
2429         hammer2_chain_insert(parent, chain,
2430                              HAMMER2_CHAIN_INSERT_SPIN |
2431                              HAMMER2_CHAIN_INSERT_LIVE,
2432                              0);
2433
2434         if (allocated) {
2435                 /*
2436                  * Mark the newly created chain modified.  This will cause
2437                  * UPDATE to be set and process the INITIAL flag.
2438                  *
2439                  * Device buffers are not instantiated for DATA elements
2440                  * as these are handled by logical buffers.
2441                  *
2442                  * Indirect and freemap node indirect blocks are handled
2443                  * by hammer2_chain_create_indirect() and not by this
2444                  * function.
2445                  *
2446                  * Data for all other bref types is expected to be
2447                  * instantiated (INODE, LEAF).
2448                  */
2449                 switch(chain->bref.type) {
2450                 case HAMMER2_BREF_TYPE_DATA:
2451                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2452                 case HAMMER2_BREF_TYPE_INODE:
2453                         hammer2_chain_modify(chain, mtid,
2454                                              HAMMER2_MODIFY_OPTDATA);
2455                         break;
2456                 default:
2457                         /*
2458                          * Remaining types are not supported by this function.
2459                          * In particular, INDIRECT and LEAF_NODE types are
2460                          * handled by create_indirect().
2461                          */
2462                         panic("hammer2_chain_create: bad type: %d",
2463                               chain->bref.type);
2464                         /* NOT REACHED */
2465                         break;
2466                 }
2467         } else {
2468                 /*
2469                  * When reconnecting a chain we must set UPDATE and
2470                  * setflush so the flush recognizes that it must update
2471                  * the bref in the parent.
2472                  */
2473                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2474                         hammer2_chain_ref(chain);
2475                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2476                 }
2477         }
2478
2479         /*
2480          * We must setflush(parent) to ensure that it recurses through to
2481          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2482          * already set in the chain (so it won't recurse up to set it in the
2483          * parent).
2484          */
2485         hammer2_chain_setflush(parent);
2486
2487 done:
2488         *chainp = chain;
2489
2490         return (error);
2491 }
2492
2493 /*
2494  * Move the chain from its old parent to a new parent.  The chain must have
2495  * already been deleted or already disconnected (or never associated) with
2496  * a parent.  The chain is reassociated with the new parent and the deleted
2497  * flag will be cleared (no longer deleted).  The chain's modification state
2498  * is not altered.
2499  *
2500  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2501  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2502  * FULL.  This typically means that the caller is creating the chain after
2503  * doing a hammer2_chain_lookup().
2504  *
2505  * A non-NULL bref is typically passed when key and keybits must be overridden.
2506  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2507  * from a passed-in bref and uses the old chain's bref for everything else.
2508  *
2509  * Neither (parent) or (chain) can be errored.
2510  *
2511  * If (parent) is non-NULL then the new duplicated chain is inserted under
2512  * the parent.
2513  *
2514  * If (parent) is NULL then the newly duplicated chain is not inserted
2515  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2516  * passing into hammer2_chain_create() after this function returns).
2517  *
2518  * WARNING! This function calls create which means it can insert indirect
2519  *          blocks.  This can cause other unrelated chains in the parent to
2520  *          be moved to a newly inserted indirect block in addition to the
2521  *          specific chain.
2522  */
2523 void
2524 hammer2_chain_rename(hammer2_blockref_t *bref,
2525                      hammer2_chain_t **parentp, hammer2_chain_t *chain,
2526                      hammer2_tid_t mtid, int flags)
2527 {
2528         hammer2_dev_t *hmp;
2529         hammer2_chain_t *parent;
2530         size_t bytes;
2531
2532         /*
2533          * WARNING!  We should never resolve DATA to device buffers
2534          *           (XXX allow it if the caller did?), and since
2535          *           we currently do not have the logical buffer cache
2536          *           buffer in-hand to fix its cached physical offset
2537          *           we also force the modify code to not COW it. XXX
2538          */
2539         hmp = chain->hmp;
2540         KKASSERT(chain->parent == NULL);
2541         KKASSERT(chain->error == 0);
2542
2543         /*
2544          * Now create a duplicate of the chain structure, associating
2545          * it with the same core, making it the same size, pointing it
2546          * to the same bref (the same media block).
2547          */
2548         if (bref == NULL)
2549                 bref = &chain->bref;
2550         bytes = (hammer2_off_t)1 <<
2551                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2552
2553         /*
2554          * If parent is not NULL the duplicated chain will be entered under
2555          * the parent and the UPDATE bit set to tell flush to update
2556          * the blockref.
2557          *
2558          * We must setflush(parent) to ensure that it recurses through to
2559          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2560          * already set in the chain (so it won't recurse up to set it in the
2561          * parent).
2562          *
2563          * Having both chains locked is extremely important for atomicy.
2564          */
2565         if (parentp && (parent = *parentp) != NULL) {
2566                 KKASSERT(hammer2_mtx_owned(&parent->lock));
2567                 KKASSERT(parent->refs > 0);
2568                 KKASSERT(parent->error == 0);
2569
2570                 hammer2_chain_create(parentp, &chain, chain->pmp,
2571                                      bref->key, bref->keybits, bref->type,
2572                                      chain->bytes, mtid, flags);
2573                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2574                 hammer2_chain_setflush(*parentp);
2575         }
2576 }
2577
2578 /*
2579  * Helper function for deleting chains.
2580  *
2581  * The chain is removed from the live view (the RBTREE) as well as the parent's
2582  * blockmap.  Both chain and its parent must be locked.
2583  *
2584  * parent may not be errored.  chain can be errored.
2585  */
2586 static void
2587 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
2588                              hammer2_tid_t mtid, int flags)
2589 {
2590         hammer2_dev_t *hmp;
2591
2592         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2593                                   HAMMER2_CHAIN_FICTITIOUS)) == 0);
2594         KKASSERT(chain->parent == parent);
2595         hmp = chain->hmp;
2596
2597         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2598                 /*
2599                  * Chain is blockmapped, so there must be a parent.
2600                  * Atomically remove the chain from the parent and remove
2601                  * the blockmap entry.
2602                  */
2603                 hammer2_blockref_t *base;
2604                 int count;
2605
2606                 KKASSERT(parent != NULL);
2607                 KKASSERT(parent->error == 0);
2608                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2609                 hammer2_chain_modify(parent, mtid, HAMMER2_MODIFY_OPTDATA);
2610
2611                 /*
2612                  * Calculate blockmap pointer
2613                  */
2614                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2615                 hammer2_spin_ex(&parent->core.spin);
2616
2617                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2618                 atomic_add_int(&parent->core.live_count, -1);
2619                 ++parent->core.generation;
2620                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2621                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2622                 --parent->core.chain_count;
2623                 chain->parent = NULL;
2624
2625                 switch(parent->bref.type) {
2626                 case HAMMER2_BREF_TYPE_INODE:
2627                         /*
2628                          * Access the inode's block array.  However, there
2629                          * is no block array if the inode is flagged
2630                          * DIRECTDATA.  The DIRECTDATA case typicaly only
2631                          * occurs when a hardlink has been shifted up the
2632                          * tree and the original inode gets replaced with
2633                          * an OBJTYPE_HARDLINK placeholding inode.
2634                          */
2635                         if (parent->data &&
2636                             (parent->data->ipdata.meta.op_flags &
2637                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2638                                 base =
2639                                    &parent->data->ipdata.u.blockset.blockref[0];
2640                         } else {
2641                                 base = NULL;
2642                         }
2643                         count = HAMMER2_SET_COUNT;
2644                         break;
2645                 case HAMMER2_BREF_TYPE_INDIRECT:
2646                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2647                         if (parent->data)
2648                                 base = &parent->data->npdata[0];
2649                         else
2650                                 base = NULL;
2651                         count = parent->bytes / sizeof(hammer2_blockref_t);
2652                         break;
2653                 case HAMMER2_BREF_TYPE_VOLUME:
2654                         base = &parent->data->voldata.
2655                                         sroot_blockset.blockref[0];
2656                         count = HAMMER2_SET_COUNT;
2657                         break;
2658                 case HAMMER2_BREF_TYPE_FREEMAP:
2659                         base = &parent->data->blkset.blockref[0];
2660                         count = HAMMER2_SET_COUNT;
2661                         break;
2662                 default:
2663                         base = NULL;
2664                         count = 0;
2665                         panic("hammer2_flush_pass2: "
2666                               "unrecognized blockref type: %d",
2667                               parent->bref.type);
2668                 }
2669
2670                 /*
2671                  * delete blockmapped chain from its parent.
2672                  *
2673                  * The parent is not affected by any statistics in chain
2674                  * which are pending synchronization.  That is, there is
2675                  * nothing to undo in the parent since they have not yet
2676                  * been incorporated into the parent.
2677                  *
2678                  * The parent is affected by statistics stored in inodes.
2679                  * Those have already been synchronized, so they must be
2680                  * undone.  XXX split update possible w/delete in middle?
2681                  */
2682                 if (base) {
2683                         int cache_index = -1;
2684                         hammer2_base_delete(parent, base, count,
2685                                             &cache_index, chain);
2686                 }
2687                 hammer2_spin_unex(&parent->core.spin);
2688         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2689                 /*
2690                  * Chain is not blockmapped but a parent is present.
2691                  * Atomically remove the chain from the parent.  There is
2692                  * no blockmap entry to remove.
2693                  *
2694                  * Because chain was associated with a parent but not
2695                  * synchronized, the chain's *_count_up fields contain
2696                  * inode adjustment statistics which must be undone.
2697                  */
2698                 hammer2_spin_ex(&parent->core.spin);
2699                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2700                 atomic_add_int(&parent->core.live_count, -1);
2701                 ++parent->core.generation;
2702                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2703                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2704                 --parent->core.chain_count;
2705                 chain->parent = NULL;
2706                 hammer2_spin_unex(&parent->core.spin);
2707         } else {
2708                 /*
2709                  * Chain is not blockmapped and has no parent.  This
2710                  * is a degenerate case.
2711                  */
2712                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2713         }
2714 }
2715
2716 /*
2717  * Create an indirect block that covers one or more of the elements in the
2718  * current parent.  Either returns the existing parent with no locking or
2719  * ref changes or returns the new indirect block locked and referenced
2720  * and leaving the original parent lock/ref intact as well.
2721  *
2722  * If an error occurs, NULL is returned and *errorp is set to the error.
2723  *
2724  * The returned chain depends on where the specified key falls.
2725  *
2726  * The key/keybits for the indirect mode only needs to follow three rules:
2727  *
2728  * (1) That all elements underneath it fit within its key space and
2729  *
2730  * (2) That all elements outside it are outside its key space.
2731  *
2732  * (3) When creating the new indirect block any elements in the current
2733  *     parent that fit within the new indirect block's keyspace must be
2734  *     moved into the new indirect block.
2735  *
2736  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2737  *     keyspace the the current parent, but lookup/iteration rules will
2738  *     ensure (and must ensure) that rule (2) for all parents leading up
2739  *     to the nearest inode or the root volume header is adhered to.  This
2740  *     is accomplished by always recursing through matching keyspaces in
2741  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
2742  *
2743  * The current implementation calculates the current worst-case keyspace by
2744  * iterating the current parent and then divides it into two halves, choosing
2745  * whichever half has the most elements (not necessarily the half containing
2746  * the requested key).
2747  *
2748  * We can also opt to use the half with the least number of elements.  This
2749  * causes lower-numbered keys (aka logical file offsets) to recurse through
2750  * fewer indirect blocks and higher-numbered keys to recurse through more.
2751  * This also has the risk of not moving enough elements to the new indirect
2752  * block and being forced to create several indirect blocks before the element
2753  * can be inserted.
2754  *
2755  * Must be called with an exclusively locked parent.
2756  */
2757 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2758                                 hammer2_key_t *keyp, int keybits,
2759                                 hammer2_blockref_t *base, int count);
2760 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2761                                 hammer2_key_t *keyp, int keybits,
2762                                 hammer2_blockref_t *base, int count);
2763 static
2764 hammer2_chain_t *
2765 hammer2_chain_create_indirect(hammer2_chain_t *parent,
2766                               hammer2_key_t create_key, int create_bits,
2767                               hammer2_tid_t mtid, int for_type, int *errorp)
2768 {
2769         hammer2_dev_t *hmp;
2770         hammer2_blockref_t *base;
2771         hammer2_blockref_t *bref;
2772         hammer2_blockref_t bcopy;
2773         hammer2_chain_t *chain;
2774         hammer2_chain_t *ichain;
2775         hammer2_chain_t dummy;
2776         hammer2_key_t key = create_key;
2777         hammer2_key_t key_beg;
2778         hammer2_key_t key_end;
2779         hammer2_key_t key_next;
2780         int keybits = create_bits;
2781         int count;
2782         int nbytes;
2783         int cache_index;
2784         int loops;
2785         int reason;
2786         int generation;
2787         int maxloops = 300000;
2788
2789         /*
2790          * Calculate the base blockref pointer or NULL if the chain
2791          * is known to be empty.  We need to calculate the array count
2792          * for RB lookups either way.
2793          */
2794         hmp = parent->hmp;
2795         *errorp = 0;
2796         KKASSERT(hammer2_mtx_owned(&parent->lock));
2797
2798         /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
2799         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2800                 base = NULL;
2801
2802                 switch(parent->bref.type) {
2803                 case HAMMER2_BREF_TYPE_INODE:
2804                         count = HAMMER2_SET_COUNT;
2805                         break;
2806                 case HAMMER2_BREF_TYPE_INDIRECT:
2807                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2808                         count = parent->bytes / sizeof(hammer2_blockref_t);
2809                         break;
2810                 case HAMMER2_BREF_TYPE_VOLUME:
2811                         count = HAMMER2_SET_COUNT;
2812                         break;
2813                 case HAMMER2_BREF_TYPE_FREEMAP:
2814                         count = HAMMER2_SET_COUNT;
2815                         break;
2816                 default:
2817                         panic("hammer2_chain_create_indirect: "
2818                               "unrecognized blockref type: %d",
2819                               parent->bref.type);
2820                         count = 0;
2821                         break;
2822                 }
2823         } else {
2824                 switch(parent->bref.type) {
2825                 case HAMMER2_BREF_TYPE_INODE:
2826                         base = &parent->data->ipdata.u.blockset.blockref[0];
2827                         count = HAMMER2_SET_COUNT;
2828                         break;
2829                 case HAMMER2_BREF_TYPE_INDIRECT:
2830                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2831                         base = &parent->data->npdata[0];
2832                         count = parent->bytes / sizeof(hammer2_blockref_t);
2833                         break;
2834                 case HAMMER2_BREF_TYPE_VOLUME:
2835                         base = &parent->data->voldata.
2836                                         sroot_blockset.blockref[0];
2837                         count = HAMMER2_SET_COUNT;
2838                         break;
2839                 case HAMMER2_BREF_TYPE_FREEMAP:
2840                         base = &parent->data->blkset.blockref[0];
2841                         count = HAMMER2_SET_COUNT;
2842                         break;
2843                 default:
2844                         panic("hammer2_chain_create_indirect: "
2845                               "unrecognized blockref type: %d",
2846                               parent->bref.type);
2847                         count = 0;
2848                         break;
2849                 }
2850         }
2851
2852         /*
2853          * dummy used in later chain allocation (no longer used for lookups).
2854          */
2855         bzero(&dummy, sizeof(dummy));
2856
2857         /*
2858          * When creating an indirect block for a freemap node or leaf
2859          * the key/keybits must be fitted to static radix levels because
2860          * particular radix levels use particular reserved blocks in the
2861          * related zone.
2862          *
2863          * This routine calculates the key/radix of the indirect block
2864          * we need to create, and whether it is on the high-side or the
2865          * low-side.
2866          */
2867         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2868             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2869                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2870                                                        base, count);
2871         } else {
2872                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2873                                                       base, count);
2874         }
2875
2876         /*
2877          * Normalize the key for the radix being represented, keeping the
2878          * high bits and throwing away the low bits.
2879          */
2880         key &= ~(((hammer2_key_t)1 << keybits) - 1);
2881
2882         /*
2883          * How big should our new indirect block be?  It has to be at least
2884          * as large as its parent.
2885          *
2886          * The freemap uses a specific indirect block size.
2887          *
2888          * The first indirect block level down from an inode typically
2889          * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
2890          */
2891         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2892             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2893                 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
2894         } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
2895                 nbytes = HAMMER2_IND_BYTES_MIN;
2896         } else {
2897                 nbytes = HAMMER2_IND_BYTES_MAX;
2898         }
2899         if (nbytes < count * sizeof(hammer2_blockref_t)) {
2900                 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
2901                          for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
2902                 nbytes = count * sizeof(hammer2_blockref_t);
2903         }
2904
2905         /*
2906          * Ok, create our new indirect block
2907          */
2908         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2909             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2910                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2911         } else {
2912                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2913         }
2914         dummy.bref.key = key;
2915         dummy.bref.keybits = keybits;
2916         dummy.bref.data_off = hammer2_getradix(nbytes);
2917         dummy.bref.methods = parent->bref.methods;
2918
2919         ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
2920         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2921         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2922         /* ichain has one ref at this point */
2923
2924         /*
2925          * We have to mark it modified to allocate its block, but use
2926          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
2927          * it won't be acted upon by the flush code.
2928          */
2929         hammer2_chain_modify(ichain, mtid, HAMMER2_MODIFY_OPTDATA);
2930
2931         /*
2932          * Iterate the original parent and move the matching brefs into
2933          * the new indirect block.
2934          *
2935          * XXX handle flushes.
2936          */
2937         key_beg = 0;
2938         key_end = HAMMER2_KEY_MAX;
2939         cache_index = 0;
2940         hammer2_spin_ex(&parent->core.spin);
2941         loops = 0;
2942         reason = 0;
2943
2944         for (;;) {
2945                 if (++loops > 100000) {
2946                     hammer2_spin_unex(&parent->core.spin);
2947                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2948                           reason, parent, base, count, key_next);
2949                 }
2950
2951                 /*
2952                  * NOTE: spinlock stays intact, returned chain (if not NULL)
2953                  *       is not referenced or locked which means that we
2954                  *       cannot safely check its flagged / deletion status
2955                  *       until we lock it.
2956                  */
2957                 chain = hammer2_combined_find(parent, base, count,
2958                                               &cache_index, &key_next,
2959                                               key_beg, key_end,
2960                                               &bref);
2961                 generation = parent->core.generation;
2962                 if (bref == NULL)
2963                         break;
2964                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2965
2966                 /*
2967                  * Skip keys that are not within the key/radix of the new
2968                  * indirect block.  They stay in the parent.
2969                  */
2970                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2971                     (key ^ bref->key)) != 0) {
2972                         goto next_key_spinlocked;
2973                 }
2974
2975                 /*
2976                  * Load the new indirect block by acquiring the related
2977                  * chains (potentially from media as it might not be
2978                  * in-memory).  Then move it to the new parent (ichain)
2979                  * via DELETE-DUPLICATE.
2980                  *
2981                  * chain is referenced but not locked.  We must lock the
2982                  * chain to obtain definitive DUPLICATED/DELETED state
2983                  */
2984                 if (chain) {
2985                         /*
2986                          * Use chain already present in the RBTREE
2987                          */
2988                         hammer2_chain_ref(chain);
2989                         hammer2_spin_unex(&parent->core.spin);
2990                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
2991                 } else {
2992                         /*
2993                          * Get chain for blockref element.  _get returns NULL
2994                          * on insertion race.
2995                          */
2996                         bcopy = *bref;
2997                         hammer2_spin_unex(&parent->core.spin);
2998                         chain = hammer2_chain_get(parent, generation, &bcopy);
2999                         if (chain == NULL) {
3000                                 reason = 1;
3001                                 hammer2_spin_ex(&parent->core.spin);
3002                                 continue;
3003                         }
3004                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3005                                 kprintf("REASON 2\n");
3006                                 reason = 2;
3007                                 hammer2_chain_drop(chain);
3008                                 hammer2_spin_ex(&parent->core.spin);
3009                                 continue;
3010                         }
3011                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3012                 }
3013
3014                 /*
3015                  * This is always live so if the chain has been deleted
3016                  * we raced someone and we have to retry.
3017                  *
3018                  * NOTE: Lookups can race delete-duplicate because
3019                  *       delete-duplicate does not lock the parent's core
3020                  *       (they just use the spinlock on the core).  We must
3021                  *       check for races by comparing the DUPLICATED flag before
3022                  *       releasing the spinlock with the flag after locking the
3023                  *       chain.
3024                  *
3025                  *       (note reversed logic for this one)
3026                  */
3027                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3028                         hammer2_chain_unlock(chain);
3029                         hammer2_chain_drop(chain);
3030                         goto next_key;
3031                 }
3032
3033                 /*
3034                  * Shift the chain to the indirect block.
3035                  *
3036                  * WARNING! No reason for us to load chain data, pass NOSTATS
3037                  *          to prevent delete/insert from trying to access
3038                  *          inode stats (and thus asserting if there is no
3039                  *          chain->data loaded).
3040                  */
3041                 hammer2_chain_delete(parent, chain, mtid, 0);
3042                 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3043                 hammer2_chain_unlock(chain);
3044                 hammer2_chain_drop(chain);
3045                 KKASSERT(parent->refs > 0);
3046                 chain = NULL;
3047 next_key:
3048                 hammer2_spin_ex(&parent->core.spin);
3049 next_key_spinlocked:
3050                 if (--maxloops == 0)
3051                         panic("hammer2_chain_create_indirect: maxloops");
3052                 reason = 4;
3053                 if (key_next == 0 || key_next > key_end)
3054                         break;
3055                 key_beg = key_next;
3056                 /* loop */
3057         }
3058         hammer2_spin_unex(&parent->core.spin);
3059
3060         /*
3061          * Insert the new indirect block into the parent now that we've
3062          * cleared out some entries in the parent.  We calculated a good
3063          * insertion index in the loop above (ichain->index).
3064          *
3065          * We don't have to set UPDATE here because we mark ichain
3066          * modified down below (so the normal modified -> flush -> set-moved
3067          * sequence applies).
3068          *
3069          * The insertion shouldn't race as this is a completely new block
3070          * and the parent is locked.
3071          */
3072         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3073         hammer2_chain_insert(parent, ichain,
3074                              HAMMER2_CHAIN_INSERT_SPIN |
3075                              HAMMER2_CHAIN_INSERT_LIVE,
3076                              0);
3077
3078         /*
3079          * Make sure flushes propogate after our manual insertion.
3080          */
3081         hammer2_chain_setflush(ichain);
3082         hammer2_chain_setflush(parent);
3083
3084         /*
3085          * Figure out what to return.
3086          */
3087         if (~(((hammer2_key_t)1 << keybits) - 1) &
3088                    (create_key ^ key)) {
3089                 /*
3090                  * Key being created is outside the key range,
3091                  * return the original parent.
3092                  */
3093                 hammer2_chain_unlock(ichain);
3094                 hammer2_chain_drop(ichain);
3095         } else {
3096                 /*
3097                  * Otherwise its in the range, return the new parent.
3098                  * (leave both the new and old parent locked).
3099                  */
3100                 parent = ichain;
3101         }
3102
3103         return(parent);
3104 }
3105
3106 /*
3107  * Calculate the keybits and highside/lowside of the freemap node the
3108  * caller is creating.
3109  *
3110  * This routine will specify the next higher-level freemap key/radix
3111  * representing the lowest-ordered set.  By doing so, eventually all
3112  * low-ordered sets will be moved one level down.
3113  *
3114  * We have to be careful here because the freemap reserves a limited
3115  * number of blocks for a limited number of levels.  So we can't just
3116  * push indiscriminately.
3117  */
3118 int
3119 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3120                              int keybits, hammer2_blockref_t *base, int count)
3121 {
3122         hammer2_chain_t *chain;
3123         hammer2_blockref_t *bref;
3124         hammer2_key_t key;
3125         hammer2_key_t key_beg;
3126         hammer2_key_t key_end;
3127         hammer2_key_t key_next;
3128         int cache_index;
3129         int locount;
3130         int hicount;
3131         int maxloops = 300000;
3132
3133         key = *keyp;
3134         locount = 0;
3135         hicount = 0;
3136         keybits = 64;
3137
3138         /*
3139          * Calculate the range of keys in the array being careful to skip
3140          * slots which are overridden with a deletion.
3141          */
3142         key_beg = 0;
3143         key_end = HAMMER2_KEY_MAX;
3144         cache_index = 0;
3145         hammer2_spin_ex(&parent->core.spin);
3146
3147         for (;;) {
3148                 if (--maxloops == 0) {
3149                         panic("indkey_freemap shit %p %p:%d\n",
3150                               parent, base, count);
3151                 }
3152                 chain = hammer2_combined_find(parent, base, count,
3153                                               &cache_index, &key_next,
3154                                               key_beg, key_end,
3155                                               &bref);
3156
3157                 /*
3158                  * Exhausted search
3159                  */
3160                 if (bref == NULL)
3161                         break;
3162
3163                 /*
3164                  * Skip deleted chains.
3165                  */
3166                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3167                         if (key_next == 0 || key_next > key_end)
3168                                 break;
3169                         key_beg = key_next;
3170                         continue;
3171                 }
3172
3173                 /*
3174                  * Use the full live (not deleted) element for the scan
3175                  * iteration.  HAMMER2 does not allow partial replacements.
3176                  *
3177                  * XXX should be built into hammer2_combined_find().
3178                  */
3179                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3180
3181                 if (keybits > bref->keybits) {
3182                         key = bref->key;
3183                         keybits = bref->keybits;
3184                 } else if (keybits == bref->keybits && bref->key < key) {
3185                         key = bref->key;
3186                 }
3187                 if (key_next == 0)
3188                         break;
3189                 key_beg = key_next;
3190         }
3191         hammer2_spin_unex(&parent->core.spin);
3192
3193         /*
3194          * Return the keybits for a higher-level FREEMAP_NODE covering
3195          * this node.
3196          */
3197         switch(keybits) {
3198         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3199                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3200                 break;
3201         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3202                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3203                 break;
3204         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3205                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3206                 break;
3207         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3208                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3209                 break;
3210         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3211                 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3212                 break;
3213         case HAMMER2_FREEMAP_LEVEL5_RADIX:
3214                 panic("hammer2_chain_indkey_freemap: level too high");
3215                 break;
3216         default:
3217                 panic("hammer2_chain_indkey_freemap: bad radix");
3218                 break;
3219         }
3220         *keyp = key;
3221
3222         return (keybits);
3223 }
3224
3225 /*
3226  * Calculate the keybits and highside/lowside of the indirect block the
3227  * caller is creating.
3228  */
3229 static int
3230 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3231                             int keybits, hammer2_blockref_t *base, int count)
3232 {
3233         hammer2_blockref_t *bref;
3234         hammer2_chain_t *chain;
3235         hammer2_key_t key_beg;
3236         hammer2_key_t key_end;
3237         hammer2_key_t key_next;
3238         hammer2_key_t key;
3239         int nkeybits;
3240         int locount;
3241         int hicount;
3242         int cache_index;
3243         int maxloops = 300000;
3244
3245         key = *keyp;
3246         locount = 0;
3247         hicount = 0;
3248
3249         /*
3250          * Calculate the range of keys in the array being careful to skip
3251          * slots which are overridden with a deletion.  Once the scan
3252          * completes we will cut the key range in half and shift half the
3253          * range into the new indirect block.
3254          */
3255         key_beg = 0;
3256         key_end = HAMMER2_KEY_MAX;
3257         cache_index = 0;
3258         hammer2_spin_ex(&parent->core.spin);
3259
3260         for (;;) {
3261                 if (--maxloops == 0) {
3262                         panic("indkey_freemap shit %p %p:%d\n",
3263                               parent, base, count);
3264                 }
3265                 chain = hammer2_combined_find(parent, base, count,
3266                                               &cache_index, &key_next,
3267                                               key_beg, key_end,
3268                                               &bref);
3269
3270                 /*
3271                  * Exhausted search
3272                  */
3273                 if (bref == NULL)
3274                         break;
3275
3276                 /*
3277                  * NOTE: No need to check DUPLICATED here because we do
3278                  *       not release the spinlock.
3279                  */
3280                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3281                         if (key_next == 0 || key_next > key_end)
3282                                 break;
3283                         key_beg = key_next;
3284                         continue;
3285                 }
3286
3287                 /*
3288                  * Use the full live (not deleted) element for the scan
3289                  * iteration.  HAMMER2 does not allow partial replacements.
3290                  *
3291                  * XXX should be built into hammer2_combined_find().
3292                  */
3293                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3294
3295                 /*
3296                  * Expand our calculated key range (key, keybits) to fit
3297                  * the scanned key.  nkeybits represents the full range
3298                  * that we will later cut in half (two halves @ nkeybits - 1).
3299                  */
3300                 nkeybits = keybits;
3301                 if (nkeybits < bref->keybits) {
3302                         if (bref->keybits > 64) {
3303                                 kprintf("bad bref chain %p bref %p\n",
3304                                         chain, bref);
3305                                 Debugger("fubar");
3306                         }
3307                         nkeybits = bref->keybits;
3308                 }
3309                 while (nkeybits < 64 &&
3310                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3311                         (key ^ bref->key)) != 0) {
3312                         ++nkeybits;
3313                 }
3314
3315                 /*
3316                  * If the new key range is larger we have to determine
3317                  * which side of the new key range the existing keys fall
3318                  * under by checking the high bit, then collapsing the
3319                  * locount into the hicount or vise-versa.
3320                  */
3321                 if (keybits != nkeybits) {
3322                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3323                                 hicount += locount;
3324                                 locount = 0;
3325                         } else {
3326                                 locount += hicount;
3327                                 hicount = 0;
3328                         }
3329                         keybits = nkeybits;
3330                 }
3331
3332                 /*
3333                  * The newly scanned key will be in the lower half or the
3334                  * upper half of the (new) key range.
3335                  */
3336                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3337                         ++hicount;
3338                 else
3339                         ++locount;
3340
3341                 if (key_next == 0)
3342                         break;
3343                 key_beg = key_next;
3344         }
3345         hammer2_spin_unex(&parent->core.spin);
3346         bref = NULL;    /* now invalid (safety) */
3347
3348         /*
3349          * Adjust keybits to represent half of the full range calculated
3350          * above (radix 63 max)
3351          */
3352         --keybits;
3353
3354         /*
3355          * Select whichever half contains the most elements.  Theoretically
3356          * we can select either side as long as it contains at least one
3357          * element (in order to ensure that a free slot is present to hold
3358          * the indirect block).
3359          */
3360         if (hammer2_indirect_optimize) {
3361                 /*
3362                  * Insert node for least number of keys, this will arrange
3363                  * the first few blocks of a large file or the first few
3364                  * inodes in a directory with fewer indirect blocks when
3365                  * created linearly.
3366                  */
3367                 if (hicount < locount && hicount != 0)
3368                         key |= (hammer2_key_t)1 << keybits;
3369                 else
3370                         key &= ~(hammer2_key_t)1 << keybits;
3371         } else {
3372                 /*
3373                  * Insert node for most number of keys, best for heavily
3374                  * fragmented files.
3375                  */
3376                 if (hicount > locount)
3377                         key |= (hammer2_key_t)1 << keybits;
3378                 else
3379                         key &= ~(hammer2_key_t)1 << keybits;
3380         }
3381         *keyp = key;
3382
3383         return (keybits);
3384 }
3385
3386 /*
3387  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3388  * it exists.
3389  *
3390  * Both parent and chain must be locked exclusively.
3391  *
3392  * This function will modify the parent if the blockref requires removal
3393  * from the parent's block table.
3394  *
3395  * This function is NOT recursive.  Any entity already pushed into the
3396  * chain (such as an inode) may still need visibility into its contents,
3397  * as well as the ability to read and modify the contents.  For example,
3398  * for an unlinked file which is still open.
3399  */
3400 void
3401 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
3402                      hammer2_tid_t mtid, int flags)
3403 {
3404         KKASSERT(hammer2_mtx_owned(&chain->lock));
3405
3406         /*
3407          * Nothing to do if already marked.
3408          *
3409          * We need the spinlock on the core whos RBTREE contains chain
3410          * to protect against races.
3411          */
3412         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3413                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3414                          chain->parent == parent);
3415                 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
3416         }
3417
3418         /*
3419          * To avoid losing track of a permanent deletion we add the chain
3420          * to the delayed flush queue.  If were to flush it right now the
3421          * parent would end up in a modified state and generate I/O.
3422          * The delayed queue gives the parent a chance to be deleted to
3423          * (e.g. rm -rf).
3424          */
3425         if (flags & HAMMER2_DELETE_PERMANENT) {
3426                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3427                 hammer2_delayed_flush(chain);
3428         } else {
3429                 /* XXX might not be needed */
3430                 hammer2_chain_setflush(chain);
3431         }
3432 }
3433
3434 /*
3435  * Returns the index of the nearest element in the blockref array >= elm.
3436  * Returns (count) if no element could be found.
3437  *
3438  * Sets *key_nextp to the next key for loop purposes but does not modify
3439  * it if the next key would be higher than the current value of *key_nextp.
3440  * Note that *key_nexp can overflow to 0, which should be tested by the
3441  * caller.
3442  *
3443  * (*cache_indexp) is a heuristic and can be any value without effecting
3444  * the result.
3445  *
3446  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3447  *           held through the operation.
3448  */
3449 static int
3450 hammer2_base_find(hammer2_chain_t *parent,
3451                   hammer2_blockref_t *base, int count,
3452                   int *cache_indexp, hammer2_key_t *key_nextp,
3453                   hammer2_key_t key_beg, hammer2_key_t key_end)
3454 {
3455         hammer2_blockref_t *scan;
3456         hammer2_key_t scan_end;
3457         int i;
3458         int limit;
3459
3460         /*
3461          * Require the live chain's already have their core's counted
3462          * so we can optimize operations.
3463          */
3464         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
3465
3466         /*
3467          * Degenerate case
3468          */
3469         if (count == 0 || base == NULL)
3470                 return(count);
3471
3472         /*
3473          * Sequential optimization using *cache_indexp.  This is the most
3474          * likely scenario.
3475          *
3476          * We can avoid trailing empty entries on live chains, otherwise
3477          * we might have to check the whole block array.
3478          */
3479         i = *cache_indexp;
3480         cpu_ccfence();
3481         limit = parent->core.live_zero;
3482         if (i >= limit)
3483                 i = limit - 1;
3484         if (i < 0)
3485                 i = 0;
3486         KKASSERT(i < count);
3487
3488         /*
3489          * Search backwards
3490          */
3491         scan = &base[i];
3492         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3493                 --scan;
3494                 --i;
3495         }
3496         *cache_indexp = i;
3497
3498         /*
3499          * Search forwards, stop when we find a scan element which
3500          * encloses the key or until we know that there are no further
3501          * elements.
3502          */
3503         while (i < count) {
3504                 if (scan->type != 0) {
3505                         scan_end = scan->key +
3506                                    ((hammer2_key_t)1 << scan->keybits) - 1;
3507                         if (scan->key > key_beg || scan_end >= key_beg)
3508                                 break;
3509                 }
3510                 if (i >= limit)
3511                         return (count);
3512                 ++scan;
3513                 ++i;
3514         }
3515         if (i != count) {
3516                 *cache_indexp = i;
3517                 if (i >= limit) {
3518                         i = count;
3519                 } else {
3520                         scan_end = scan->key +
3521                                    ((hammer2_key_t)1 << scan->keybits);
3522                         if (scan_end && (*key_nextp > scan_end ||
3523                                          *key_nextp == 0)) {
3524                                 *key_nextp = scan_end;
3525                         }
3526                 }
3527         }
3528         return (i);
3529 }
3530
3531 /*
3532  * Do a combined search and return the next match either from the blockref
3533  * array or from the in-memory chain.  Sets *bresp to the returned bref in
3534  * both cases, or sets it to NULL if the search exhausted.  Only returns
3535  * a non-NULL chain if the search matched from the in-memory chain.
3536  *
3537  * When no in-memory chain has been found and a non-NULL bref is returned
3538  * in *bresp.
3539  *
3540  *
3541  * The returned chain is not locked or referenced.  Use the returned bref
3542  * to determine if the search exhausted or not.  Iterate if the base find
3543  * is chosen but matches a deleted chain.
3544  *
3545  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
3546  *           held through the operation.
3547  */
3548 static hammer2_chain_t *
3549 hammer2_combined_find(hammer2_chain_t *parent,
3550                       hammer2_blockref_t *base, int count,
3551                       int *cache_indexp, hammer2_key_t *key_nextp,
3552                       hammer2_key_t key_beg, hammer2_key_t key_end,
3553                       hammer2_blockref_t **bresp)
3554 {
3555         hammer2_blockref_t *bref;
3556         hammer2_chain_t *chain;
3557         int i;
3558
3559         /*
3560          * Lookup in block array and in rbtree.
3561          */
3562         *key_nextp = key_end + 1;
3563         i = hammer2_base_find(parent, base, count, cache_indexp,
3564                               key_nextp, key_beg, key_end);
3565         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3566
3567         /*
3568          * Neither matched
3569          */
3570         if (i == count && chain == NULL) {
3571                 *bresp = NULL;
3572                 return(NULL);
3573         }
3574
3575         /*
3576          * Only chain matched.
3577          */
3578         if (i == count) {
3579                 bref = &chain->bref;
3580                 goto found;
3581         }
3582
3583         /*
3584          * Only blockref matched.
3585          */
3586         if (chain == NULL) {
3587                 bref = &base[i];
3588                 goto found;
3589         }
3590
3591         /*
3592          * Both in-memory and blockref matched, select the nearer element.
3593          *
3594          * If both are flush with the left-hand side or both are the
3595          * same distance away, select the chain.  In this situation the
3596          * chain must have been loaded from the matching blockmap.
3597          */
3598         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3599             chain->bref.key == base[i].key) {
3600                 KKASSERT(chain->bref.key == base[i].key);
3601                 bref = &chain->bref;
3602                 goto found;
3603         }
3604
3605         /*
3606          * Select the nearer key
3607          */
3608         if (chain->bref.key < base[i].key) {
3609                 bref = &chain->bref;
3610         } else {
3611                 bref = &base[i];
3612                 chain = NULL;
3613         }
3614
3615         /*
3616          * If the bref is out of bounds we've exhausted our search.
3617          */
3618 found:
3619         if (bref->key > key_end) {
3620                 *bresp = NULL;
3621                 chain = NULL;
3622         } else {
3623                 *bresp = bref;
3624         }
3625         return(chain);
3626 }
3627
3628 /*
3629  * Locate the specified block array element and delete it.  The element
3630  * must exist.
3631  *
3632  * The spin lock on the related chain must be held.
3633  *
3634  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3635  *       need to be adjusted when we commit the media change.
3636  */
3637 void
3638 hammer2_base_delete(hammer2_chain_t *parent,
3639                     hammer2_blockref_t *base, int count,
3640                     int *cache_indexp, hammer2_chain_t *chain)
3641 {
3642         hammer2_blockref_t *elm = &chain->bref;
3643         hammer2_key_t key_next;
3644         int i;
3645
3646         /*
3647          * Delete element.  Expect the element to exist.
3648          *
3649          * XXX see caller, flush code not yet sophisticated enough to prevent
3650          *     re-flushed in some cases.
3651          */
3652         key_next = 0; /* max range */
3653         i = hammer2_base_find(parent, base, count, cache_indexp,
3654                               &key_next, elm->key, elm->key);
3655         if (i == count || base[i].type == 0 ||
3656             base[i].key != elm->key ||
3657             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3658              base[i].keybits != elm->keybits)) {
3659                 hammer2_spin_unex(&parent->core.spin);
3660                 panic("delete base %p element not found at %d/%d elm %p\n",
3661                       base, i, count, elm);
3662                 return;
3663         }
3664
3665         /*
3666          * Update stats and zero the entry
3667          */
3668         parent->bref.data_count -= base[i].data_count;
3669         parent->bref.data_count -= (hammer2_off_t)1 <<
3670                         (int)(base[i].data_off & HAMMER2_OFF_MASK_RADIX);
3671         parent->bref.inode_count -= base[i].inode_count;
3672         if (base[i].type == HAMMER2_BREF_TYPE_INODE)
3673                 parent->bref.inode_count -= 1;
3674
3675         bzero(&base[i], sizeof(*base));
3676
3677         /*
3678          * We can only optimize parent->core.live_zero for live chains.
3679          */
3680         if (parent->core.live_zero == i + 1) {
3681                 while (--i >= 0 && base[i].type == 0)
3682                         ;
3683                 parent->core.live_zero = i + 1;
3684         }
3685
3686         /*
3687          * Clear appropriate blockmap flags in chain.
3688          */
3689         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3690                                         HAMMER2_CHAIN_BMAPUPD);
3691 }
3692
3693 /*
3694  * Insert the specified element.  The block array must not already have the
3695  * element and must have space available for the insertion.
3696  *
3697  * The spin lock on the related chain must be held.
3698  *
3699  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3700  *       need to be adjusted when we commit the media change.
3701  */
3702 void
3703 hammer2_base_insert(hammer2_chain_t *parent,
3704                     hammer2_blockref_t *base, int count,
3705                     int *cache_indexp, hammer2_chain_t *chain)
3706 {
3707         hammer2_blockref_t *elm = &chain->bref;
3708         hammer2_key_t key_next;
3709         hammer2_key_t xkey;
3710         int i;
3711         int j;
3712         int k;
3713         int l;
3714         int u = 1;
3715
3716         /*
3717          * Insert new element.  Expect the element to not already exist
3718          * unless we are replacing it.
3719          *
3720          * XXX see caller, flush code not yet sophisticated enough to prevent
3721          *     re-flushed in some cases.
3722          */
3723         key_next = 0; /* max range */
3724         i = hammer2_base_find(parent, base, count, cache_indexp,
3725                               &key_next, elm->key, elm->key);
3726
3727         /*
3728          * Shortcut fill optimization, typical ordered insertion(s) may not
3729          * require a search.
3730          */
3731         KKASSERT(i >= 0 && i <= count);
3732
3733         /*
3734          * Set appropriate blockmap flags in chain.
3735          */
3736         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3737
3738         /*
3739          * Update stats and zero the entry
3740          */
3741         parent->bref.data_count += elm->data_count;
3742         parent->bref.data_count += (hammer2_off_t)1 <<
3743                         (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
3744         parent->bref.inode_count += elm->inode_count;
3745         if (elm->type == HAMMER2_BREF_TYPE_INODE)
3746                 parent->bref.inode_count += 1;
3747
3748
3749         /*
3750          * We can only optimize parent->core.live_zero for live chains.
3751          */
3752         if (i == count && parent->core.live_zero < count) {
3753                 i = parent->core.live_zero++;
3754                 base[i] = *elm;
3755                 return;
3756         }
3757
3758         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3759         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3760                 hammer2_spin_unex(&parent->core.spin);
3761                 panic("insert base %p overlapping elements at %d elm %p\n",
3762                       base, i, elm);
3763         }
3764
3765         /*
3766          * Try to find an empty slot before or after.
3767          */
3768         j = i;
3769         k = i;
3770         while (j > 0 || k < count) {
3771                 --j;
3772                 if (j >= 0 && base[j].type == 0) {
3773                         if (j == i - 1) {
3774                                 base[j] = *elm;
3775                         } else {
3776                                 bcopy(&base[j+1], &base[j],
3777                                       (i - j - 1) * sizeof(*base));
3778                                 base[i - 1] = *elm;
3779                         }
3780                         goto validate;
3781                 }
3782                 ++k;
3783                 if (k < count && base[k].type == 0) {
3784                         bcopy(&base[i], &base[i+1],
3785                               (k - i) * sizeof(hammer2_blockref_t));
3786                         base[i] = *elm;
3787
3788                         /*
3789                          * We can only update parent->core.live_zero for live
3790                          * chains.
3791                          */
3792                         if (parent->core.live_zero <= k)
3793                                 parent->core.live_zero = k + 1;
3794                         u = 2;
3795                         goto validate;
3796                 }
3797         }
3798         panic("hammer2_base_insert: no room!");
3799
3800         /*
3801          * Debugging
3802          */
3803 validate:
3804         key_next = 0;
3805         for (l = 0; l < count; ++l) {
3806                 if (base[l].type) {
3807                         key_next = base[l].key +
3808                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3809                         break;
3810                 }
3811         }
3812         while (++l < count) {
3813                 if (base[l].type) {
3814                         if (base[l].key <= key_next)
3815                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3816                         key_next = base[l].key +
3817                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3818
3819                 }
3820         }
3821
3822 }
3823
3824 #if 0
3825
3826 /*
3827  * Sort the blockref array for the chain.  Used by the flush code to
3828  * sort the blockref[] array.
3829  *
3830  * The chain must be exclusively locked AND spin-locked.
3831  */
3832 typedef hammer2_blockref_t *hammer2_blockref_p;
3833
3834 static
3835 int
3836 hammer2_base_sort_callback(const void *v1, const void *v2)
3837 {
3838         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3839         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3840
3841         /*
3842          * Make sure empty elements are placed at the end of the array
3843          */
3844         if (bref1->type == 0) {
3845                 if (bref2->type == 0)
3846                         return(0);
3847                 return(1);
3848         } else if (bref2->type == 0) {
3849                 return(-1);
3850         }
3851
3852         /*
3853          * Sort by key
3854          */
3855         if (bref1->key < bref2->key)
3856                 return(-1);
3857         if (bref1->key > bref2->key)
3858                 return(1);
3859         return(0);
3860 }
3861
3862 void
3863 hammer2_base_sort(hammer2_chain_t *chain)
3864 {
3865         hammer2_blockref_t *base;
3866         int count;
3867
3868         switch(chain->bref.type) {
3869         case HAMMER2_BREF_TYPE_INODE:
3870                 /*
3871                  * Special shortcut for embedded data returns the inode
3872                  * itself.  Callers must detect this condition and access
3873                  * the embedded data (the strategy code does this for us).
3874                  *
3875                  * This is only applicable to regular files and softlinks.
3876                  */
3877                 if (chain->data->ipdata.meta.op_flags &
3878                     HAMMER2_OPFLAG_DIRECTDATA) {
3879                         return;
3880                 }
3881                 base = &chain->data->ipdata.u.blockset.blockref[0];
3882                 count = HAMMER2_SET_COUNT;
3883                 break;
3884         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3885         case HAMMER2_BREF_TYPE_INDIRECT:
3886                 /*
3887                  * Optimize indirect blocks in the INITIAL state to avoid
3888                  * I/O.
3889                  */
3890                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3891                 base = &chain->data->npdata[0];
3892                 count = chain->bytes / sizeof(hammer2_blockref_t);
3893                 break;
3894         case HAMMER2_BREF_TYPE_VOLUME:
3895                 base = &chain->data->voldata.sroot_blockset.blockref[0];
3896                 count = HAMMER2_SET_COUNT;
3897                 break;
3898         case HAMMER2_BREF_TYPE_FREEMAP:
3899                 base = &chain->data->blkset.blockref[0];
3900                 count = HAMMER2_SET_COUNT;
3901                 break;
3902         default:
3903                 kprintf("hammer2_chain_lookup: unrecognized "
3904                         "blockref(A) type: %d",
3905                         chain->bref.type);
3906                 while (1)
3907                         tsleep(&base, 0, "dead", 0);
3908                 panic("hammer2_chain_lookup: unrecognized "
3909                       "blockref(A) type: %d",
3910                       chain->bref.type);
3911                 base = NULL;    /* safety */
3912                 count = 0;      /* safety */
3913         }
3914         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3915 }
3916
3917 #endif
3918
3919 /*
3920  * Chain memory management
3921  */
3922 void
3923 hammer2_chain_wait(hammer2_chain_t *chain)
3924 {
3925         tsleep(chain, 0, "chnflw", 1);
3926 }
3927
3928 const hammer2_media_data_t *
3929 hammer2_chain_rdata(hammer2_chain_t *chain)
3930 {
3931         KKASSERT(chain->data != NULL);
3932         return (chain->data);
3933 }
3934
3935 hammer2_media_data_t *
3936 hammer2_chain_wdata(hammer2_chain_t *chain)
3937 {
3938         KKASSERT(chain->data != NULL);
3939         return (chain->data);
3940 }
3941
3942 /*
3943  * Set the check data for a chain.  This can be a heavy-weight operation
3944  * and typically only runs on-flush.  For file data check data is calculated
3945  * when the logical buffers are flushed.
3946  */
3947 void
3948 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
3949 {
3950         chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
3951
3952         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
3953         case HAMMER2_CHECK_NONE:
3954                 break;
3955         case HAMMER2_CHECK_DISABLED:
3956                 break;
3957         case HAMMER2_CHECK_ISCSI32:
3958                 chain->bref.check.iscsi32.value =
3959                         hammer2_icrc32(bdata, chain->bytes);
3960                 break;
3961         case HAMMER2_CHECK_CRC64:
3962                 chain->bref.check.crc64.value = 0;
3963                 /* XXX */
3964                 break;
3965         case HAMMER2_CHECK_SHA192:
3966                 {
3967                         SHA256_CTX hash_ctx;
3968                         union {
3969                                 uint8_t digest[SHA256_DIGEST_LENGTH];
3970                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
3971                         } u;
3972
3973                         SHA256_Init(&hash_ctx);
3974                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
3975                         SHA256_Final(u.digest, &hash_ctx);
3976                         u.digest64[2] ^= u.digest64[3];
3977                         bcopy(u.digest,
3978                               chain->bref.check.sha192.data,
3979                               sizeof(chain->bref.check.sha192.data));
3980                 }
3981                 break;
3982         case HAMMER2_CHECK_FREEMAP:
3983                 chain->bref.check.freemap.icrc32 =
3984                         hammer2_icrc32(bdata, chain->bytes);
3985                 break;
3986         default:
3987                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
3988                         chain->bref.methods);
3989                 break;
3990         }
3991 }
3992
3993 int
3994 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
3995 {
3996         int r;
3997
3998         if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
3999                 return 1;
4000
4001         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4002         case HAMMER2_CHECK_NONE:
4003                 r = 1;
4004                 break;
4005         case HAMMER2_CHECK_DISABLED:
4006                 r = 1;
4007                 break;
4008         case HAMMER2_CHECK_ISCSI32:
4009                 r = (chain->bref.check.iscsi32.value ==
4010                      hammer2_icrc32(bdata, chain->bytes));
4011                 break;
4012         case HAMMER2_CHECK_CRC64:
4013                 r = (chain->bref.check.crc64.value == 0);
4014                 /* XXX */
4015                 break;
4016         case HAMMER2_CHECK_SHA192:
4017                 {
4018                         SHA256_CTX hash_ctx;
4019                         union {
4020                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4021                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4022                         } u;
4023
4024                         SHA256_Init(&hash_ctx);
4025                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4026                         SHA256_Final(u.digest, &hash_ctx);
4027                         u.digest64[2] ^= u.digest64[3];
4028                         if (bcmp(u.digest,
4029                                  chain->bref.check.sha192.data,
4030                                  sizeof(chain->bref.check.sha192.data)) == 0) {
4031                                 r = 1;
4032                         } else {
4033                                 r = 0;
4034                         }
4035                 }
4036                 break;
4037         case HAMMER2_CHECK_FREEMAP:
4038                 r = (chain->bref.check.freemap.icrc32 ==
4039                      hammer2_icrc32(bdata, chain->bytes));
4040                 if (r == 0) {
4041                         kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
4042                                 chain->bref.check.freemap.icrc32,
4043                                 hammer2_icrc32(bdata, chain->bytes), chain->bytes);
4044                         if (chain->dio)
4045                                 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
4046                                         chain->dio, chain->dio->bp->b_loffset, chain->dio->bp->b_bufsize, bdata, chain->dio->bp->b_data);
4047                 }
4048
4049                 break;
4050         default:
4051                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4052                         chain->bref.methods);
4053                 r = 1;
4054                 break;
4055         }
4056         return r;
4057 }
4058
4059 /*
4060  * The caller presents a shared-locked (parent, chain) where the chain
4061  * is of type HAMMER2_OBJTYPE_HARDLINK.  The caller must hold the ip
4062  * structure representing the inode locked to prevent
4063  * consolidation/deconsolidation races.
4064  *
4065  * We locate the hardlink in the current or a common parent directory.
4066  *
4067  * If we are unable to locate the hardlink, EIO is returned and
4068  * (*chainp) is unlocked and dropped.
4069  */
4070 int
4071 hammer2_chain_hardlink_find(hammer2_inode_t *dip,
4072                         hammer2_chain_t **parentp,
4073                         hammer2_chain_t **chainp,
4074                         int flags)
4075 {
4076         hammer2_chain_t *parent;
4077         hammer2_chain_t *rchain;
4078         hammer2_key_t key_dummy;
4079         hammer2_key_t lhc;
4080         int cache_index = -1;
4081
4082         /*
4083          * Obtain the key for the hardlink from *chainp.
4084          */
4085         rchain = *chainp;
4086         lhc = rchain->data->ipdata.meta.inum;
4087         hammer2_chain_unlock(rchain);
4088         hammer2_chain_drop(rchain);
4089         rchain = NULL;
4090
4091         for (;;) {
4092                 int nloops;
4093                 rchain = hammer2_chain_lookup(parentp, &key_dummy,
4094                                               lhc, lhc,
4095                                               &cache_index, flags);
4096                 if (rchain)
4097                         break;
4098
4099                 /*
4100                  * Iterate parents, handle parent rename races by retrying
4101                  * the operation.
4102                  */
4103                 nloops = -1;
4104                 while (nloops) {
4105                         --nloops;
4106                         parent = *parentp;
4107                         if (nloops < 0 &&
4108                             parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4109                                 nloops = 1;
4110                         }
4111                         if (parent->bref.flags & HAMMER2_BREF_FLAG_PFSROOT)
4112                                 goto done;
4113                         if (parent->parent == NULL)
4114                                 goto done;
4115                         parent = parent->parent;
4116                         hammer2_chain_ref(parent);
4117                         hammer2_chain_unlock(*parentp);
4118                         hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
4119                                                    flags);
4120                         if ((*parentp)->parent == parent) {
4121                                 hammer2_chain_drop(*parentp);
4122                                 *parentp = parent;
4123                         } else {
4124                                 hammer2_chain_unlock(parent);
4125                                 hammer2_chain_drop(parent);
4126                                 hammer2_chain_lock(*parentp,
4127                                                    HAMMER2_RESOLVE_ALWAYS |
4128                                                    flags);
4129                                 parent = NULL;  /* safety */
4130                                 /* retry */
4131                         }
4132                 }
4133         }
4134 done:
4135
4136         *chainp = rchain;
4137         return (rchain ? EINVAL : 0);
4138 }
4139
4140 /*
4141  * Used by the bulkscan code to snapshot the synchronized storage for
4142  * a volume, allowing it to be scanned concurrently against normal
4143  * operation.
4144  */
4145 hammer2_chain_t *
4146 hammer2_chain_bulksnap(hammer2_chain_t *chain)
4147 {
4148         hammer2_chain_t *copy;
4149
4150         copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
4151         switch(chain->bref.type) {
4152         case HAMMER2_BREF_TYPE_VOLUME:
4153                 copy->data = kmalloc(sizeof(copy->data->voldata),
4154                                      chain->hmp->mchain,
4155                                      M_WAITOK | M_ZERO);
4156                 hammer2_spin_ex(&chain->core.spin);
4157                 copy->data->voldata = chain->data->voldata;
4158                 hammer2_spin_unex(&chain->core.spin);
4159                 break;
4160         case HAMMER2_BREF_TYPE_FREEMAP:
4161                 copy->data = kmalloc(sizeof(hammer2_blockset_t),
4162                                      chain->hmp->mchain,
4163                                      M_WAITOK | M_ZERO);
4164                 hammer2_spin_ex(&chain->core.spin);
4165                 copy->data->blkset = chain->data->blkset;
4166                 hammer2_spin_unex(&chain->core.spin);
4167                 break;
4168         default:
4169                 break;
4170         }
4171         return copy;
4172 }
4173
4174 void
4175 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
4176 {
4177         switch(copy->bref.type) {
4178         case HAMMER2_BREF_TYPE_VOLUME:
4179         case HAMMER2_BREF_TYPE_FREEMAP:
4180                 KKASSERT(copy->data);
4181                 kfree(copy->data, copy->hmp->mchain);
4182                 copy->data = NULL;
4183         default:
4184                 break;
4185         }
4186         hammer2_chain_drop(copy);
4187 }
4188
4189 /*
4190  * Create a snapshot of the specified {parent, ochain} with the specified
4191  * label.  The originating hammer2_inode must be exclusively locked for
4192  * safety.
4193  *
4194  * The ioctl code has already synced the filesystem.
4195  */
4196 int
4197 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
4198                        hammer2_tid_t mtid)
4199 {
4200         hammer2_dev_t *hmp;
4201         const hammer2_inode_data_t *ripdata;
4202         hammer2_inode_data_t *wipdata;
4203         hammer2_chain_t *nchain;
4204         hammer2_inode_t *nip;
4205         size_t name_len;
4206         hammer2_key_t lhc;
4207         struct vattr vat;
4208 #if 0
4209         uuid_t opfs_clid;
4210 #endif
4211         int error;
4212
4213         kprintf("snapshot %s\n", pmp->name);
4214
4215         name_len = strlen(pmp->name);
4216         lhc = hammer2_dirhash(pmp->name, name_len);
4217
4218         /*
4219          * Get the clid
4220          */
4221         ripdata = &chain->data->ipdata;
4222 #if 0
4223         opfs_clid = ripdata->meta.pfs_clid;
4224 #endif
4225         hmp = chain->hmp;
4226
4227         /*
4228          * Create the snapshot directory under the super-root
4229          *
4230          * Set PFS type, generate a unique filesystem id, and generate
4231          * a cluster id.  Use the same clid when snapshotting a PFS root,
4232          * which theoretically allows the snapshot to be used as part of
4233          * the same cluster (perhaps as a cache).
4234          *
4235          * Copy the (flushed) blockref array.  Theoretically we could use
4236          * chain_duplicate() but it becomes difficult to disentangle
4237          * the shared core so for now just brute-force it.
4238          */
4239         VATTR_NULL(&vat);
4240         vat.va_type = VDIR;
4241         vat.va_mode = 0755;
4242         nip = hammer2_inode_create(hmp->spmp->iroot, &vat, proc0.p_ucred,
4243                                    pmp->name, name_len, 0,
4244                                    1, 0, 0,
4245                                    HAMMER2_INSERT_PFSROOT, &error);
4246
4247         if (nip) {
4248                 hammer2_inode_modify(nip);
4249                 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
4250                 hammer2_chain_modify(nchain, mtid, 0);
4251                 wipdata = &nchain->data->ipdata;
4252
4253                 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
4254                 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
4255                 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
4256                 kern_uuidgen(&nip->meta.pfs_fsid, 1);
4257
4258                 /*
4259                  * Give the snapshot its own private cluster id.  As a
4260                  * snapshot no further synchronization with the original
4261                  * cluster will be done.
4262                  */
4263 #if 0
4264                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
4265                         nip->meta.pfs_clid = opfs_clid;
4266                 else
4267                         kern_uuidgen(&nip->meta.pfs_clid, 1);
4268 #endif
4269                 kern_uuidgen(&nip->meta.pfs_clid, 1);
4270                 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
4271
4272                 /* XXX hack blockset copy */
4273                 /* XXX doesn't work with real cluster */
4274                 wipdata->meta = nip->meta;
4275                 wipdata->u.blockset = ripdata->u.blockset;
4276                 hammer2_flush(nchain, mtid, 1);
4277                 hammer2_chain_unlock(nchain);
4278                 hammer2_chain_drop(nchain);
4279                 hammer2_inode_unlock(nip);
4280         }
4281         return (error);
4282 }