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