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