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