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