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