hammer2 - Initial HARDLINK -> DIRENT replacement code
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2015 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 hammer2_chain_t *hammer2_chain_create_indirect(
68                 hammer2_chain_t *parent,
69                 hammer2_key_t key, int keybits,
70                 hammer2_tid_t mtid, int for_type, int *errorp);
71 static hammer2_io_t *hammer2_chain_drop_data(hammer2_chain_t *chain,
72                 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 extern int h2timer[32];
91 extern int h2last;
92 extern int h2lid;
93
94 #define TIMER(which)    do {                            \
95         if (h2last)                                     \
96                 h2timer[h2lid] += (int)(ticks - h2last);\
97         h2last = ticks;                                 \
98         h2lid = which;                                  \
99 } while(0)
100
101 int
102 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
103 {
104         hammer2_key_t c1_beg;
105         hammer2_key_t c1_end;
106         hammer2_key_t c2_beg;
107         hammer2_key_t c2_end;
108
109         /*
110          * Compare chains.  Overlaps are not supposed to happen and catch
111          * any software issues early we count overlaps as a match.
112          */
113         c1_beg = chain1->bref.key;
114         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
115         c2_beg = chain2->bref.key;
116         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
117
118         if (c1_end < c2_beg)    /* fully to the left */
119                 return(-1);
120         if (c1_beg > c2_end)    /* fully to the right */
121                 return(1);
122         return(0);              /* overlap (must not cross edge boundary) */
123 }
124
125 /*
126  * Make a chain visible to the flusher.  The flusher needs to be able to
127  * do flushes of subdirectory chains or single files so it does a top-down
128  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
129  * or UPDATE chains and flushes back up the chain to the volume root.
130  *
131  * This routine sets ONFLUSH upward until it hits the volume root.  For
132  * simplicity we ignore PFSROOT boundaries whos rules can be complex.
133  * Extra ONFLUSH flagging doesn't hurt the filesystem.
134  */
135 void
136 hammer2_chain_setflush(hammer2_chain_t *chain)
137 {
138         hammer2_chain_t *parent;
139
140         if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
141                 hammer2_spin_sh(&chain->core.spin);
142                 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
143                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
144                         if ((parent = chain->parent) == NULL)
145                                 break;
146                         hammer2_spin_sh(&parent->core.spin);
147                         hammer2_spin_unsh(&chain->core.spin);
148                         chain = parent;
149                 }
150                 hammer2_spin_unsh(&chain->core.spin);
151         }
152 }
153
154 /*
155  * Allocate a new disconnected chain element representing the specified
156  * bref.  chain->refs is set to 1 and the passed bref is copied to
157  * chain->bref.  chain->bytes is derived from the bref.
158  *
159  * chain->pmp inherits pmp unless the chain is an inode (other than the
160  * super-root inode).
161  *
162  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
163  */
164 hammer2_chain_t *
165 hammer2_chain_alloc(hammer2_dev_t *hmp, hammer2_pfs_t *pmp,
166                     hammer2_blockref_t *bref)
167 {
168         hammer2_chain_t *chain;
169         u_int bytes;
170
171         /*
172          * Special case - radix of 0 indicates a chain that does not
173          * need a data reference (context is completely embedded in the
174          * bref).
175          */
176         if ((int)(bref->data_off & HAMMER2_OFF_MASK_RADIX))
177                 bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
178         else
179                 bytes = 0;
180
181         atomic_add_long(&hammer2_chain_allocs, 1);
182
183         /*
184          * Construct the appropriate system structure.
185          */
186         switch(bref->type) {
187         case HAMMER2_BREF_TYPE_DIRENT:
188         case HAMMER2_BREF_TYPE_INODE:
189         case HAMMER2_BREF_TYPE_INDIRECT:
190         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
191         case HAMMER2_BREF_TYPE_DATA:
192         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
193                 /*
194                  * Chain's are really only associated with the hmp but we
195                  * maintain a pmp association for per-mount memory tracking
196                  * purposes.  The pmp can be NULL.
197                  */
198                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
199                 break;
200         case HAMMER2_BREF_TYPE_VOLUME:
201         case HAMMER2_BREF_TYPE_FREEMAP:
202                 /*
203                  * Only hammer2_chain_bulksnap() calls this function with these
204                  * types.
205                  */
206                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
207                 break;
208         default:
209                 chain = NULL;
210                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
211                       bref->type);
212         }
213
214         /*
215          * Initialize the new chain structure.  pmp must be set to NULL for
216          * chains belonging to the super-root topology of a device mount.
217          */
218         if (pmp == hmp->spmp)
219                 chain->pmp = NULL;
220         else
221                 chain->pmp = pmp;
222         chain->hmp = hmp;
223         chain->bref = *bref;
224         chain->bytes = bytes;
225         chain->refs = 1;
226         chain->flags = HAMMER2_CHAIN_ALLOCATED;
227
228         /*
229          * Set the PFS boundary flag if this chain represents a PFS root.
230          */
231         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
232                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_PFSBOUNDARY);
233         hammer2_chain_core_init(chain);
234
235         return (chain);
236 }
237
238 /*
239  * Initialize a chain's core structure.  This structure used to be allocated
240  * but is now embedded.
241  *
242  * The core is not locked.  No additional refs on the chain are made.
243  * (trans) must not be NULL if (core) is not NULL.
244  */
245 void
246 hammer2_chain_core_init(hammer2_chain_t *chain)
247 {
248         /*
249          * Fresh core under nchain (no multi-homing of ochain's
250          * sub-tree).
251          */
252         RB_INIT(&chain->core.rbtree);   /* live chains */
253         hammer2_mtx_init(&chain->lock, "h2chain");
254 }
255
256 /*
257  * Add a reference to a chain element, preventing its destruction.
258  *
259  * (can be called with spinlock held)
260  */
261 void
262 hammer2_chain_ref(hammer2_chain_t *chain)
263 {
264         if (atomic_fetchadd_int(&chain->refs, 1) == 0) {
265                 /*
266                  * 0->non-zero transition must ensure that chain is removed
267                  * from the LRU list.
268                  *
269                  * NOTE: Already holding lru_spin here so we cannot call
270                  *       hammer2_chain_ref() to get it off lru_list, do
271                  *       it manually.
272                  */
273                 if (chain->flags & HAMMER2_CHAIN_ONLRU) {
274                         hammer2_pfs_t *pmp = chain->pmp;
275                         hammer2_spin_ex(&pmp->lru_spin);
276                         if (chain->flags & HAMMER2_CHAIN_ONLRU) {
277                                 atomic_add_int(&pmp->lru_count, -1);
278                                 atomic_clear_int(&chain->flags,
279                                                  HAMMER2_CHAIN_ONLRU);
280                                 TAILQ_REMOVE(&pmp->lru_list, chain, lru_node);
281                         }
282                         hammer2_spin_unex(&pmp->lru_spin);
283                 }
284         }
285 #if 0
286         kprintf("REFC %p %d %08x\n", chain, chain->refs - 1, chain->flags);
287         print_backtrace(8);
288 #endif
289 }
290
291 /*
292  * Ref a locked chain and force the data to be held across an unlock.
293  * Chain must be currently locked.  The user of the chain who desires
294  * to release the hold must call hammer2_chain_lock_unhold() to lock
295  * and unhold the chain, then unlock normally, or may simply call
296  * hammer2_chain_drop_unhold() (which is safer against deadlocks).
297  */
298 void
299 hammer2_chain_ref_hold(hammer2_chain_t *chain)
300 {
301         atomic_add_int(&chain->persist_refs, 1);
302         hammer2_chain_ref(chain);
303 }
304
305 /*
306  * Insert the chain in the core rbtree.
307  *
308  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
309  * chain is a special case used by the flush code that is placed on the
310  * unstaged deleted list to avoid confusing the live view.
311  */
312 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
313 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
314 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
315
316 static
317 int
318 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
319                      int flags, int generation)
320 {
321         hammer2_chain_t *xchain;
322         int error = 0;
323
324         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
325                 hammer2_spin_ex(&parent->core.spin);
326
327         /*
328          * Interlocked by spinlock, check for race
329          */
330         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
331             parent->core.generation != generation) {
332                 error = EAGAIN;
333                 goto failed;
334         }
335
336         /*
337          * Insert chain
338          */
339         xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
340         KASSERT(xchain == NULL,
341                 ("hammer2_chain_insert: collision %p %p (key=%016jx)",
342                 chain, xchain, chain->bref.key));
343         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
344         chain->parent = parent;
345         ++parent->core.chain_count;
346         ++parent->core.generation;      /* XXX incs for _get() too, XXX */
347
348         /*
349          * We have to keep track of the effective live-view blockref count
350          * so the create code knows when to push an indirect block.
351          */
352         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
353                 atomic_add_int(&parent->core.live_count, 1);
354 failed:
355         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
356                 hammer2_spin_unex(&parent->core.spin);
357         return error;
358 }
359
360 /*
361  * Drop the caller's reference to the chain.  When the ref count drops to
362  * zero this function will try to disassociate the chain from its parent and
363  * deallocate it, then recursely drop the parent using the implied ref
364  * from the chain's chain->parent.
365  */
366 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
367
368 void
369 hammer2_chain_drop(hammer2_chain_t *chain)
370 {
371         u_int refs;
372
373         if (hammer2_debug & 0x200000)
374                 Debugger("drop");
375 #if 0
376         kprintf("DROP %p %d %08x\n", chain, chain->refs - 1, chain->flags);
377         print_backtrace(8);
378 #endif
379
380         KKASSERT(chain->refs > 0);
381
382         while (chain) {
383                 refs = chain->refs;
384                 cpu_ccfence();
385                 KKASSERT(refs > 0);
386
387                 if (refs == 1) {
388                         chain = hammer2_chain_lastdrop(chain);
389                 } else {
390                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
391                                 break;
392                         /* retry the same chain */
393                 }
394         }
395 }
396
397 /*
398  * Unhold a held and probably not-locked chain.  To ensure that the data
399  * is properly dropped we check lockcnt.  If lockcnt is 0 we unconditionally
400  * interlock the chain to release its data.  We must obtain the lock
401  * unconditionally becuase it is possible for the chain to still be
402  * temporarily locked by a hammer2_chain_unlock() call in a race.
403  */
404 void
405 hammer2_chain_drop_unhold(hammer2_chain_t *chain)
406 {
407         hammer2_io_t *dio;
408
409         atomic_add_int(&chain->persist_refs, -1);
410         cpu_lfence();
411         if (chain->lockcnt == 0) {
412                 hammer2_mtx_ex(&chain->lock);
413                 if (chain->lockcnt == 0 && chain->persist_refs == 0) {
414                         dio = hammer2_chain_drop_data(chain, 0);
415                         if (dio)
416                                 hammer2_io_bqrelse(&dio);
417                 }
418                 hammer2_mtx_unlock(&chain->lock);
419         }
420         hammer2_chain_drop(chain);
421 }
422
423 /*
424  * Safe handling of the 1->0 transition on chain.  Returns a chain for
425  * recursive drop or NULL, possibly returning the same chain if the atomic
426  * op fails.
427  *
428  * When two chains need to be recursively dropped we use the chain we
429  * would otherwise free to placehold the additional chain.  It's a bit
430  * convoluted but we can't just recurse without potentially blowing out
431  * the kernel stack.
432  *
433  * The chain cannot be freed if it has any children.
434  * The chain cannot be freed if flagged MODIFIED unless we can dispose of that.
435  * The chain cannot be freed if flagged UPDATE unless we can dispose of that.
436  *
437  * The core spinlock is allowed nest child-to-parent (not parent-to-child).
438  */
439 static
440 hammer2_chain_t *
441 hammer2_chain_lastdrop(hammer2_chain_t *chain)
442 {
443         hammer2_pfs_t *pmp;
444         hammer2_dev_t *hmp;
445         hammer2_chain_t *parent;
446         hammer2_chain_t *rdrop;
447         hammer2_io_t *dio;
448
449         /*
450          * Critical field access.
451          */
452         hammer2_spin_ex(&chain->core.spin);
453
454         if ((parent = chain->parent) != NULL) {
455                 /*
456                  * If the chain has a parent the UPDATE bit prevents scrapping
457                  * as the chain is needed to properly flush the parent.  Try
458                  * to complete the 1->0 transition and return NULL.  Retry
459                  * (return chain) if we are unable to complete the 1->0
460                  * transition, else return NULL (nothing more to do).
461                  *
462                  * If the chain has a parent the MODIFIED bit prevents
463                  * scrapping.
464                  *
465                  * Chains with UPDATE/MODIFIED are *not* put on the LRU list!
466                  */
467                 if (chain->flags & (HAMMER2_CHAIN_UPDATE |
468                                     HAMMER2_CHAIN_MODIFIED)) {
469                         if (atomic_cmpset_int(&chain->refs, 1, 0)) {
470                                 dio = hammer2_chain_drop_data(chain, 0);
471                                 hammer2_spin_unex(&chain->core.spin);
472                                 if (dio)
473                                         hammer2_io_bqrelse(&dio);
474                                 chain = NULL;
475                         } else {
476                                 hammer2_spin_unex(&chain->core.spin);
477                         }
478                         return (chain);
479                 }
480                 /* spinlock still held */
481         } else {
482                 /*
483                  * The chain has no parent and can be flagged for destruction.
484                  * Since it has no parent, UPDATE can also be cleared.
485                  */
486                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
487                 if (chain->flags & HAMMER2_CHAIN_UPDATE)
488                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
489
490                 /*
491                  * If the chain has children or if it has been MODIFIED and
492                  * also recorded for DEDUP, we must still flush the chain.
493                  *
494                  * In the case where it has children, the DESTROY flag test
495                  * in the flush code will prevent unnecessary flushes of
496                  * MODIFIED chains that are not flagged DEDUP so don't worry
497                  * about that here.
498                  */
499                 if (chain->core.chain_count ||
500                     (chain->flags & (HAMMER2_CHAIN_MODIFIED |
501                                      HAMMER2_CHAIN_DEDUP)) ==
502                     (HAMMER2_CHAIN_MODIFIED | HAMMER2_CHAIN_DEDUP)) {
503                         /*
504                          * Put on flushq (should ensure refs > 1), retry
505                          * the drop.
506                          */
507                         hammer2_spin_unex(&chain->core.spin);
508                         hammer2_delayed_flush(chain);
509                         return(chain);  /* retry drop */
510                 }
511
512                 /*
513                  * Otherwise we can scrap the MODIFIED bit if it is set,
514                  * and continue along the freeing path.
515                  */
516                 if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
517                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
518                         atomic_add_long(&hammer2_count_modified_chains, -1);
519                         if (chain->pmp)
520                                 hammer2_pfs_memory_wakeup(chain->pmp);
521                 }
522                 /* spinlock still held */
523         }
524
525         /* spinlock still held */
526         dio = NULL;
527
528         /*
529          * If any children exist we must leave the chain intact with refs == 0.
530          * They exist because chains are retained below us which have refs or
531          * may require flushing.  This case can occur when parent != NULL.
532          *
533          * Retry (return chain) if we fail to transition the refs to 0, else
534          * return NULL indication nothing more to do.
535          *
536          * Chains with children are NOT put on the LRU list.
537          */
538         if (chain->core.chain_count) {
539                 if (parent)
540                         hammer2_spin_ex(&parent->core.spin);
541                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
542                         dio = hammer2_chain_drop_data(chain, 1);
543                         hammer2_spin_unex(&chain->core.spin);
544                         if (parent)
545                                 hammer2_spin_unex(&parent->core.spin);
546                         chain = NULL;
547                         if (dio)
548                                 hammer2_io_bqrelse(&dio);
549                 } else {
550                         hammer2_spin_unex(&chain->core.spin);
551                         if (parent)
552                                 hammer2_spin_unex(&parent->core.spin);
553                 }
554                 return (chain);
555         }
556         /* spinlock still held */
557         /* no chains left under us */
558
559         /*
560          * chain->core has no children left so no accessors can get to our
561          * chain from there.  Now we have to lock the parent core to interlock
562          * remaining possible accessors that might bump chain's refs before
563          * we can safely drop chain's refs with intent to free the chain.
564          */
565         hmp = chain->hmp;
566         pmp = chain->pmp;       /* can be NULL */
567         rdrop = NULL;
568
569         parent = chain->parent;
570
571         /*
572          * WARNING! chain's spin lock is still held here, and other spinlocks
573          *          will be acquired and released in the code below.  We
574          *          cannot be making fancy procedure calls!
575          */
576
577         /*
578          * We can cache the chain if it is associated with a pmp
579          * and not flagged as being destroyed or requesting a full
580          * release.  In this situation the chain is not removed
581          * from its parent, i.e. it can still be looked up.
582          *
583          * We intentionally do not cache DATA chains because these
584          * were likely used to load data into the logical buffer cache
585          * and will not be accessed again for some time.
586          */
587         if ((chain->flags &
588              (HAMMER2_CHAIN_DESTROY | HAMMER2_CHAIN_RELEASE)) == 0 &&
589             chain->pmp &&
590             chain->bref.type != HAMMER2_BREF_TYPE_DATA) {
591                 if (parent)
592                         hammer2_spin_ex(&parent->core.spin);
593                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
594                         /*
595                          * 1->0 transition failed, retry.  Do not drop
596                          * the chain's data yet!
597                          */
598                         if (parent)
599                                 hammer2_spin_unex(&parent->core.spin);
600                         hammer2_spin_unex(&chain->core.spin);
601
602                         return(chain);
603                 }
604
605                 /*
606                  * Success, be sure to clean out the chain's data
607                  * before putting it on a queue that it might be
608                  * reused from.
609                  */
610                 dio = hammer2_chain_drop_data(chain, 1);
611
612                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONLRU) == 0);
613                 hammer2_spin_ex(&pmp->lru_spin);
614                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONLRU);
615                 TAILQ_INSERT_TAIL(&pmp->lru_list, chain, lru_node);
616
617                 /*
618                  * If we are over the LRU limit we need to drop something.
619                  */
620                 if (pmp->lru_count > HAMMER2_LRU_LIMIT) {
621                         rdrop = TAILQ_FIRST(&pmp->lru_list);
622                         atomic_clear_int(&rdrop->flags, HAMMER2_CHAIN_ONLRU);
623                         TAILQ_REMOVE(&pmp->lru_list, rdrop, lru_node);
624                         atomic_add_int(&rdrop->refs, 1);
625                         atomic_set_int(&rdrop->flags, HAMMER2_CHAIN_RELEASE);
626                 } else {
627                         atomic_add_int(&pmp->lru_count, 1);
628                 }
629                 hammer2_spin_unex(&pmp->lru_spin);
630                 if (parent) {
631                         hammer2_spin_unex(&parent->core.spin);
632                         parent = NULL;  /* safety */
633                 }
634                 hammer2_spin_unex(&chain->core.spin);
635                 if (dio)
636                         hammer2_io_bqrelse(&dio);
637
638                 return rdrop;
639                 /* NOT REACHED */
640         }
641
642         /*
643          * Spinlock the parent and try to drop the last ref on chain.
644          * On success determine if we should dispose of the chain
645          * (remove the chain from its parent, etc).
646          *
647          * (normal core locks are top-down recursive but we define
648          * core spinlocks as bottom-up recursive, so this is safe).
649          */
650         if (parent) {
651                 hammer2_spin_ex(&parent->core.spin);
652                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
653 #if 0
654                         /* XXX remove, don't try to drop data on fail */
655                         hammer2_spin_unex(&parent->core.spin);
656                         dio = hammer2_chain_drop_data(chain, 0);
657                         hammer2_spin_unex(&chain->core.spin);
658                         if (dio)
659                                 hammer2_io_bqrelse(&dio);
660 #endif
661                         /*
662                          * 1->0 transition failed, retry.
663                          */
664                         hammer2_spin_unex(&parent->core.spin);
665                         hammer2_spin_unex(&chain->core.spin);
666
667                         return(chain);
668                 }
669
670                 /*
671                  * 1->0 transition successful, remove chain from the
672                  * parent.
673                  */
674                 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
675                         RB_REMOVE(hammer2_chain_tree,
676                                   &parent->core.rbtree, chain);
677                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
678                         --parent->core.chain_count;
679                         chain->parent = NULL;
680                 }
681
682                 /*
683                  * If our chain was the last chain in the parent's core the
684                  * core is now empty and its parent might have to be
685                  * re-dropped if it has 0 refs.
686                  */
687                 if (parent->core.chain_count == 0) {
688                         rdrop = parent;
689                         atomic_add_int(&rdrop->refs, 1);
690                         /*
691                         if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0)
692                                 rdrop = NULL;
693                         */
694                 }
695                 hammer2_spin_unex(&parent->core.spin);
696                 parent = NULL;  /* safety */
697                 /* FALL THROUGH */
698         }
699
700         /*
701          * Successful 1->0 transition and the chain can be destroyed now.
702          *
703          * We still have the core spinlock, and core's chain_count is 0.
704          * Any parent spinlock is gone.
705          */
706         hammer2_spin_unex(&chain->core.spin);
707         KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
708                  chain->core.chain_count == 0);
709
710         /*
711          * All spin locks are gone, no pointers remain to the chain, finish
712          * freeing it.
713          */
714         KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
715                                   HAMMER2_CHAIN_MODIFIED)) == 0);
716         dio = hammer2_chain_drop_data(chain, 1);
717         if (dio)
718                 hammer2_io_bqrelse(&dio);
719
720         /*
721          * Once chain resources are gone we can use the now dead chain
722          * structure to placehold what might otherwise require a recursive
723          * drop, because we have potentially two things to drop and can only
724          * return one directly.
725          */
726         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
727                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ALLOCATED);
728                 chain->hmp = NULL;
729                 kfree(chain, hmp->mchain);
730         }
731
732         /*
733          * Possible chaining loop when parent re-drop needed.
734          */
735         return(rdrop);
736 }
737
738 /*
739  * On either last lock release or last drop
740  */
741 static hammer2_io_t *
742 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
743 {
744         hammer2_io_t *dio;
745
746         if ((dio = chain->dio) != NULL) {
747                 chain->dio = NULL;
748                 chain->data = NULL;
749         } else {
750                 switch(chain->bref.type) {
751                 case HAMMER2_BREF_TYPE_VOLUME:
752                 case HAMMER2_BREF_TYPE_FREEMAP:
753                         if (lastdrop)
754                                 chain->data = NULL;
755                         break;
756                 default:
757                         if (chain->data != NULL) {
758                                 hammer2_spin_unex(&chain->core.spin);
759                                 panic("chain data not null");
760                         }
761                         KKASSERT(chain->data == NULL);
762                         break;
763                 }
764         }
765         return dio;
766 }
767
768 /*
769  * Lock a referenced chain element, acquiring its data with I/O if necessary,
770  * and specify how you would like the data to be resolved.
771  *
772  * If an I/O or other fatal error occurs, chain->error will be set to non-zero.
773  *
774  * The lock is allowed to recurse, multiple locking ops will aggregate
775  * the requested resolve types.  Once data is assigned it will not be
776  * removed until the last unlock.
777  *
778  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
779  *                         (typically used to avoid device/logical buffer
780  *                          aliasing for data)
781  *
782  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
783  *                         the INITIAL-create state (indirect blocks only).
784  *
785  *                         Do not resolve data elements for DATA chains.
786  *                         (typically used to avoid device/logical buffer
787  *                          aliasing for data)
788  *
789  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
790  *
791  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
792  *                         it will be locked exclusive.
793  *
794  * NOTE: Embedded elements (volume header, inodes) are always resolved
795  *       regardless.
796  *
797  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
798  *       element will instantiate and zero its buffer, and flush it on
799  *       release.
800  *
801  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
802  *       so as not to instantiate a device buffer, which could alias against
803  *       a logical file buffer.  However, if ALWAYS is specified the
804  *       device buffer will be instantiated anyway.
805  *
806  * WARNING! This function blocks on I/O if data needs to be fetched.  This
807  *          blocking can run concurrent with other compatible lock holders
808  *          who do not need data returning.  The lock is not upgraded to
809  *          exclusive during a data fetch, a separate bit is used to
810  *          interlock I/O.  However, an exclusive lock holder can still count
811  *          on being interlocked against an I/O fetch managed by a shared
812  *          lock holder.
813  */
814 void
815 hammer2_chain_lock(hammer2_chain_t *chain, int how)
816 {
817         /*
818          * Ref and lock the element.  Recursive locks are allowed.
819          */
820         KKASSERT(chain->refs > 0);
821         atomic_add_int(&chain->lockcnt, 1);
822
823         TIMER(20);
824
825         /*
826          * Get the appropriate lock.  If LOCKAGAIN is flagged with SHARED
827          * the caller expects a shared lock to already be present and we
828          * are giving it another ref.  This case must importantly not block
829          * if there is a pending exclusive lock request.
830          */
831         if (how & HAMMER2_RESOLVE_SHARED) {
832                 if (how & HAMMER2_RESOLVE_LOCKAGAIN) {
833                         hammer2_mtx_sh_again(&chain->lock);
834                 } else {
835                         hammer2_mtx_sh(&chain->lock);
836                 }
837         } else {
838                 hammer2_mtx_ex(&chain->lock);
839         }
840         ++curthread->td_tracker;
841         TIMER(21);
842
843         /*
844          * If we already have a valid data pointer no further action is
845          * necessary.
846          */
847         if (chain->data)
848                 return;
849         TIMER(22);
850
851         /*
852          * Do we have to resolve the data?  This is generally only
853          * applicable to HAMMER2_BREF_TYPE_DATA which is special-cased.
854          * Other BREF types expects the data to be there.
855          */
856         switch(how & HAMMER2_RESOLVE_MASK) {
857         case HAMMER2_RESOLVE_NEVER:
858                 return;
859         case HAMMER2_RESOLVE_MAYBE:
860                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
861                         return;
862                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
863                         return;
864 #if 0
865                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
866                         return;
867                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
868                         return;
869 #endif
870                 /* fall through */
871         case HAMMER2_RESOLVE_ALWAYS:
872         default:
873                 break;
874         }
875
876         /*
877          * Caller requires data
878          */
879         hammer2_chain_load_data(chain);
880 }
881
882 /*
883  * Lock the chain and remove the data hold (matches against
884  * hammer2_chain_unlock_hold()).  The data remains valid because
885  * the chain is now locked, but will be dropped as per-normal when
886  * the caller does a normal unlock.
887  */
888 void
889 hammer2_chain_lock_unhold(hammer2_chain_t *chain, int how)
890 {
891         atomic_add_int(&chain->persist_refs, -1);
892         hammer2_chain_lock(chain, how);
893 }
894
895 #if 0
896 /*
897  * Downgrade an exclusive chain lock to a shared chain lock.
898  *
899  * NOTE: There is no upgrade equivalent due to the ease of
900  *       deadlocks in that direction.
901  */
902 void
903 hammer2_chain_lock_downgrade(hammer2_chain_t *chain)
904 {
905         hammer2_mtx_downgrade(&chain->lock);
906 }
907 #endif
908
909 #if 0
910 /*
911  * Obtains a second shared lock on the chain, does not account the second
912  * shared lock as being owned by the current thread.
913  *
914  * Caller must already own a shared lock on this chain.
915  *
916  * The lock function is required to obtain the second shared lock without
917  * blocking on pending exclusive requests.
918  */
919 void
920 hammer2_chain_push_shared_lock(hammer2_chain_t *chain)
921 {
922         hammer2_mtx_sh_again(&chain->lock);
923         atomic_add_int(&chain->lockcnt, 1);
924         /* do not count in td_tracker for this thread */
925 }
926
927 /*
928  * Accounts for a shared lock that was pushed to us as being owned by our
929  * thread.
930  */
931 void
932 hammer2_chain_pull_shared_lock(hammer2_chain_t *chain)
933 {
934         ++curthread->td_tracker;
935 }
936 #endif
937
938 /*
939  * Issue I/O and install chain->data.  Caller must hold a chain lock, lock
940  * may be of any type.
941  *
942  * Once chain->data is set it cannot be disposed of until all locks are
943  * released.
944  */
945 void
946 hammer2_chain_load_data(hammer2_chain_t *chain)
947 {
948         hammer2_blockref_t *bref;
949         hammer2_dev_t *hmp;
950         hammer2_io_t *dio;
951         char *bdata;
952         int error;
953
954         /*
955          * Degenerate case, data already present, or chain is not expected
956          * to have any data.
957          */
958         if (chain->data)
959                 return;
960         if ((chain->bref.data_off & HAMMER2_OFF_MASK_RADIX) == 0)
961                 return;
962         TIMER(23);
963
964         hmp = chain->hmp;
965         KKASSERT(hmp != NULL);
966
967         /*
968          * Gain the IOINPROG bit, interlocked block.
969          */
970         for (;;) {
971                 u_int oflags;
972                 u_int nflags;
973
974                 oflags = chain->flags;
975                 cpu_ccfence();
976                 if (oflags & HAMMER2_CHAIN_IOINPROG) {
977                         nflags = oflags | HAMMER2_CHAIN_IOSIGNAL;
978                         tsleep_interlock(&chain->flags, 0);
979                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
980                                 tsleep(&chain->flags, PINTERLOCKED,
981                                         "h2iocw", 0);
982                         }
983                         /* retry */
984                 } else {
985                         nflags = oflags | HAMMER2_CHAIN_IOINPROG;
986                         if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
987                                 break;
988                         }
989                         /* retry */
990                 }
991         }
992         TIMER(24);
993
994         /*
995          * We own CHAIN_IOINPROG
996          *
997          * Degenerate case if we raced another load.
998          */
999         if (chain->data)
1000                 goto done;
1001
1002         /*
1003          * We must resolve to a device buffer, either by issuing I/O or
1004          * by creating a zero-fill element.  We do not mark the buffer
1005          * dirty when creating a zero-fill element (the hammer2_chain_modify()
1006          * API must still be used to do that).
1007          *
1008          * The device buffer is variable-sized in powers of 2 down
1009          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
1010          * chunk always contains buffers of the same size. (XXX)
1011          *
1012          * The minimum physical IO size may be larger than the variable
1013          * block size.
1014          */
1015         bref = &chain->bref;
1016
1017         /*
1018          * The getblk() optimization can only be used on newly created
1019          * elements if the physical block size matches the request.
1020          */
1021         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1022                 error = hammer2_io_new(hmp, bref->type,
1023                                        bref->data_off, chain->bytes,
1024                                        &chain->dio);
1025         } else {
1026                 error = hammer2_io_bread(hmp, bref->type,
1027                                          bref->data_off, chain->bytes,
1028                                          &chain->dio);
1029                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1030         }
1031         TIMER(25);
1032         if (error) {
1033                 chain->error = HAMMER2_ERROR_IO;
1034                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
1035                         (intmax_t)bref->data_off, error);
1036                 hammer2_io_bqrelse(&chain->dio);
1037                 goto done;
1038         }
1039         chain->error = 0;
1040
1041         /*
1042          * This isn't perfect and can be ignored on OSs which do not have
1043          * an indication as to whether a buffer is coming from cache or
1044          * if I/O was actually issued for the read.  TESTEDGOOD will work
1045          * pretty well without the B_IOISSUED logic because chains are
1046          * cached.
1047          *
1048          * If the underlying kernel buffer covers the entire chain we can
1049          * use the B_IOISSUED indication to determine if we have to re-run
1050          * the CRC on chain data for chains that managed to stay cached
1051          * across the kernel disposal of the original buffer.
1052          */
1053         if ((dio = chain->dio) != NULL && dio->bp) {
1054                 struct buf *bp = dio->bp;
1055
1056                 if (dio->psize == chain->bytes &&
1057                     (bp->b_flags & B_IOISSUED)) {
1058                         atomic_clear_int(&chain->flags,
1059                                          HAMMER2_CHAIN_TESTEDGOOD);
1060                         bp->b_flags &= ~B_IOISSUED;
1061                 }
1062         }
1063
1064         /*
1065          * NOTE: A locked chain's data cannot be modified without first
1066          *       calling hammer2_chain_modify().
1067          */
1068
1069         /*
1070          * Clear INITIAL.  In this case we used io_new() and the buffer has
1071          * been zero'd and marked dirty.
1072          */
1073         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
1074
1075         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1076                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1077                 chain->bref.flags |= HAMMER2_BREF_FLAG_ZERO;
1078         } else if (chain->flags & HAMMER2_CHAIN_MODIFIED) {
1079                 /*
1080                  * check data not currently synchronized due to
1081                  * modification.  XXX assumes data stays in the buffer
1082                  * cache, which might not be true (need biodep on flush
1083                  * to calculate crc?  or simple crc?).
1084                  */
1085         } else if ((chain->flags & HAMMER2_CHAIN_TESTEDGOOD) == 0) {
1086         TIMER(26);
1087                 if (hammer2_chain_testcheck(chain, bdata) == 0) {
1088                         chain->error = HAMMER2_ERROR_CHECK;
1089                 } else {
1090                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_TESTEDGOOD);
1091                 }
1092         }
1093         TIMER(27);
1094
1095         /*
1096          * Setup the data pointer, either pointing it to an embedded data
1097          * structure and copying the data from the buffer, or pointing it
1098          * into the buffer.
1099          *
1100          * The buffer is not retained when copying to an embedded data
1101          * structure in order to avoid potential deadlocks or recursions
1102          * on the same physical buffer.
1103          *
1104          * WARNING! Other threads can start using the data the instant we
1105          *          set chain->data non-NULL.
1106          */
1107         switch (bref->type) {
1108         case HAMMER2_BREF_TYPE_VOLUME:
1109         case HAMMER2_BREF_TYPE_FREEMAP:
1110                 /*
1111                  * Copy data from bp to embedded buffer
1112                  */
1113                 panic("hammer2_chain_load_data: unresolved volume header");
1114                 break;
1115         case HAMMER2_BREF_TYPE_DIRENT:
1116                 KKASSERT(chain->bytes != 0);
1117                 /* fall through */
1118         case HAMMER2_BREF_TYPE_INODE:
1119         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1120         case HAMMER2_BREF_TYPE_INDIRECT:
1121         case HAMMER2_BREF_TYPE_DATA:
1122         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1123         default:
1124                 /*
1125                  * Point data at the device buffer and leave dio intact.
1126                  */
1127                 chain->data = (void *)bdata;
1128                 break;
1129         }
1130
1131         /*
1132          * Release HAMMER2_CHAIN_IOINPROG and signal waiters if requested.
1133          */
1134 done:
1135         for (;;) {
1136                 u_int oflags;
1137                 u_int nflags;
1138
1139                 oflags = chain->flags;
1140                 nflags = oflags & ~(HAMMER2_CHAIN_IOINPROG |
1141                                     HAMMER2_CHAIN_IOSIGNAL);
1142                 KKASSERT(oflags & HAMMER2_CHAIN_IOINPROG);
1143                 if (atomic_cmpset_int(&chain->flags, oflags, nflags)) {
1144                         if (oflags & HAMMER2_CHAIN_IOSIGNAL)
1145                                 wakeup(&chain->flags);
1146                         break;
1147                 }
1148         }
1149         TIMER(28);
1150 }
1151
1152 /*
1153  * Unlock and deref a chain element.
1154  *
1155  * Remember that the presence of children under chain prevent the chain's
1156  * destruction but do not add additional references, so the dio will still
1157  * be dropped.
1158  */
1159 void
1160 hammer2_chain_unlock(hammer2_chain_t *chain)
1161 {
1162         u_int lockcnt;
1163
1164         --curthread->td_tracker;
1165         /*
1166          * If multiple locks are present (or being attempted) on this
1167          * particular chain we can just unlock, drop refs, and return.
1168          *
1169          * Otherwise fall-through on the 1->0 transition.
1170          */
1171         for (;;) {
1172                 lockcnt = chain->lockcnt;
1173                 KKASSERT(lockcnt > 0);
1174                 cpu_ccfence();
1175                 if (lockcnt > 1) {
1176                         if (atomic_cmpset_int(&chain->lockcnt,
1177                                               lockcnt, lockcnt - 1)) {
1178                                 hammer2_mtx_unlock(&chain->lock);
1179                                 return;
1180                         }
1181                 } else {
1182                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1183                                 break;
1184                 }
1185                 /* retry */
1186         }
1187
1188         /*
1189          * Normally we want to disassociate the data on the last unlock,
1190          * but leave it intact if persist_refs is non-zero.  The persist-data
1191          * user modifies persist_refs only while holding the chain locked
1192          * so there should be no race on the last unlock here.
1193          *
1194          * NOTE: If this was a shared lock we have to temporarily upgrade it
1195          *       to prevent data load races.  We can only do this non-blocking,
1196          *       and unlock/relock-excl can deadlock.  If the try fails it
1197          *       means someone else got a shared or exclusive lock while we
1198          *       we bandying about.
1199          */
1200         if (chain->persist_refs == 0) {
1201                 hammer2_io_t *dio;
1202
1203                 if (hammer2_mtx_upgrade_try(&chain->lock) == 0 &&
1204                     chain->lockcnt == 0 && chain->persist_refs == 0) {
1205                         dio = hammer2_chain_drop_data(chain, 0);
1206                         if (dio)
1207                                 hammer2_io_bqrelse(&dio);
1208                 }
1209         }
1210         hammer2_mtx_unlock(&chain->lock);
1211 }
1212
1213 /*
1214  * Unlock and hold chain data intact
1215  */
1216 void
1217 hammer2_chain_unlock_hold(hammer2_chain_t *chain)
1218 {
1219         atomic_add_int(&chain->persist_refs, 1);
1220         hammer2_chain_unlock(chain);
1221 }
1222
1223 /*
1224  * Helper to obtain the blockref[] array base and count for a chain.
1225  *
1226  * XXX Not widely used yet, various use cases need to be validated and
1227  *     converted to use this function.
1228  */
1229 static
1230 hammer2_blockref_t *
1231 hammer2_chain_base_and_count(hammer2_chain_t *parent, int *countp)
1232 {
1233         hammer2_blockref_t *base;
1234         int count;
1235
1236         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1237                 base = NULL;
1238
1239                 switch(parent->bref.type) {
1240                 case HAMMER2_BREF_TYPE_INODE:
1241                         count = HAMMER2_SET_COUNT;
1242                         break;
1243                 case HAMMER2_BREF_TYPE_INDIRECT:
1244                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1245                         count = parent->bytes / sizeof(hammer2_blockref_t);
1246                         break;
1247                 case HAMMER2_BREF_TYPE_VOLUME:
1248                         count = HAMMER2_SET_COUNT;
1249                         break;
1250                 case HAMMER2_BREF_TYPE_FREEMAP:
1251                         count = HAMMER2_SET_COUNT;
1252                         break;
1253                 default:
1254                         panic("hammer2_chain_create_indirect: "
1255                               "unrecognized blockref type: %d",
1256                               parent->bref.type);
1257                         count = 0;
1258                         break;
1259                 }
1260         } else {
1261                 switch(parent->bref.type) {
1262                 case HAMMER2_BREF_TYPE_INODE:
1263                         base = &parent->data->ipdata.u.blockset.blockref[0];
1264                         count = HAMMER2_SET_COUNT;
1265                         break;
1266                 case HAMMER2_BREF_TYPE_INDIRECT:
1267                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1268                         base = &parent->data->npdata[0];
1269                         count = parent->bytes / sizeof(hammer2_blockref_t);
1270                         break;
1271                 case HAMMER2_BREF_TYPE_VOLUME:
1272                         base = &parent->data->voldata.
1273                                         sroot_blockset.blockref[0];
1274                         count = HAMMER2_SET_COUNT;
1275                         break;
1276                 case HAMMER2_BREF_TYPE_FREEMAP:
1277                         base = &parent->data->blkset.blockref[0];
1278                         count = HAMMER2_SET_COUNT;
1279                         break;
1280                 default:
1281                         panic("hammer2_chain_create_indirect: "
1282                               "unrecognized blockref type: %d",
1283                               parent->bref.type);
1284                         count = 0;
1285                         break;
1286                 }
1287         }
1288         *countp = count;
1289
1290         return base;
1291 }
1292
1293 /*
1294  * This counts the number of live blockrefs in a block array and
1295  * also calculates the point at which all remaining blockrefs are empty.
1296  * This routine can only be called on a live chain.
1297  *
1298  * NOTE: Flag is not set until after the count is complete, allowing
1299  *       callers to test the flag without holding the spinlock.
1300  *
1301  * NOTE: If base is NULL the related chain is still in the INITIAL
1302  *       state and there are no blockrefs to count.
1303  *
1304  * NOTE: live_count may already have some counts accumulated due to
1305  *       creation and deletion and could even be initially negative.
1306  */
1307 void
1308 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1309                          hammer2_blockref_t *base, int count)
1310 {
1311         hammer2_spin_ex(&chain->core.spin);
1312         if ((chain->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0) {
1313                 if (base) {
1314                         while (--count >= 0) {
1315                                 if (base[count].type)
1316                                         break;
1317                         }
1318                         chain->core.live_zero = count + 1;
1319                         while (count >= 0) {
1320                                 if (base[count].type)
1321                                         atomic_add_int(&chain->core.live_count,
1322                                                        1);
1323                                 --count;
1324                         }
1325                 } else {
1326                         chain->core.live_zero = 0;
1327                 }
1328                 /* else do not modify live_count */
1329                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_COUNTEDBREFS);
1330         }
1331         hammer2_spin_unex(&chain->core.spin);
1332 }
1333
1334 /*
1335  * Resize the chain's physical storage allocation in-place.  This function does
1336  * not usually adjust the data pointer and must be followed by (typically) a
1337  * hammer2_chain_modify() call to copy any old data over and adjust the
1338  * data pointer.
1339  *
1340  * Chains can be resized smaller without reallocating the storage.  Resizing
1341  * larger will reallocate the storage.  Excess or prior storage is reclaimed
1342  * asynchronously at a later time.
1343  *
1344  * An nradix value of 0 is special-cased to mean that the storage should
1345  * be disassociated, that is the chain is being resized to 0 bytes (not 1
1346  * byte).
1347  *
1348  * Must be passed an exclusively locked parent and chain.
1349  *
1350  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1351  * to avoid instantiating a device buffer that conflicts with the vnode data
1352  * buffer.  However, because H2 can compress or encrypt data, the chain may
1353  * have a dio assigned to it in those situations, and they do not conflict.
1354  *
1355  * XXX return error if cannot resize.
1356  */
1357 void
1358 hammer2_chain_resize(hammer2_chain_t *chain,
1359                      hammer2_tid_t mtid, hammer2_off_t dedup_off,
1360                      int nradix, int flags)
1361 {
1362         hammer2_dev_t *hmp;
1363         size_t obytes;
1364         size_t nbytes;
1365
1366         hmp = chain->hmp;
1367
1368         /*
1369          * Only data and indirect blocks can be resized for now.
1370          * (The volu root, inodes, and freemap elements use a fixed size).
1371          */
1372         KKASSERT(chain != &hmp->vchain);
1373         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1374                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1375                  chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1376
1377         /*
1378          * Nothing to do if the element is already the proper size
1379          */
1380         obytes = chain->bytes;
1381         nbytes = (nradix) ? (1U << nradix) : 0;
1382         if (obytes == nbytes)
1383                 return;
1384
1385         /*
1386          * Make sure the old data is instantiated so we can copy it.  If this
1387          * is a data block, the device data may be superfluous since the data
1388          * might be in a logical block, but compressed or encrypted data is
1389          * another matter.
1390          *
1391          * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1392          */
1393         hammer2_chain_modify(chain, mtid, dedup_off, 0);
1394
1395         /*
1396          * Relocate the block, even if making it smaller (because different
1397          * block sizes may be in different regions).
1398          *
1399          * NOTE: Operation does not copy the data and may only be used
1400          *        to resize data blocks in-place, or directory entry blocks
1401          *        which are about to be modified in some manner.
1402          */
1403         hammer2_freemap_alloc(chain, nbytes);
1404         chain->bytes = nbytes;
1405
1406         /*
1407          * We don't want the followup chain_modify() to try to copy data
1408          * from the old (wrong-sized) buffer.  It won't know how much to
1409          * copy.  This case should only occur during writes when the
1410          * originator already has the data to write in-hand.
1411          */
1412         if (chain->dio) {
1413                 KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1414                          chain->bref.type == HAMMER2_BREF_TYPE_DIRENT);
1415                 hammer2_io_brelse(&chain->dio);
1416                 chain->data = NULL;
1417         }
1418 }
1419
1420 /*
1421  * Helper for chains already flagged as MODIFIED.  A new allocation may
1422  * still be required if the existing one has already been used in a de-dup.
1423  */
1424 static __inline
1425 int
1426 modified_needs_new_allocation(hammer2_chain_t *chain)
1427 {
1428         hammer2_io_t *dio;
1429
1430         /*
1431          * We only live-dedup data, we do not live-dedup meta-data.
1432          */
1433         if (chain->bref.type != HAMMER2_BREF_TYPE_DATA &&
1434             chain->bref.type != HAMMER2_BREF_TYPE_DIRENT) {
1435                 return 0;
1436         }
1437
1438         /*
1439          * If chain has no data, then there is nothing to live-dedup.
1440          */
1441         if (chain->bytes == 0)
1442                 return 0;
1443
1444         /*
1445          * If this flag is not set the current modification has not been
1446          * recorded for dedup so a new allocation is not needed.  The
1447          * recording occurs when dirty file data is flushed from the frontend
1448          * to the backend.
1449          */
1450         if (chain->flags & HAMMER2_CHAIN_DEDUP)
1451                 return 1;
1452
1453         /*
1454          * If the DEDUP flag is set we have one final line of defense to
1455          * allow re-use of a modified buffer, and that is if the DIO_INVALOK
1456          * flag is still set on the underlying DIO.  This flag is only set
1457          * for hammer2_io_new() buffers which cover the whole buffer (64KB),
1458          * and is cleared when a dedup operation actually decides to use
1459          * the buffer.
1460          */
1461
1462         if ((dio = chain->dio) != NULL) {
1463                 if (dio->refs & HAMMER2_DIO_INVALOK)
1464                         return 0;
1465         } else {
1466                 dio = hammer2_io_getquick(chain->hmp, chain->bref.data_off,
1467                                           chain->bytes);
1468                 if (dio) {
1469                         if (dio->refs & HAMMER2_DIO_INVALOK) {
1470                                 hammer2_io_putblk(&dio);
1471                                 return 0;
1472                         }
1473                         hammer2_io_putblk(&dio);
1474                 }
1475         }
1476         return 1;
1477 }
1478
1479 /*
1480  * Set the chain modified so its data can be changed by the caller.
1481  *
1482  * Sets bref.modify_tid to mtid only if mtid != 0.  Note that bref.modify_tid
1483  * is a CLC (cluster level change) field and is not updated by parent
1484  * propagation during a flush.
1485  *
1486  * If the caller passes a non-zero dedup_off we assign data_off to that
1487  * instead of allocating a ne block.  Caller must not modify the data already
1488  * present at the target offset.
1489  */
1490 void
1491 hammer2_chain_modify(hammer2_chain_t *chain, hammer2_tid_t mtid,
1492                      hammer2_off_t dedup_off, int flags)
1493 {
1494         hammer2_blockref_t obref;
1495         hammer2_dev_t *hmp;
1496         hammer2_io_t *dio;
1497         int error;
1498         int wasinitial;
1499         int newmod;
1500         char *bdata;
1501
1502         hmp = chain->hmp;
1503         obref = chain->bref;
1504         KKASSERT((chain->flags & HAMMER2_CHAIN_FICTITIOUS) == 0);
1505
1506         /*
1507          * Data is not optional for freemap chains (we must always be sure
1508          * to copy the data on COW storage allocations).
1509          */
1510         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1511             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1512                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1513                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1514         }
1515
1516         /*
1517          * Data must be resolved if already assigned, unless explicitly
1518          * flagged otherwise.
1519          */
1520         if (chain->data == NULL && chain->bytes != 0 &&
1521             (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1522             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1523                 hammer2_chain_load_data(chain);
1524         }
1525
1526         /*
1527          * Set MODIFIED to indicate that the chain has been modified.
1528          * Set UPDATE to ensure that the blockref is updated in the parent.
1529          *
1530          * If MODIFIED is already set determine if we can reuse the assigned
1531          * data block or if we need a new data block.  The assigned data block
1532          * can be reused if HAMMER2_DIO_INVALOK is set on the dio.
1533          */
1534         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
1535             modified_needs_new_allocation(chain)) {
1536                 newmod = 1;
1537         } else if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1538                 /*
1539                  * Must set modified bit.
1540                  */
1541                 atomic_add_long(&hammer2_count_modified_chains, 1);
1542                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1543                 hammer2_pfs_memory_inc(chain->pmp);  /* can be NULL */
1544
1545                 /*
1546                  * We may be able to avoid a copy-on-write if the chain's
1547                  * check mode is set to NONE and the chain's current
1548                  * modify_tid is beyond the last explicit snapshot tid.
1549                  *
1550                  * This implements HAMMER2's overwrite-in-place feature.
1551                  *
1552                  * NOTE! This data-block cannot be used as a de-duplication
1553                  *       source when the check mode is set to NONE.
1554                  */
1555                 if ((chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1556                      chain->bref.type == HAMMER2_BREF_TYPE_DIRENT) &&
1557                     (chain->flags & HAMMER2_CHAIN_INITIAL) == 0 &&
1558                     HAMMER2_DEC_CHECK(chain->bref.methods) ==
1559                      HAMMER2_CHECK_NONE &&
1560                     chain->pmp &&
1561                     chain->bref.modify_tid >
1562                      chain->pmp->iroot->meta.pfs_lsnap_tid &&
1563                     modified_needs_new_allocation(chain) == 0) {
1564                         /*
1565                          * Sector overwrite allowed.
1566                          */
1567                         newmod = 0;
1568                 } else {
1569                         /*
1570                          * Sector overwrite not allowed, must copy-on-write.
1571                          */
1572                         newmod = 1;
1573                 }
1574         } else {
1575                 /*
1576                  * Already flagged modified, no new allocation is needed.
1577                  */
1578                 newmod = 0;
1579         }
1580
1581         /*
1582          * Flag parent update required.
1583          */
1584         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
1585                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1586
1587         /*
1588          * The modification or re-modification requires an allocation and
1589          * possible COW.
1590          *
1591          * If dedup_off is non-zero, caller already has a data offset
1592          * containing the caller's desired data.  The dedup offset is
1593          * allowed to be in a partially free state and we must be sure
1594          * to reset it to a fully allocated state to force two bulkfree
1595          * passes to free it again.
1596          *
1597          * NOTE: Only applicable when chain->bytes != 0.
1598          *
1599          * XXX can a chain already be marked MODIFIED without a data
1600          * assignment?  If not, assert here instead of testing the case.
1601          */
1602         if (chain != &hmp->vchain && chain != &hmp->fchain &&
1603             chain->bytes) {
1604                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1605                      newmod
1606                 ) {
1607                         if (dedup_off) {
1608                                 chain->bref.data_off = dedup_off;
1609                                 chain->bytes = 1 << (dedup_off &
1610                                                      HAMMER2_OFF_MASK_RADIX);
1611                                 atomic_set_int(&chain->flags,
1612                                                HAMMER2_CHAIN_DEDUP);
1613                                 hammer2_freemap_adjust(hmp, &chain->bref,
1614                                                 HAMMER2_FREEMAP_DORECOVER);
1615                         } else {
1616                                 hammer2_freemap_alloc(chain, chain->bytes);
1617                                 atomic_clear_int(&chain->flags,
1618                                                  HAMMER2_CHAIN_DEDUP);
1619                         }
1620                         /* XXX failed allocation */
1621                 }
1622         }
1623
1624         /*
1625          * Update mirror_tid and modify_tid.  modify_tid is only updated
1626          * if not passed as zero (during flushes, parent propagation passes
1627          * the value 0).
1628          *
1629          * NOTE: chain->pmp could be the device spmp.
1630          */
1631         chain->bref.mirror_tid = hmp->voldata.mirror_tid + 1;
1632         if (mtid)
1633                 chain->bref.modify_tid = mtid;
1634
1635         /*
1636          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1637          * requires updating as well as to tell the delete code that the
1638          * chain's blockref might not exactly match (in terms of physical size
1639          * or block offset) the one in the parent's blocktable.  The base key
1640          * of course will still match.
1641          */
1642         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1643                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1644
1645         /*
1646          * Short-cut data blocks which the caller does not need an actual
1647          * data reference to (aka OPTDATA), as long as the chain does not
1648          * already have a data pointer to the data.  This generally means
1649          * that the modifications are being done via the logical buffer cache.
1650          * The INITIAL flag relates only to the device data buffer and thus
1651          * remains unchange in this situation.
1652          *
1653          * This code also handles bytes == 0 (most dirents).
1654          */
1655         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1656             (flags & HAMMER2_MODIFY_OPTDATA) &&
1657             chain->data == NULL) {
1658                 KKASSERT(chain->dio == NULL);
1659                 goto skip2;
1660         }
1661
1662         /*
1663          * Clearing the INITIAL flag (for indirect blocks) indicates that
1664          * we've processed the uninitialized storage allocation.
1665          *
1666          * If this flag is already clear we are likely in a copy-on-write
1667          * situation but we have to be sure NOT to bzero the storage if
1668          * no data is present.
1669          */
1670         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1671                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1672                 wasinitial = 1;
1673         } else {
1674                 wasinitial = 0;
1675         }
1676
1677         /*
1678          * Instantiate data buffer and possibly execute COW operation
1679          */
1680         switch(chain->bref.type) {
1681         case HAMMER2_BREF_TYPE_VOLUME:
1682         case HAMMER2_BREF_TYPE_FREEMAP:
1683                 /*
1684                  * The data is embedded, no copy-on-write operation is
1685                  * needed.
1686                  */
1687                 KKASSERT(chain->dio == NULL);
1688                 break;
1689         case HAMMER2_BREF_TYPE_DIRENT:
1690                 /*
1691                  * The data might be fully embedded.
1692                  */
1693                 if (chain->bytes == 0) {
1694                         KKASSERT(chain->dio == NULL);
1695                         break;
1696                 }
1697                 /* fall through */
1698         case HAMMER2_BREF_TYPE_INODE:
1699         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1700         case HAMMER2_BREF_TYPE_DATA:
1701         case HAMMER2_BREF_TYPE_INDIRECT:
1702         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1703                 /*
1704                  * Perform the copy-on-write operation
1705                  *
1706                  * zero-fill or copy-on-write depending on whether
1707                  * chain->data exists or not and set the dirty state for
1708                  * the new buffer.  hammer2_io_new() will handle the
1709                  * zero-fill.
1710                  *
1711                  * If a dedup_off was supplied this is an existing block
1712                  * and no COW, copy, or further modification is required.
1713                  */
1714                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1715
1716                 if (wasinitial && dedup_off == 0) {
1717                         error = hammer2_io_new(hmp, chain->bref.type,
1718                                                chain->bref.data_off,
1719                                                chain->bytes, &dio);
1720                 } else {
1721                         error = hammer2_io_bread(hmp, chain->bref.type,
1722                                                  chain->bref.data_off,
1723                                                  chain->bytes, &dio);
1724                 }
1725                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1726
1727                 /*
1728                  * If an I/O error occurs make sure callers cannot accidently
1729                  * modify the old buffer's contents and corrupt the filesystem.
1730                  */
1731                 if (error) {
1732                         kprintf("hammer2_chain_modify: hmp=%p I/O error\n",
1733                                 hmp);
1734                         chain->error = HAMMER2_ERROR_IO;
1735                         hammer2_io_brelse(&dio);
1736                         hammer2_io_brelse(&chain->dio);
1737                         chain->data = NULL;
1738                         break;
1739                 }
1740                 chain->error = 0;
1741                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1742
1743                 if (chain->data) {
1744                         /*
1745                          * COW (unless a dedup).
1746                          */
1747                         KKASSERT(chain->dio != NULL);
1748                         if (chain->data != (void *)bdata && dedup_off == 0) {
1749                                 bcopy(chain->data, bdata, chain->bytes);
1750                         }
1751                 } else if (wasinitial == 0) {
1752                         /*
1753                          * We have a problem.  We were asked to COW but
1754                          * we don't have any data to COW with!
1755                          */
1756                         panic("hammer2_chain_modify: having a COW %p\n",
1757                               chain);
1758                 }
1759
1760                 /*
1761                  * Retire the old buffer, replace with the new.  Dirty or
1762                  * redirty the new buffer.
1763                  *
1764                  * WARNING! The system buffer cache may have already flushed
1765                  *          the buffer, so we must be sure to [re]dirty it
1766                  *          for further modification.
1767                  *
1768                  *          If dedup_off was supplied, the caller is not
1769                  *          expected to make any further modification to the
1770                  *          buffer.
1771                  */
1772                 if (chain->dio)
1773                         hammer2_io_bqrelse(&chain->dio);
1774                 chain->data = (void *)bdata;
1775                 chain->dio = dio;
1776                 if (dedup_off == 0)
1777                         hammer2_io_setdirty(dio);
1778                 break;
1779         default:
1780                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1781                       chain->bref.type);
1782                 break;
1783
1784         }
1785 skip2:
1786         /*
1787          * setflush on parent indicating that the parent must recurse down
1788          * to us.  Do not call on chain itself which might already have it
1789          * set.
1790          */
1791         if (chain->parent)
1792                 hammer2_chain_setflush(chain->parent);
1793 }
1794
1795 /*
1796  * Modify the chain associated with an inode.
1797  */
1798 void
1799 hammer2_chain_modify_ip(hammer2_inode_t *ip, hammer2_chain_t *chain,
1800                         hammer2_tid_t mtid, int flags)
1801 {
1802         hammer2_inode_modify(ip);
1803         hammer2_chain_modify(chain, mtid, 0, flags);
1804 }
1805
1806 /*
1807  * Volume header data locks
1808  */
1809 void
1810 hammer2_voldata_lock(hammer2_dev_t *hmp)
1811 {
1812         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1813 }
1814
1815 void
1816 hammer2_voldata_unlock(hammer2_dev_t *hmp)
1817 {
1818         lockmgr(&hmp->vollk, LK_RELEASE);
1819 }
1820
1821 void
1822 hammer2_voldata_modify(hammer2_dev_t *hmp)
1823 {
1824         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1825                 atomic_add_long(&hammer2_count_modified_chains, 1);
1826                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1827                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1828         }
1829 }
1830
1831 /*
1832  * This function returns the chain at the nearest key within the specified
1833  * range.  The returned chain will be referenced but not locked.
1834  *
1835  * This function will recurse through chain->rbtree as necessary and will
1836  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1837  * the iteration value is less than the current value of *key_nextp.
1838  *
1839  * The caller should use (*key_nextp) to calculate the actual range of
1840  * the returned element, which will be (key_beg to *key_nextp - 1), because
1841  * there might be another element which is superior to the returned element
1842  * and overlaps it.
1843  *
1844  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1845  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1846  * it will wind up being (key_end + 1).
1847  *
1848  * WARNING!  Must be called with child's spinlock held.  Spinlock remains
1849  *           held through the operation.
1850  */
1851 struct hammer2_chain_find_info {
1852         hammer2_chain_t         *best;
1853         hammer2_key_t           key_beg;
1854         hammer2_key_t           key_end;
1855         hammer2_key_t           key_next;
1856 };
1857
1858 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1859 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1860
1861 static
1862 hammer2_chain_t *
1863 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1864                           hammer2_key_t key_beg, hammer2_key_t key_end)
1865 {
1866         struct hammer2_chain_find_info info;
1867
1868         info.best = NULL;
1869         info.key_beg = key_beg;
1870         info.key_end = key_end;
1871         info.key_next = *key_nextp;
1872
1873         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1874                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1875                 &info);
1876         *key_nextp = info.key_next;
1877 #if 0
1878         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1879                 parent, key_beg, key_end, *key_nextp);
1880 #endif
1881
1882         return (info.best);
1883 }
1884
1885 static
1886 int
1887 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1888 {
1889         struct hammer2_chain_find_info *info = data;
1890         hammer2_key_t child_beg;
1891         hammer2_key_t child_end;
1892
1893         child_beg = child->bref.key;
1894         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1895
1896         if (child_end < info->key_beg)
1897                 return(-1);
1898         if (child_beg > info->key_end)
1899                 return(1);
1900         return(0);
1901 }
1902
1903 static
1904 int
1905 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1906 {
1907         struct hammer2_chain_find_info *info = data;
1908         hammer2_chain_t *best;
1909         hammer2_key_t child_end;
1910
1911         /*
1912          * WARNING! Layerq is scanned forwards, exact matches should keep
1913          *          the existing info->best.
1914          */
1915         if ((best = info->best) == NULL) {
1916                 /*
1917                  * No previous best.  Assign best
1918                  */
1919                 info->best = child;
1920         } else if (best->bref.key <= info->key_beg &&
1921                    child->bref.key <= info->key_beg) {
1922                 /*
1923                  * Illegal overlap.
1924                  */
1925                 KKASSERT(0);
1926                 /*info->best = child;*/
1927         } else if (child->bref.key < best->bref.key) {
1928                 /*
1929                  * Child has a nearer key and best is not flush with key_beg.
1930                  * Set best to child.  Truncate key_next to the old best key.
1931                  */
1932                 info->best = child;
1933                 if (info->key_next > best->bref.key || info->key_next == 0)
1934                         info->key_next = best->bref.key;
1935         } else if (child->bref.key == best->bref.key) {
1936                 /*
1937                  * If our current best is flush with the child then this
1938                  * is an illegal overlap.
1939                  *
1940                  * key_next will automatically be limited to the smaller of
1941                  * the two end-points.
1942                  */
1943                 KKASSERT(0);
1944                 info->best = child;
1945         } else {
1946                 /*
1947                  * Keep the current best but truncate key_next to the child's
1948                  * base.
1949                  *
1950                  * key_next will also automatically be limited to the smaller
1951                  * of the two end-points (probably not necessary for this case
1952                  * but we do it anyway).
1953                  */
1954                 if (info->key_next > child->bref.key || info->key_next == 0)
1955                         info->key_next = child->bref.key;
1956         }
1957
1958         /*
1959          * Always truncate key_next based on child's end-of-range.
1960          */
1961         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1962         if (child_end && (info->key_next > child_end || info->key_next == 0))
1963                 info->key_next = child_end;
1964
1965         return(0);
1966 }
1967
1968 /*
1969  * Retrieve the specified chain from a media blockref, creating the
1970  * in-memory chain structure which reflects it.
1971  *
1972  * To handle insertion races pass the INSERT_RACE flag along with the
1973  * generation number of the core.  NULL will be returned if the generation
1974  * number changes before we have a chance to insert the chain.  Insert
1975  * races can occur because the parent might be held shared.
1976  *
1977  * Caller must hold the parent locked shared or exclusive since we may
1978  * need the parent's bref array to find our block.
1979  *
1980  * WARNING! chain->pmp is always set to NULL for any chain representing
1981  *          part of the super-root topology.
1982  */
1983 hammer2_chain_t *
1984 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1985                   hammer2_blockref_t *bref)
1986 {
1987         hammer2_dev_t *hmp = parent->hmp;
1988         hammer2_chain_t *chain;
1989         int error;
1990
1991         /*
1992          * Allocate a chain structure representing the existing media
1993          * entry.  Resulting chain has one ref and is not locked.
1994          */
1995         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1996                 chain = hammer2_chain_alloc(hmp, NULL, bref);
1997         else
1998                 chain = hammer2_chain_alloc(hmp, parent->pmp, bref);
1999         /* ref'd chain returned */
2000
2001         /*
2002          * Flag that the chain is in the parent's blockmap so delete/flush
2003          * knows what to do with it.
2004          */
2005         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
2006
2007         /*
2008          * Link the chain into its parent.  A spinlock is required to safely
2009          * access the RBTREE, and it is possible to collide with another
2010          * hammer2_chain_get() operation because the caller might only hold
2011          * a shared lock on the parent.
2012          *
2013          * NOTE: Get races can occur quite often when we distribute
2014          *       asynchronous read-aheads across multiple threads.
2015          */
2016         KKASSERT(parent->refs > 0);
2017         error = hammer2_chain_insert(parent, chain,
2018                                      HAMMER2_CHAIN_INSERT_SPIN |
2019                                      HAMMER2_CHAIN_INSERT_RACE,
2020                                      generation);
2021         if (error) {
2022                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2023                 /*kprintf("chain %p get race\n", chain);*/
2024                 hammer2_chain_drop(chain);
2025                 chain = NULL;
2026         } else {
2027                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2028         }
2029
2030         /*
2031          * Return our new chain referenced but not locked, or NULL if
2032          * a race occurred.
2033          */
2034         return (chain);
2035 }
2036
2037 /*
2038  * Lookup initialization/completion API
2039  */
2040 hammer2_chain_t *
2041 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
2042 {
2043         hammer2_chain_ref(parent);
2044         if (flags & HAMMER2_LOOKUP_SHARED) {
2045                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
2046                                            HAMMER2_RESOLVE_SHARED);
2047         } else {
2048                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
2049         }
2050         return (parent);
2051 }
2052
2053 void
2054 hammer2_chain_lookup_done(hammer2_chain_t *parent)
2055 {
2056         if (parent) {
2057                 hammer2_chain_unlock(parent);
2058                 hammer2_chain_drop(parent);
2059         }
2060 }
2061
2062 hammer2_chain_t *
2063 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
2064 {
2065         hammer2_chain_t *oparent;
2066         hammer2_chain_t *nparent;
2067
2068         /*
2069          * Be careful of order, oparent must be unlocked before nparent
2070          * is locked below to avoid a deadlock.
2071          */
2072         oparent = *parentp;
2073         hammer2_spin_ex(&oparent->core.spin);
2074         nparent = oparent->parent;
2075         if (nparent == NULL) {
2076                 hammer2_spin_unex(&oparent->core.spin);
2077                 panic("hammer2_chain_getparent: no parent");
2078         }
2079         hammer2_chain_ref(nparent);
2080         hammer2_spin_unex(&oparent->core.spin);
2081         if (oparent) {
2082                 hammer2_chain_unlock(oparent);
2083                 hammer2_chain_drop(oparent);
2084                 oparent = NULL;
2085         }
2086
2087         hammer2_chain_lock(nparent, how);
2088         *parentp = nparent;
2089
2090         return (nparent);
2091 }
2092
2093 /*
2094  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
2095  * (*parentp) typically points to an inode but can also point to a related
2096  * indirect block and this function will recurse upwards and find the inode
2097  * again.
2098  *
2099  * (*parentp) must be exclusively locked and referenced and can be an inode
2100  * or an existing indirect block within the inode.
2101  *
2102  * On return (*parentp) will be modified to point at the deepest parent chain
2103  * element encountered during the search, as a helper for an insertion or
2104  * deletion.   The new (*parentp) will be locked and referenced and the old
2105  * will be unlocked and dereferenced (no change if they are both the same).
2106  *
2107  * The matching chain will be returned exclusively locked.  If NOLOCK is
2108  * requested the chain will be returned only referenced.  Note that the
2109  * parent chain must always be locked shared or exclusive, matching the
2110  * HAMMER2_LOOKUP_SHARED flag.  We can conceivably lock it SHARED temporarily
2111  * when NOLOCK is specified but that complicates matters if *parentp must
2112  * inherit the chain.
2113  *
2114  * NOLOCK also implies NODATA, since an unlocked chain usually has a NULL
2115  * data pointer or can otherwise be in flux.
2116  *
2117  * NULL is returned if no match was found, but (*parentp) will still
2118  * potentially be adjusted.
2119  *
2120  * If a fatal error occurs (typically an I/O error), a dummy chain is
2121  * returned with chain->error and error-identifying information set.  This
2122  * chain will assert if you try to do anything fancy with it.
2123  *
2124  * XXX Depending on where the error occurs we should allow continued iteration.
2125  *
2126  * On return (*key_nextp) will point to an iterative value for key_beg.
2127  * (If NULL is returned (*key_nextp) is set to (key_end + 1)).
2128  *
2129  * This function will also recurse up the chain if the key is not within the
2130  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
2131  * can simply allow (*parentp) to float inside the loop.
2132  *
2133  * NOTE!  chain->data is not always resolved.  By default it will not be
2134  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
2135  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
2136  *        BREF_TYPE_DATA as the device buffer can alias the logical file
2137  *        buffer).
2138  */
2139
2140 hammer2_chain_t *
2141 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
2142                      hammer2_key_t key_beg, hammer2_key_t key_end,
2143                      int *cache_indexp, int flags)
2144 {
2145         hammer2_dev_t *hmp;
2146         hammer2_chain_t *parent;
2147         hammer2_chain_t *chain;
2148         hammer2_blockref_t *base;
2149         hammer2_blockref_t *bref;
2150         hammer2_blockref_t bcopy;
2151         hammer2_key_t scan_beg;
2152         hammer2_key_t scan_end;
2153         int count = 0;
2154         int how_always = HAMMER2_RESOLVE_ALWAYS;
2155         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2156         int how;
2157         int generation;
2158         int maxloops = 300000;
2159
2160         TIMER(8);
2161
2162         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2163                 how_maybe = how_always;
2164                 how = HAMMER2_RESOLVE_ALWAYS;
2165         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2166                 how = HAMMER2_RESOLVE_NEVER;
2167         } else {
2168                 how = HAMMER2_RESOLVE_MAYBE;
2169         }
2170         if (flags & HAMMER2_LOOKUP_SHARED) {
2171                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2172                 how_always |= HAMMER2_RESOLVE_SHARED;
2173                 how |= HAMMER2_RESOLVE_SHARED;
2174         }
2175
2176         /*
2177          * Recurse (*parentp) upward if necessary until the parent completely
2178          * encloses the key range or we hit the inode.
2179          *
2180          * Handle races against the flusher deleting indirect nodes on its
2181          * way back up by continuing to recurse upward past the deletion.
2182          */
2183         parent = *parentp;
2184         hmp = parent->hmp;
2185
2186         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2187                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2188                 scan_beg = parent->bref.key;
2189                 scan_end = scan_beg +
2190                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2191                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT ||
2192                     (parent->flags & HAMMER2_CHAIN_DELETED) == 0) {
2193                         if (key_beg >= scan_beg && key_end <= scan_end)
2194                                 break;
2195                 }
2196                 parent = hammer2_chain_getparent(parentp, how_maybe);
2197         }
2198 again:
2199
2200         TIMER(9);
2201         if (--maxloops == 0)
2202                 panic("hammer2_chain_lookup: maxloops");
2203         /*
2204          * Locate the blockref array.  Currently we do a fully associative
2205          * search through the array.
2206          */
2207         switch(parent->bref.type) {
2208         case HAMMER2_BREF_TYPE_INODE:
2209                 /*
2210                  * Special shortcut for embedded data returns the inode
2211                  * itself.  Callers must detect this condition and access
2212                  * the embedded data (the strategy code does this for us).
2213                  *
2214                  * This is only applicable to regular files and softlinks.
2215                  *
2216                  * We need a second lock on parent.  Since we already have
2217                  * a lock we must pass LOCKAGAIN to prevent unexpected
2218                  * blocking (we don't want to block on a second shared
2219                  * ref if an exclusive lock is pending)
2220                  */
2221                 if (parent->data->ipdata.meta.op_flags &
2222                     HAMMER2_OPFLAG_DIRECTDATA) {
2223                         if (flags & HAMMER2_LOOKUP_NODIRECT) {
2224                                 chain = NULL;
2225                                 *key_nextp = key_end + 1;
2226                                 goto done;
2227                         }
2228                         hammer2_chain_ref(parent);
2229                         if ((flags & HAMMER2_LOOKUP_NOLOCK) == 0)
2230                                 hammer2_chain_lock(parent,
2231                                                    how_always |
2232                                                     HAMMER2_RESOLVE_LOCKAGAIN);
2233                         *key_nextp = key_end + 1;
2234                         return (parent);
2235                 }
2236                 base = &parent->data->ipdata.u.blockset.blockref[0];
2237                 count = HAMMER2_SET_COUNT;
2238                 break;
2239         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2240         case HAMMER2_BREF_TYPE_INDIRECT:
2241                 /*
2242                  * Handle MATCHIND on the parent
2243                  */
2244                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
2245                         scan_beg = parent->bref.key;
2246                         scan_end = scan_beg +
2247                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2248                         if (key_beg == scan_beg && key_end == scan_end) {
2249                                 chain = parent;
2250                                 hammer2_chain_ref(chain);
2251                                 hammer2_chain_lock(chain, how_maybe);
2252                                 *key_nextp = scan_end + 1;
2253                                 goto done;
2254                         }
2255                 }
2256
2257                 /*
2258                  * Optimize indirect blocks in the INITIAL state to avoid
2259                  * I/O.
2260                  */
2261                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2262                         base = NULL;
2263                 } else {
2264                         if (parent->data == NULL) {
2265                                 kprintf("parent->data is NULL %p\n", parent);
2266                                 while (1)
2267                                         tsleep(parent, 0, "xxx", 0);
2268                         }
2269                         base = &parent->data->npdata[0];
2270                 }
2271                 count = parent->bytes / sizeof(hammer2_blockref_t);
2272                 break;
2273         case HAMMER2_BREF_TYPE_VOLUME:
2274                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2275                 count = HAMMER2_SET_COUNT;
2276                 break;
2277         case HAMMER2_BREF_TYPE_FREEMAP:
2278                 base = &parent->data->blkset.blockref[0];
2279                 count = HAMMER2_SET_COUNT;
2280                 break;
2281         default:
2282                 kprintf("hammer2_chain_lookup: unrecognized "
2283                         "blockref(B) type: %d",
2284                         parent->bref.type);
2285                 while (1)
2286                         tsleep(&base, 0, "dead", 0);
2287                 panic("hammer2_chain_lookup: unrecognized "
2288                       "blockref(B) type: %d",
2289                       parent->bref.type);
2290                 base = NULL;    /* safety */
2291                 count = 0;      /* safety */
2292         }
2293         TIMER(10);
2294
2295         /*
2296          * Merged scan to find next candidate.
2297          *
2298          * hammer2_base_*() functions require the parent->core.live_* fields
2299          * to be synchronized.
2300          *
2301          * We need to hold the spinlock to access the block array and RB tree
2302          * and to interlock chain creation.
2303          */
2304         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2305                 hammer2_chain_countbrefs(parent, base, count);
2306
2307         TIMER(11);
2308
2309         /*
2310          * Combined search
2311          */
2312         hammer2_spin_ex(&parent->core.spin);
2313         chain = hammer2_combined_find(parent, base, count,
2314                                       cache_indexp, key_nextp,
2315                                       key_beg, key_end,
2316                                       &bref);
2317         generation = parent->core.generation;
2318
2319         TIMER(12);
2320
2321         /*
2322          * Exhausted parent chain, iterate.
2323          */
2324         if (bref == NULL) {
2325                 TIMER(13);
2326                 hammer2_spin_unex(&parent->core.spin);
2327                 if (key_beg == key_end) /* short cut single-key case */
2328                         return (NULL);
2329
2330                 /*
2331                  * Stop if we reached the end of the iteration.
2332                  */
2333                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2334                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2335                         return (NULL);
2336                 }
2337
2338                 /*
2339                  * Calculate next key, stop if we reached the end of the
2340                  * iteration, otherwise go up one level and loop.
2341                  */
2342                 key_beg = parent->bref.key +
2343                           ((hammer2_key_t)1 << parent->bref.keybits);
2344                 if (key_beg == 0 || key_beg > key_end)
2345                         return (NULL);
2346                 parent = hammer2_chain_getparent(parentp, how_maybe);
2347                 goto again;
2348         }
2349
2350         /*
2351          * Selected from blockref or in-memory chain.
2352          */
2353         if (chain == NULL) {
2354                 TIMER(14);
2355                 bcopy = *bref;
2356                 hammer2_spin_unex(&parent->core.spin);
2357                 chain = hammer2_chain_get(parent, generation,
2358                                           &bcopy);
2359                 if (chain == NULL) {
2360                         /*
2361                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2362                                 parent, key_beg, key_end);
2363                         */
2364                         goto again;
2365                 }
2366                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2367                         hammer2_chain_drop(chain);
2368                         goto again;
2369                 }
2370         } else {
2371                 TIMER(15);
2372                 hammer2_chain_ref(chain);
2373                 hammer2_spin_unex(&parent->core.spin);
2374         }
2375
2376         TIMER(16);
2377         /*
2378          * chain is referenced but not locked.  We must lock the chain
2379          * to obtain definitive state.
2380          */
2381         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2382             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2383                 hammer2_chain_lock(chain, how_maybe);
2384         } else {
2385                 hammer2_chain_lock(chain, how);
2386         }
2387         KKASSERT(chain->parent == parent);
2388         TIMER(17);
2389
2390         /*
2391          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2392          *
2393          * NOTE: Chain's key range is not relevant as there might be
2394          *       one-offs within the range that are not deleted.
2395          *
2396          * NOTE: Lookups can race delete-duplicate because
2397          *       delete-duplicate does not lock the parent's core
2398          *       (they just use the spinlock on the core).
2399          */
2400         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2401                 kprintf("skip deleted chain %016jx.%02x key=%016jx\n",
2402                         chain->bref.data_off, chain->bref.type,
2403                         chain->bref.key);
2404                 hammer2_chain_unlock(chain);
2405                 hammer2_chain_drop(chain);
2406                 key_beg = *key_nextp;
2407                 if (key_beg == 0 || key_beg > key_end)
2408                         return(NULL);
2409                 goto again;
2410         }
2411         TIMER(18);
2412
2413         /*
2414          * If the chain element is an indirect block it becomes the new
2415          * parent and we loop on it.  We must maintain our top-down locks
2416          * to prevent the flusher from interfering (i.e. doing a
2417          * delete-duplicate and leaving us recursing down a deleted chain).
2418          *
2419          * The parent always has to be locked with at least RESOLVE_MAYBE
2420          * so we can access its data.  It might need a fixup if the caller
2421          * passed incompatible flags.  Be careful not to cause a deadlock
2422          * as a data-load requires an exclusive lock.
2423          *
2424          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2425          * range is within the requested key range we return the indirect
2426          * block and do NOT loop.  This is usually only used to acquire
2427          * freemap nodes.
2428          */
2429         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2430             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2431                 hammer2_chain_unlock(parent);
2432                 hammer2_chain_drop(parent);
2433                 *parentp = parent = chain;
2434                 goto again;
2435         }
2436         TIMER(19);
2437 done:
2438         /*
2439          * All done, return the chain.
2440          *
2441          * If the caller does not want a locked chain, replace the lock with
2442          * a ref.  Perhaps this can eventually be optimized to not obtain the
2443          * lock in the first place for situations where the data does not
2444          * need to be resolved.
2445          */
2446         if (chain) {
2447                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2448                         hammer2_chain_unlock(chain);
2449         }
2450         TIMER(20);
2451
2452         return (chain);
2453 }
2454
2455 /*
2456  * After having issued a lookup we can iterate all matching keys.
2457  *
2458  * If chain is non-NULL we continue the iteration from just after it's index.
2459  *
2460  * If chain is NULL we assume the parent was exhausted and continue the
2461  * iteration at the next parent.
2462  *
2463  * If a fatal error occurs (typically an I/O error), a dummy chain is
2464  * returned with chain->error and error-identifying information set.  This
2465  * chain will assert if you try to do anything fancy with it.
2466  *
2467  * XXX Depending on where the error occurs we should allow continued iteration.
2468  *
2469  * parent must be locked on entry and remains locked throughout.  chain's
2470  * lock status must match flags.  Chain is always at least referenced.
2471  *
2472  * WARNING!  The MATCHIND flag does not apply to this function.
2473  */
2474 hammer2_chain_t *
2475 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2476                    hammer2_key_t *key_nextp,
2477                    hammer2_key_t key_beg, hammer2_key_t key_end,
2478                    int *cache_indexp, int flags)
2479 {
2480         hammer2_chain_t *parent;
2481         int how_maybe;
2482
2483         /*
2484          * Calculate locking flags for upward recursion.
2485          */
2486         how_maybe = HAMMER2_RESOLVE_MAYBE;
2487         if (flags & HAMMER2_LOOKUP_SHARED)
2488                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2489
2490         parent = *parentp;
2491
2492         /*
2493          * Calculate the next index and recalculate the parent if necessary.
2494          */
2495         if (chain) {
2496                 key_beg = chain->bref.key +
2497                           ((hammer2_key_t)1 << chain->bref.keybits);
2498                 if ((flags & (HAMMER2_LOOKUP_NOLOCK |
2499                               HAMMER2_LOOKUP_NOUNLOCK)) == 0) {
2500                         hammer2_chain_unlock(chain);
2501                 }
2502                 hammer2_chain_drop(chain);
2503
2504                 /*
2505                  * chain invalid past this point, but we can still do a
2506                  * pointer comparison w/parent.
2507                  *
2508                  * Any scan where the lookup returned degenerate data embedded
2509                  * in the inode has an invalid index and must terminate.
2510                  */
2511                 if (chain == parent)
2512                         return(NULL);
2513                 if (key_beg == 0 || key_beg > key_end)
2514                         return(NULL);
2515                 chain = NULL;
2516         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2517                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2518                 /*
2519                  * We reached the end of the iteration.
2520                  */
2521                 return (NULL);
2522         } else {
2523                 /*
2524                  * Continue iteration with next parent unless the current
2525                  * parent covers the range.
2526                  *
2527                  * (This also handles the case of a deleted, empty indirect
2528                  * node).
2529                  */
2530                 key_beg = parent->bref.key +
2531                           ((hammer2_key_t)1 << parent->bref.keybits);
2532                 if (key_beg == 0 || key_beg > key_end)
2533                         return (NULL);
2534                 parent = hammer2_chain_getparent(parentp, how_maybe);
2535         }
2536
2537         /*
2538          * And execute
2539          */
2540         return (hammer2_chain_lookup(parentp, key_nextp,
2541                                      key_beg, key_end,
2542                                      cache_indexp, flags));
2543 }
2544
2545 /*
2546  * The raw scan function is similar to lookup/next but does not seek to a key.
2547  * Blockrefs are iterated via first_bref = (parent, NULL) and
2548  * next_chain = (parent, bref).
2549  *
2550  * The passed-in parent must be locked and its data resolved.  The function
2551  * nominally returns a locked and referenced *chainp != NULL for chains
2552  * the caller might need to recurse on (and will dipose of any *chainp passed
2553  * in).  The caller must check the chain->bref.type either way.
2554  *
2555  * *chainp is not set for leaf elements.
2556  *
2557  * This function takes a pointer to a stack-based bref structure whos
2558  * contents is updated for each iteration.  The same pointer is returned,
2559  * or NULL when the iteration is complete.  *firstp must be set to 1 for
2560  * the first ieration.  This function will set it to 0.
2561  */
2562 hammer2_blockref_t *
2563 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t **chainp,
2564                    hammer2_blockref_t *bref, int *firstp,
2565                    int *cache_indexp, int flags)
2566 {
2567         hammer2_dev_t *hmp;
2568         hammer2_blockref_t *base;
2569         hammer2_blockref_t *bref_ptr;
2570         hammer2_key_t key;
2571         hammer2_key_t next_key;
2572         hammer2_chain_t *chain = NULL;
2573         int count = 0;
2574         int how_always = HAMMER2_RESOLVE_ALWAYS;
2575         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2576         int how;
2577         int generation;
2578         int maxloops = 300000;
2579
2580         hmp = parent->hmp;
2581
2582         /*
2583          * Scan flags borrowed from lookup.
2584          */
2585         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2586                 how_maybe = how_always;
2587                 how = HAMMER2_RESOLVE_ALWAYS;
2588         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2589                 how = HAMMER2_RESOLVE_NEVER;
2590         } else {
2591                 how = HAMMER2_RESOLVE_MAYBE;
2592         }
2593         if (flags & HAMMER2_LOOKUP_SHARED) {
2594                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2595                 how_always |= HAMMER2_RESOLVE_SHARED;
2596                 how |= HAMMER2_RESOLVE_SHARED;
2597         }
2598
2599         /*
2600          * Calculate key to locate first/next element, unlocking the previous
2601          * element as we go.  Be careful, the key calculation can overflow.
2602          *
2603          * (also reset bref to NULL)
2604          */
2605         if (*firstp) {
2606                 key = 0;
2607                 *firstp = 0;
2608         } else {
2609                 key = bref->key + ((hammer2_key_t)1 << bref->keybits);
2610                 if ((chain = *chainp) != NULL) {
2611                         *chainp = NULL;
2612                         hammer2_chain_unlock(chain);
2613                         hammer2_chain_drop(chain);
2614                         chain = NULL;
2615                 }
2616                 if (key == 0) {
2617                         bref = NULL;
2618                         goto done;
2619                 }
2620         }
2621
2622 again:
2623         KKASSERT(parent->error == 0);   /* XXX case not handled yet */
2624         if (--maxloops == 0)
2625                 panic("hammer2_chain_scan: maxloops");
2626         /*
2627          * Locate the blockref array.  Currently we do a fully associative
2628          * search through the array.
2629          */
2630         switch(parent->bref.type) {
2631         case HAMMER2_BREF_TYPE_INODE:
2632                 /*
2633                  * An inode with embedded data has no sub-chains.
2634                  *
2635                  * WARNING! Bulk scan code may pass a static chain marked
2636                  *          as BREF_TYPE_INODE with a copy of the volume
2637                  *          root blockset to snapshot the volume.
2638                  */
2639                 if (parent->data->ipdata.meta.op_flags &
2640                     HAMMER2_OPFLAG_DIRECTDATA) {
2641                         bref = NULL;
2642                         goto done;
2643                 }
2644                 base = &parent->data->ipdata.u.blockset.blockref[0];
2645                 count = HAMMER2_SET_COUNT;
2646                 break;
2647         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2648         case HAMMER2_BREF_TYPE_INDIRECT:
2649                 /*
2650                  * Optimize indirect blocks in the INITIAL state to avoid
2651                  * I/O.
2652                  */
2653                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2654                         base = NULL;
2655                 } else {
2656                         if (parent->data == NULL)
2657                                 panic("parent->data is NULL");
2658                         base = &parent->data->npdata[0];
2659                 }
2660                 count = parent->bytes / sizeof(hammer2_blockref_t);
2661                 break;
2662         case HAMMER2_BREF_TYPE_VOLUME:
2663                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2664                 count = HAMMER2_SET_COUNT;
2665                 break;
2666         case HAMMER2_BREF_TYPE_FREEMAP:
2667                 base = &parent->data->blkset.blockref[0];
2668                 count = HAMMER2_SET_COUNT;
2669                 break;
2670         default:
2671                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2672                       parent->bref.type);
2673                 base = NULL;    /* safety */
2674                 count = 0;      /* safety */
2675         }
2676
2677         /*
2678          * Merged scan to find next candidate.
2679          *
2680          * hammer2_base_*() functions require the parent->core.live_* fields
2681          * to be synchronized.
2682          *
2683          * We need to hold the spinlock to access the block array and RB tree
2684          * and to interlock chain creation.
2685          */
2686         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
2687                 hammer2_chain_countbrefs(parent, base, count);
2688
2689         next_key = 0;
2690         bref_ptr = NULL;
2691         hammer2_spin_ex(&parent->core.spin);
2692         chain = hammer2_combined_find(parent, base, count,
2693                                       cache_indexp, &next_key,
2694                                       key, HAMMER2_KEY_MAX,
2695                                       &bref_ptr);
2696         generation = parent->core.generation;
2697
2698         /*
2699          * Exhausted parent chain, we're done.
2700          */
2701         if (bref_ptr == NULL) {
2702                 hammer2_spin_unex(&parent->core.spin);
2703                 KKASSERT(chain == NULL);
2704                 bref = NULL;
2705                 goto done;
2706         }
2707
2708         /*
2709          * Copy into the supplied stack-based blockref.
2710          */
2711         *bref = *bref_ptr;
2712
2713         /*
2714          * Selected from blockref or in-memory chain.
2715          */
2716         if (chain == NULL) {
2717                 switch(bref->type) {
2718                 case HAMMER2_BREF_TYPE_INODE:
2719                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2720                 case HAMMER2_BREF_TYPE_INDIRECT:
2721                 case HAMMER2_BREF_TYPE_VOLUME:
2722                 case HAMMER2_BREF_TYPE_FREEMAP:
2723                         /*
2724                          * Recursion, always get the chain
2725                          */
2726                         hammer2_spin_unex(&parent->core.spin);
2727                         chain = hammer2_chain_get(parent, generation, bref);
2728                         if (chain == NULL) {
2729                                 kprintf("retry scan parent %p keys %016jx\n",
2730                                         parent, key);
2731                                 goto again;
2732                         }
2733                         if (bcmp(bref, bref_ptr, sizeof(*bref))) {
2734                                 hammer2_chain_drop(chain);
2735                                 chain = NULL;
2736                                 goto again;
2737                         }
2738                         break;
2739                 default:
2740                         /*
2741                          * No recursion, do not waste time instantiating
2742                          * a chain, just iterate using the bref.
2743                          */
2744                         hammer2_spin_unex(&parent->core.spin);
2745                         break;
2746                 }
2747         } else {
2748                 /*
2749                  * Recursion or not we need the chain in order to supply
2750                  * the bref.
2751                  */
2752                 hammer2_chain_ref(chain);
2753                 hammer2_spin_unex(&parent->core.spin);
2754         }
2755
2756         /*
2757          * chain is referenced but not locked.  We must lock the chain
2758          * to obtain definitive state.
2759          */
2760         if (chain)
2761                 hammer2_chain_lock(chain, how);
2762
2763         /*
2764          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2765          *
2766          * NOTE: chain's key range is not relevant as there might be
2767          *       one-offs within the range that are not deleted.
2768          *
2769          * NOTE: XXX this could create problems with scans used in
2770          *       situations other than mount-time recovery.
2771          *
2772          * NOTE: Lookups can race delete-duplicate because
2773          *       delete-duplicate does not lock the parent's core
2774          *       (they just use the spinlock on the core).
2775          */
2776         if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
2777                 hammer2_chain_unlock(chain);
2778                 hammer2_chain_drop(chain);
2779                 chain = NULL;
2780
2781                 key = next_key;
2782                 if (key == 0) {
2783                         bref = NULL;
2784                         goto done;
2785                 }
2786                 goto again;
2787         }
2788
2789 done:
2790         /*
2791          * All done, return the bref or NULL, supply chain if necessary.
2792          */
2793         if (chain)
2794                 *chainp = chain;
2795         return (bref);
2796 }
2797
2798 /*
2799  * Create and return a new hammer2 system memory structure of the specified
2800  * key, type and size and insert it under (*parentp).  This is a full
2801  * insertion, based on the supplied key/keybits, and may involve creating
2802  * indirect blocks and moving other chains around via delete/duplicate.
2803  *
2804  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2805  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2806  * FULL.  This typically means that the caller is creating the chain after
2807  * doing a hammer2_chain_lookup().
2808  *
2809  * (*parentp) must be exclusive locked and may be replaced on return
2810  * depending on how much work the function had to do.
2811  *
2812  * (*parentp) must not be errored or this function will assert.
2813  *
2814  * (*chainp) usually starts out NULL and returns the newly created chain,
2815  * but if the caller desires the caller may allocate a disconnected chain
2816  * and pass it in instead.
2817  *
2818  * This function should NOT be used to insert INDIRECT blocks.  It is
2819  * typically used to create/insert inodes and data blocks.
2820  *
2821  * Caller must pass-in an exclusively locked parent the new chain is to
2822  * be inserted under, and optionally pass-in a disconnected, exclusively
2823  * locked chain to insert (else we create a new chain).  The function will
2824  * adjust (*parentp) as necessary, create or connect the chain, and
2825  * return an exclusively locked chain in *chainp.
2826  *
2827  * When creating a PFSROOT inode under the super-root, pmp is typically NULL
2828  * and will be reassigned.
2829  */
2830 int
2831 hammer2_chain_create(hammer2_chain_t **parentp, hammer2_chain_t **chainp,
2832                      hammer2_pfs_t *pmp, int methods,
2833                      hammer2_key_t key, int keybits, int type, size_t bytes,
2834                      hammer2_tid_t mtid, hammer2_off_t dedup_off, int flags)
2835 {
2836         hammer2_dev_t *hmp;
2837         hammer2_chain_t *chain;
2838         hammer2_chain_t *parent;
2839         hammer2_blockref_t *base;
2840         hammer2_blockref_t dummy;
2841         int allocated = 0;
2842         int error = 0;
2843         int count;
2844         int maxloops = 300000;
2845
2846         /*
2847          * Topology may be crossing a PFS boundary.
2848          */
2849         parent = *parentp;
2850         KKASSERT(hammer2_mtx_owned(&parent->lock));
2851         KKASSERT(parent->error == 0);
2852         hmp = parent->hmp;
2853         chain = *chainp;
2854
2855         if (chain == NULL) {
2856                 /*
2857                  * First allocate media space and construct the dummy bref,
2858                  * then allocate the in-memory chain structure.  Set the
2859                  * INITIAL flag for fresh chains which do not have embedded
2860                  * data.
2861                  *
2862                  * XXX for now set the check mode of the child based on
2863                  *     the parent or, if the parent is an inode, the
2864                  *     specification in the inode.
2865                  */
2866                 bzero(&dummy, sizeof(dummy));
2867                 dummy.type = type;
2868                 dummy.key = key;
2869                 dummy.keybits = keybits;
2870                 dummy.data_off = hammer2_getradix(bytes);
2871
2872                 /*
2873                  * Inherit methods from parent by default.  Primarily used
2874                  * for BREF_TYPE_DATA.  Non-data types *must* be set to
2875                  * a non-NONE check algorithm.
2876                  */
2877                 if (methods == -1)
2878                         dummy.methods = parent->bref.methods;
2879                 else
2880                         dummy.methods = (uint8_t)methods;
2881
2882                 if (type != HAMMER2_BREF_TYPE_DATA &&
2883                     HAMMER2_DEC_CHECK(dummy.methods) == HAMMER2_CHECK_NONE) {
2884                         dummy.methods |=
2885                                 HAMMER2_ENC_CHECK(HAMMER2_CHECK_DEFAULT);
2886                 }
2887
2888                 chain = hammer2_chain_alloc(hmp, pmp, &dummy);
2889
2890                 /*
2891                  * Lock the chain manually, chain_lock will load the chain
2892                  * which we do NOT want to do.  (note: chain->refs is set
2893                  * to 1 by chain_alloc() for us, but lockcnt is not).
2894                  */
2895                 chain->lockcnt = 1;
2896                 hammer2_mtx_ex(&chain->lock);
2897                 allocated = 1;
2898                 ++curthread->td_tracker;
2899
2900                 /*
2901                  * Set INITIAL to optimize I/O.  The flag will generally be
2902                  * processed when we call hammer2_chain_modify().
2903                  *
2904                  * Recalculate bytes to reflect the actual media block
2905                  * allocation.  Handle special case radix 0 == 0 bytes.
2906                  */
2907                 bytes = (size_t)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2908                 if (bytes)
2909                         bytes = (hammer2_off_t)1 << bytes;
2910                 chain->bytes = bytes;
2911
2912                 switch(type) {
2913                 case HAMMER2_BREF_TYPE_VOLUME:
2914                 case HAMMER2_BREF_TYPE_FREEMAP:
2915                         panic("hammer2_chain_create: called with volume type");
2916                         break;
2917                 case HAMMER2_BREF_TYPE_INDIRECT:
2918                         panic("hammer2_chain_create: cannot be used to"
2919                               "create indirect block");
2920                         break;
2921                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2922                         panic("hammer2_chain_create: cannot be used to"
2923                               "create freemap root or node");
2924                         break;
2925                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2926                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2927                         /* fall through */
2928                 case HAMMER2_BREF_TYPE_DIRENT:
2929                 case HAMMER2_BREF_TYPE_INODE:
2930                 case HAMMER2_BREF_TYPE_DATA:
2931                 default:
2932                         /*
2933                          * leave chain->data NULL, set INITIAL
2934                          */
2935                         KKASSERT(chain->data == NULL);
2936                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2937                         break;
2938                 }
2939         } else {
2940                 /*
2941                  * We are reattaching a previously deleted chain, possibly
2942                  * under a new parent and possibly with a new key/keybits.
2943                  * The chain does not have to be in a modified state.  The
2944                  * UPDATE flag will be set later on in this routine.
2945                  *
2946                  * Do NOT mess with the current state of the INITIAL flag.
2947                  */
2948                 chain->bref.key = key;
2949                 chain->bref.keybits = keybits;
2950                 if (chain->flags & HAMMER2_CHAIN_DELETED)
2951                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2952                 KKASSERT(chain->parent == NULL);
2953         }
2954         if (flags & HAMMER2_INSERT_PFSROOT)
2955                 chain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
2956         else
2957                 chain->bref.flags &= ~HAMMER2_BREF_FLAG_PFSROOT;
2958
2959         /*
2960          * Calculate how many entries we have in the blockref array and
2961          * determine if an indirect block is required.
2962          */
2963 again:
2964         if (--maxloops == 0)
2965                 panic("hammer2_chain_create: maxloops");
2966
2967         switch(parent->bref.type) {
2968         case HAMMER2_BREF_TYPE_INODE:
2969                 if ((parent->data->ipdata.meta.op_flags &
2970                      HAMMER2_OPFLAG_DIRECTDATA) != 0) {
2971                         kprintf("hammer2: parent set for direct-data! "
2972                                 "pkey=%016jx ckey=%016jx\n",
2973                                 parent->bref.key,
2974                                 chain->bref.key);
2975                 }
2976                 KKASSERT((parent->data->ipdata.meta.op_flags &
2977                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2978                 KKASSERT(parent->data != NULL);
2979                 base = &parent->data->ipdata.u.blockset.blockref[0];
2980                 count = HAMMER2_SET_COUNT;
2981                 break;
2982         case HAMMER2_BREF_TYPE_INDIRECT:
2983         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2984                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2985                         base = NULL;
2986                 else
2987                         base = &parent->data->npdata[0];
2988                 count = parent->bytes / sizeof(hammer2_blockref_t);
2989                 break;
2990         case HAMMER2_BREF_TYPE_VOLUME:
2991                 KKASSERT(parent->data != NULL);
2992                 base = &parent->data->voldata.sroot_blockset.blockref[0];
2993                 count = HAMMER2_SET_COUNT;
2994                 break;
2995         case HAMMER2_BREF_TYPE_FREEMAP:
2996                 KKASSERT(parent->data != NULL);
2997                 base = &parent->data->blkset.blockref[0];
2998                 count = HAMMER2_SET_COUNT;
2999                 break;
3000         default:
3001                 panic("hammer2_chain_create: unrecognized blockref type: %d",
3002                       parent->bref.type);
3003                 base = NULL;
3004                 count = 0;
3005                 break;
3006         }
3007
3008         /*
3009          * Make sure we've counted the brefs
3010          */
3011         if ((parent->flags & HAMMER2_CHAIN_COUNTEDBREFS) == 0)
3012                 hammer2_chain_countbrefs(parent, base, count);
3013
3014         KASSERT(parent->core.live_count >= 0 &&
3015                 parent->core.live_count <= count,
3016                 ("bad live_count %d/%d (%02x, %d)",
3017                         parent->core.live_count, count,
3018                         parent->bref.type, parent->bytes));
3019
3020         /*
3021          * If no free blockref could be found we must create an indirect
3022          * block and move a number of blockrefs into it.  With the parent
3023          * locked we can safely lock each child in order to delete+duplicate
3024          * it without causing a deadlock.
3025          *
3026          * This may return the new indirect block or the old parent depending
3027          * on where the key falls.  NULL is returned on error.
3028          */
3029         if (parent->core.live_count == count) {
3030                 hammer2_chain_t *nparent;
3031
3032                 nparent = hammer2_chain_create_indirect(parent, key, keybits,
3033                                                         mtid, type, &error);
3034                 if (nparent == NULL) {
3035                         if (allocated)
3036                                 hammer2_chain_drop(chain);
3037                         chain = NULL;
3038                         goto done;
3039                 }
3040                 if (parent != nparent) {
3041                         hammer2_chain_unlock(parent);
3042                         hammer2_chain_drop(parent);
3043                         parent = *parentp = nparent;
3044                 }
3045                 goto again;
3046         }
3047
3048         if (chain->flags & HAMMER2_CHAIN_DELETED)
3049                 kprintf("Inserting deleted chain @%016jx\n",
3050                         chain->bref.key);
3051
3052         /*
3053          * Link the chain into its parent.
3054          */
3055         if (chain->parent != NULL)
3056                 panic("hammer2: hammer2_chain_create: chain already connected");
3057         KKASSERT(chain->parent == NULL);
3058         hammer2_chain_insert(parent, chain,
3059                              HAMMER2_CHAIN_INSERT_SPIN |
3060                              HAMMER2_CHAIN_INSERT_LIVE,
3061                              0);
3062
3063         if (allocated) {
3064                 /*
3065                  * Mark the newly created chain modified.  This will cause
3066                  * UPDATE to be set and process the INITIAL flag.
3067                  *
3068                  * Device buffers are not instantiated for DATA elements
3069                  * as these are handled by logical buffers.
3070                  *
3071                  * Indirect and freemap node indirect blocks are handled
3072                  * by hammer2_chain_create_indirect() and not by this
3073                  * function.
3074                  *
3075                  * Data for all other bref types is expected to be
3076                  * instantiated (INODE, LEAF).
3077                  */
3078                 switch(chain->bref.type) {
3079                 case HAMMER2_BREF_TYPE_DATA:
3080                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3081                 case HAMMER2_BREF_TYPE_DIRENT:
3082                 case HAMMER2_BREF_TYPE_INODE:
3083                         hammer2_chain_modify(chain, mtid, dedup_off,
3084                                              HAMMER2_MODIFY_OPTDATA);
3085                         break;
3086                 default:
3087                         /*
3088                          * Remaining types are not supported by this function.
3089                          * In particular, INDIRECT and LEAF_NODE types are
3090                          * handled by create_indirect().
3091                          */
3092                         panic("hammer2_chain_create: bad type: %d",
3093                               chain->bref.type);
3094                         /* NOT REACHED */
3095                         break;
3096                 }
3097         } else {
3098                 /*
3099                  * When reconnecting a chain we must set UPDATE and
3100                  * setflush so the flush recognizes that it must update
3101                  * the bref in the parent.
3102                  */
3103                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0)
3104                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
3105         }
3106
3107         /*
3108          * We must setflush(parent) to ensure that it recurses through to
3109          * chain.  setflush(chain) might not work because ONFLUSH is possibly
3110          * already set in the chain (so it won't recurse up to set it in the
3111          * parent).
3112          */
3113         hammer2_chain_setflush(parent);
3114
3115 done:
3116         *chainp = chain;
3117
3118         return (error);
3119 }
3120
3121 /*
3122  * Move the chain from its old parent to a new parent.  The chain must have
3123  * already been deleted or already disconnected (or never associated) with
3124  * a parent.  The chain is reassociated with the new parent and the deleted
3125  * flag will be cleared (no longer deleted).  The chain's modification state
3126  * is not altered.
3127  *
3128  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
3129  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
3130  * FULL.  This typically means that the caller is creating the chain after
3131  * doing a hammer2_chain_lookup().
3132  *
3133  * A non-NULL bref is typically passed when key and keybits must be overridden.
3134  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
3135  * from a passed-in bref and uses the old chain's bref for everything else.
3136  *
3137  * Neither (parent) or (chain) can be errored.
3138  *
3139  * If (parent) is non-NULL then the chain is inserted under the parent.
3140  *
3141  * If (parent) is NULL then the newly duplicated chain is not inserted
3142  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
3143  * passing into hammer2_chain_create() after this function returns).
3144  *
3145  * WARNING! This function calls create which means it can insert indirect
3146  *          blocks.  This can cause other unrelated chains in the parent to
3147  *          be moved to a newly inserted indirect block in addition to the
3148  *          specific chain.
3149  */
3150 void
3151 hammer2_chain_rename(hammer2_blockref_t *bref,
3152                      hammer2_chain_t **parentp, hammer2_chain_t *chain,
3153                      hammer2_tid_t mtid, int flags)
3154 {
3155         hammer2_dev_t *hmp;
3156         hammer2_chain_t *parent;
3157         size_t bytes;
3158
3159         /*
3160          * WARNING!  We should never resolve DATA to device buffers
3161          *           (XXX allow it if the caller did?), and since
3162          *           we currently do not have the logical buffer cache
3163          *           buffer in-hand to fix its cached physical offset
3164          *           we also force the modify code to not COW it. XXX
3165          */
3166         hmp = chain->hmp;
3167         KKASSERT(chain->parent == NULL);
3168         KKASSERT(chain->error == 0);
3169
3170         /*
3171          * Now create a duplicate of the chain structure, associating
3172          * it with the same core, making it the same size, pointing it
3173          * to the same bref (the same media block).
3174          *
3175          * NOTE: Handle special radix == 0 case (means 0 bytes).
3176          */
3177         if (bref == NULL)
3178                 bref = &chain->bref;
3179         bytes = (size_t)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
3180         if (bytes)
3181                 bytes = (hammer2_off_t)1 << bytes;
3182
3183         /*
3184          * If parent is not NULL the duplicated chain will be entered under
3185          * the parent and the UPDATE bit set to tell flush to update
3186          * the blockref.
3187          *
3188          * We must setflush(parent) to ensure that it recurses through to
3189          * chain.  setflush(chain) might not work because ONFLUSH is possibly
3190          * already set in the chain (so it won't recurse up to set it in the
3191          * parent).
3192          *
3193          * Having both chains locked is extremely important for atomicy.
3194          */
3195         if (parentp && (parent = *parentp) != NULL) {
3196                 KKASSERT(hammer2_mtx_owned(&parent->lock));
3197                 KKASSERT(parent->refs > 0);
3198                 KKASSERT(parent->error == 0);
3199
3200                 hammer2_chain_create(parentp, &chain,
3201                                      chain->pmp, HAMMER2_METH_DEFAULT,
3202                                      bref->key, bref->keybits, bref->type,
3203                                      chain->bytes, mtid, 0, flags);
3204                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
3205                 hammer2_chain_setflush(*parentp);
3206         }
3207 }
3208
3209 /*
3210  * Helper function for deleting chains.
3211  *
3212  * The chain is removed from the live view (the RBTREE) as well as the parent's
3213  * blockmap.  Both chain and its parent must be locked.
3214  *
3215  * parent may not be errored.  chain can be errored.
3216  */
3217 static void
3218 _hammer2_chain_delete_helper(hammer2_chain_t *parent, hammer2_chain_t *chain,
3219                              hammer2_tid_t mtid, int flags)
3220 {
3221         hammer2_dev_t *hmp;
3222
3223         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
3224                                   HAMMER2_CHAIN_FICTITIOUS)) == 0);
3225         KKASSERT(chain->parent == parent);
3226         hmp = chain->hmp;
3227
3228         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
3229                 /*
3230                  * Chain is blockmapped, so there must be a parent.
3231                  * Atomically remove the chain from the parent and remove
3232                  * the blockmap entry.  The parent must be set modified
3233                  * to remove the blockmap entry.
3234                  */
3235                 hammer2_blockref_t *base;
3236                 int count;
3237
3238                 KKASSERT(parent != NULL);
3239                 KKASSERT(parent->error == 0);
3240                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
3241                 hammer2_chain_modify(parent, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3242
3243                 /*
3244                  * Calculate blockmap pointer
3245                  */
3246                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
3247                 hammer2_spin_ex(&parent->core.spin);
3248
3249                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3250                 atomic_add_int(&parent->core.live_count, -1);
3251                 ++parent->core.generation;
3252                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3253                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3254                 --parent->core.chain_count;
3255                 chain->parent = NULL;
3256
3257                 switch(parent->bref.type) {
3258                 case HAMMER2_BREF_TYPE_INODE:
3259                         /*
3260                          * Access the inode's block array.  However, there
3261                          * is no block array if the inode is flagged
3262                          * DIRECTDATA.
3263                          */
3264                         if (parent->data &&
3265                             (parent->data->ipdata.meta.op_flags &
3266                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
3267                                 base =
3268                                    &parent->data->ipdata.u.blockset.blockref[0];
3269                         } else {
3270                                 base = NULL;
3271                         }
3272                         count = HAMMER2_SET_COUNT;
3273                         break;
3274                 case HAMMER2_BREF_TYPE_INDIRECT:
3275                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3276                         if (parent->data)
3277                                 base = &parent->data->npdata[0];
3278                         else
3279                                 base = NULL;
3280                         count = parent->bytes / sizeof(hammer2_blockref_t);
3281                         break;
3282                 case HAMMER2_BREF_TYPE_VOLUME:
3283                         base = &parent->data->voldata.
3284                                         sroot_blockset.blockref[0];
3285                         count = HAMMER2_SET_COUNT;
3286                         break;
3287                 case HAMMER2_BREF_TYPE_FREEMAP:
3288                         base = &parent->data->blkset.blockref[0];
3289                         count = HAMMER2_SET_COUNT;
3290                         break;
3291                 default:
3292                         base = NULL;
3293                         count = 0;
3294                         panic("hammer2_flush_pass2: "
3295                               "unrecognized blockref type: %d",
3296                               parent->bref.type);
3297                 }
3298
3299                 /*
3300                  * delete blockmapped chain from its parent.
3301                  *
3302                  * The parent is not affected by any statistics in chain
3303                  * which are pending synchronization.  That is, there is
3304                  * nothing to undo in the parent since they have not yet
3305                  * been incorporated into the parent.
3306                  *
3307                  * The parent is affected by statistics stored in inodes.
3308                  * Those have already been synchronized, so they must be
3309                  * undone.  XXX split update possible w/delete in middle?
3310                  */
3311                 if (base) {
3312                         int cache_index = -1;
3313                         hammer2_base_delete(parent, base, count,
3314                                             &cache_index, chain);
3315                 }
3316                 hammer2_spin_unex(&parent->core.spin);
3317         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
3318                 /*
3319                  * Chain is not blockmapped but a parent is present.
3320                  * Atomically remove the chain from the parent.  There is
3321                  * no blockmap entry to remove.
3322                  *
3323                  * Because chain was associated with a parent but not
3324                  * synchronized, the chain's *_count_up fields contain
3325                  * inode adjustment statistics which must be undone.
3326                  */
3327                 hammer2_spin_ex(&parent->core.spin);
3328                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3329                 atomic_add_int(&parent->core.live_count, -1);
3330                 ++parent->core.generation;
3331                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
3332                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
3333                 --parent->core.chain_count;
3334                 chain->parent = NULL;
3335                 hammer2_spin_unex(&parent->core.spin);
3336         } else {
3337                 /*
3338                  * Chain is not blockmapped and has no parent.  This
3339                  * is a degenerate case.
3340                  */
3341                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
3342         }
3343 }
3344
3345 /*
3346  * Create an indirect block that covers one or more of the elements in the
3347  * current parent.  Either returns the existing parent with no locking or
3348  * ref changes or returns the new indirect block locked and referenced
3349  * and leaving the original parent lock/ref intact as well.
3350  *
3351  * If an error occurs, NULL is returned and *errorp is set to the error.
3352  *
3353  * The returned chain depends on where the specified key falls.
3354  *
3355  * The key/keybits for the indirect mode only needs to follow three rules:
3356  *
3357  * (1) That all elements underneath it fit within its key space and
3358  *
3359  * (2) That all elements outside it are outside its key space.
3360  *
3361  * (3) When creating the new indirect block any elements in the current
3362  *     parent that fit within the new indirect block's keyspace must be
3363  *     moved into the new indirect block.
3364  *
3365  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3366  *     keyspace the the current parent, but lookup/iteration rules will
3367  *     ensure (and must ensure) that rule (2) for all parents leading up
3368  *     to the nearest inode or the root volume header is adhered to.  This
3369  *     is accomplished by always recursing through matching keyspaces in
3370  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3371  *
3372  * The current implementation calculates the current worst-case keyspace by
3373  * iterating the current parent and then divides it into two halves, choosing
3374  * whichever half has the most elements (not necessarily the half containing
3375  * the requested key).
3376  *
3377  * We can also opt to use the half with the least number of elements.  This
3378  * causes lower-numbered keys (aka logical file offsets) to recurse through
3379  * fewer indirect blocks and higher-numbered keys to recurse through more.
3380  * This also has the risk of not moving enough elements to the new indirect
3381  * block and being forced to create several indirect blocks before the element
3382  * can be inserted.
3383  *
3384  * Must be called with an exclusively locked parent.
3385  */
3386 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3387                                 hammer2_key_t *keyp, int keybits,
3388                                 hammer2_blockref_t *base, int count);
3389 static int hammer2_chain_indkey_file(hammer2_chain_t *parent,
3390                                 hammer2_key_t *keyp, int keybits,
3391                                 hammer2_blockref_t *base, int count,
3392                                 int ncount);
3393 static int hammer2_chain_indkey_dir(hammer2_chain_t *parent,
3394                                 hammer2_key_t *keyp, int keybits,
3395                                 hammer2_blockref_t *base, int count,
3396                                 int ncount);
3397 static
3398 hammer2_chain_t *
3399 hammer2_chain_create_indirect(hammer2_chain_t *parent,
3400                               hammer2_key_t create_key, int create_bits,
3401                               hammer2_tid_t mtid, int for_type, int *errorp)
3402 {
3403         hammer2_dev_t *hmp;
3404         hammer2_blockref_t *base;
3405         hammer2_blockref_t *bref;
3406         hammer2_blockref_t bcopy;
3407         hammer2_chain_t *chain;
3408         hammer2_chain_t *ichain;
3409         hammer2_chain_t dummy;
3410         hammer2_key_t key = create_key;
3411         hammer2_key_t key_beg;
3412         hammer2_key_t key_end;
3413         hammer2_key_t key_next;
3414         int keybits = create_bits;
3415         int count;
3416         int ncount;
3417         int nbytes;
3418         int cache_index;
3419         int loops;
3420         int reason;
3421         int generation;
3422         int maxloops = 300000;
3423
3424         /*
3425          * Calculate the base blockref pointer or NULL if the chain
3426          * is known to be empty.  We need to calculate the array count
3427          * for RB lookups either way.
3428          */
3429         hmp = parent->hmp;
3430         *errorp = 0;
3431         KKASSERT(hammer2_mtx_owned(&parent->lock));
3432
3433         /*hammer2_chain_modify(&parent, HAMMER2_MODIFY_OPTDATA);*/
3434         base = hammer2_chain_base_and_count(parent, &count);
3435
3436         /*
3437          * dummy used in later chain allocation (no longer used for lookups).
3438          */
3439         bzero(&dummy, sizeof(dummy));
3440
3441         /*
3442          * How big should our new indirect block be?  It has to be at least
3443          * as large as its parent.
3444          *
3445          * The freemap uses a specific indirect block size.  The number of
3446          * levels are built dynamically and ultimately depend on the size
3447          * volume.  Because freemap blocks are taken from the reserved areas
3448          * of the volume our goal is efficiency (fewer levels) and not so
3449          * much to save disk space.
3450          *
3451          * The first indirect block level for a directory usually uses
3452          * HAMMER2_IND_BYTES_MIN (4KB = 32 directory entries).
3453          * (the 4 entries built-into the inode can handle 4 directory
3454          *  entries)
3455          *
3456          * The first indirect block level for a file usually uses
3457          * HAMMER2_IND_BYTES_NOM (16KB = 128 blockrefs = ~8MB file).
3458          * (the 4 entries built-into the inode can handle a 256KB file).
3459          *
3460          * The first indirect block level down from an inode typically
3461          * uses LBUFSIZE (16384), else it uses PBUFSIZE (65536).
3462          */
3463         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3464             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3465                 nbytes = HAMMER2_FREEMAP_LEVELN_PSIZE;
3466         } else if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
3467                 if (parent->data->ipdata.meta.type ==
3468                     HAMMER2_OBJTYPE_DIRECTORY)
3469                         nbytes = HAMMER2_IND_BYTES_MIN; /* 4KB = 32 entries */
3470                 else
3471                         nbytes = HAMMER2_IND_BYTES_NOM; /* 16KB = ~8MB file */
3472
3473         } else {
3474                 nbytes = HAMMER2_IND_BYTES_MAX;
3475         }
3476         if (nbytes < count * sizeof(hammer2_blockref_t)) {
3477                 KKASSERT(for_type != HAMMER2_BREF_TYPE_FREEMAP_NODE &&
3478                          for_type != HAMMER2_BREF_TYPE_FREEMAP_LEAF);
3479                 nbytes = count * sizeof(hammer2_blockref_t);
3480         }
3481         ncount = nbytes / sizeof(hammer2_blockref_t);
3482
3483         /*
3484          * When creating an indirect block for a freemap node or leaf
3485          * the key/keybits must be fitted to static radix levels because
3486          * particular radix levels use particular reserved blocks in the
3487          * related zone.
3488          *
3489          * This routine calculates the key/radix of the indirect block
3490          * we need to create, and whether it is on the high-side or the
3491          * low-side.
3492          */
3493         switch(for_type) {
3494         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3495         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
3496                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3497                                                        base, count);
3498                 break;
3499         case HAMMER2_BREF_TYPE_DATA:
3500                 keybits = hammer2_chain_indkey_file(parent, &key, keybits,
3501                                                     base, count, ncount);
3502                 break;
3503         case HAMMER2_BREF_TYPE_DIRENT:
3504         case HAMMER2_BREF_TYPE_INODE:
3505                 keybits = hammer2_chain_indkey_dir(parent, &key, keybits,
3506                                                    base, count, ncount);
3507                 break;
3508         default:
3509                 panic("illegal indirect block for bref type %d", for_type);
3510                 break;
3511         }
3512
3513         /*
3514          * Normalize the key for the radix being represented, keeping the
3515          * high bits and throwing away the low bits.
3516          */
3517         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3518
3519         /*
3520          * Ok, create our new indirect block
3521          */
3522         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3523             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3524                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3525         } else {
3526                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3527         }
3528         dummy.bref.key = key;
3529         dummy.bref.keybits = keybits;
3530         dummy.bref.data_off = hammer2_getradix(nbytes);
3531         dummy.bref.methods =
3532                 HAMMER2_ENC_CHECK(HAMMER2_DEC_CHECK(parent->bref.methods)) |
3533                 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
3534
3535         ichain = hammer2_chain_alloc(hmp, parent->pmp, &dummy.bref);
3536         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3537         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3538         /* ichain has one ref at this point */
3539
3540         /*
3541          * We have to mark it modified to allocate its block, but use
3542          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3543          * it won't be acted upon by the flush code.
3544          */
3545         hammer2_chain_modify(ichain, mtid, 0, HAMMER2_MODIFY_OPTDATA);
3546
3547         /*
3548          * Iterate the original parent and move the matching brefs into
3549          * the new indirect block.
3550          *
3551          * XXX handle flushes.
3552          */
3553         key_beg = 0;
3554         key_end = HAMMER2_KEY_MAX;
3555         key_next = 0;   /* avoid gcc warnings */
3556         cache_index = 0;
3557         hammer2_spin_ex(&parent->core.spin);
3558         loops = 0;
3559         reason = 0;
3560
3561         for (;;) {
3562                 /*
3563                  * Parent may have been modified, relocating its block array.
3564                  * Reload the base pointer.
3565                  */
3566                 base = hammer2_chain_base_and_count(parent, &count);
3567
3568                 if (++loops > 100000) {
3569                     hammer2_spin_unex(&parent->core.spin);
3570                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3571                           reason, parent, base, count, key_next);
3572                 }
3573
3574                 /*
3575                  * NOTE: spinlock stays intact, returned chain (if not NULL)
3576                  *       is not referenced or locked which means that we
3577                  *       cannot safely check its flagged / deletion status
3578                  *       until we lock it.
3579                  */
3580                 chain = hammer2_combined_find(parent, base, count,
3581                                               &cache_index, &key_next,
3582                                               key_beg, key_end,
3583                                               &bref);
3584                 generation = parent->core.generation;
3585                 if (bref == NULL)
3586                         break;
3587                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3588
3589                 /*
3590                  * Skip keys that are not within the key/radix of the new
3591                  * indirect block.  They stay in the parent.
3592                  */
3593                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3594                     (key ^ bref->key)) != 0) {
3595                         goto next_key_spinlocked;
3596                 }
3597
3598                 /*
3599                  * Load the new indirect block by acquiring the related
3600                  * chains (potentially from media as it might not be
3601                  * in-memory).  Then move it to the new parent (ichain).
3602                  *
3603                  * chain is referenced but not locked.  We must lock the
3604                  * chain to obtain definitive state.
3605                  */
3606                 if (chain) {
3607                         /*
3608                          * Use chain already present in the RBTREE
3609                          */
3610                         hammer2_chain_ref(chain);
3611                         hammer2_spin_unex(&parent->core.spin);
3612                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3613                 } else {
3614                         /*
3615                          * Get chain for blockref element.  _get returns NULL
3616                          * on insertion race.
3617                          */
3618                         bcopy = *bref;
3619                         hammer2_spin_unex(&parent->core.spin);
3620                         chain = hammer2_chain_get(parent, generation, &bcopy);
3621                         if (chain == NULL) {
3622                                 reason = 1;
3623                                 hammer2_spin_ex(&parent->core.spin);
3624                                 continue;
3625                         }
3626                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3627                                 kprintf("REASON 2\n");
3628                                 reason = 2;
3629                                 hammer2_chain_drop(chain);
3630                                 hammer2_spin_ex(&parent->core.spin);
3631                                 continue;
3632                         }
3633                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER);
3634                 }
3635
3636                 /*
3637                  * This is always live so if the chain has been deleted
3638                  * we raced someone and we have to retry.
3639                  *
3640                  * NOTE: Lookups can race delete-duplicate because
3641                  *       delete-duplicate does not lock the parent's core
3642                  *       (they just use the spinlock on the core).
3643                  *
3644                  *       (note reversed logic for this one)
3645                  */
3646                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3647                         hammer2_chain_unlock(chain);
3648                         hammer2_chain_drop(chain);
3649                         goto next_key;
3650                 }
3651
3652                 /*
3653                  * Shift the chain to the indirect block.
3654                  *
3655                  * WARNING! No reason for us to load chain data, pass NOSTATS
3656                  *          to prevent delete/insert from trying to access
3657                  *          inode stats (and thus asserting if there is no
3658                  *          chain->data loaded).
3659                  *
3660                  * WARNING! The (parent, chain) deletion may modify the parent
3661                  *          and invalidate the base pointer.
3662                  */
3663                 hammer2_chain_delete(parent, chain, mtid, 0);
3664                 hammer2_chain_rename(NULL, &ichain, chain, mtid, 0);
3665                 hammer2_chain_unlock(chain);
3666                 hammer2_chain_drop(chain);
3667                 KKASSERT(parent->refs > 0);
3668                 chain = NULL;
3669                 base = NULL;    /* safety */
3670 next_key:
3671                 hammer2_spin_ex(&parent->core.spin);
3672 next_key_spinlocked:
3673                 if (--maxloops == 0)
3674                         panic("hammer2_chain_create_indirect: maxloops");
3675                 reason = 4;
3676                 if (key_next == 0 || key_next > key_end)
3677                         break;
3678                 key_beg = key_next;
3679                 /* loop */
3680         }
3681         hammer2_spin_unex(&parent->core.spin);
3682
3683         /*
3684          * Insert the new indirect block into the parent now that we've
3685          * cleared out some entries in the parent.  We calculated a good
3686          * insertion index in the loop above (ichain->index).
3687          *
3688          * We don't have to set UPDATE here because we mark ichain
3689          * modified down below (so the normal modified -> flush -> set-moved
3690          * sequence applies).
3691          *
3692          * The insertion shouldn't race as this is a completely new block
3693          * and the parent is locked.
3694          */
3695         base = NULL;    /* safety, parent modify may change address */
3696         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3697         hammer2_chain_insert(parent, ichain,
3698                              HAMMER2_CHAIN_INSERT_SPIN |
3699                              HAMMER2_CHAIN_INSERT_LIVE,
3700                              0);
3701
3702         /*
3703          * Make sure flushes propogate after our manual insertion.
3704          */
3705         hammer2_chain_setflush(ichain);
3706         hammer2_chain_setflush(parent);
3707
3708         /*
3709          * Figure out what to return.
3710          */
3711         if (~(((hammer2_key_t)1 << keybits) - 1) &
3712                    (create_key ^ key)) {
3713                 /*
3714                  * Key being created is outside the key range,
3715                  * return the original parent.
3716                  */
3717                 hammer2_chain_unlock(ichain);
3718                 hammer2_chain_drop(ichain);
3719         } else {
3720                 /*
3721                  * Otherwise its in the range, return the new parent.
3722                  * (leave both the new and old parent locked).
3723                  */
3724                 parent = ichain;
3725         }
3726
3727         return(parent);
3728 }
3729
3730 /*
3731  * Freemap indirect blocks
3732  *
3733  * Calculate the keybits and highside/lowside of the freemap node the
3734  * caller is creating.
3735  *
3736  * This routine will specify the next higher-level freemap key/radix
3737  * representing the lowest-ordered set.  By doing so, eventually all
3738  * low-ordered sets will be moved one level down.
3739  *
3740  * We have to be careful here because the freemap reserves a limited
3741  * number of blocks for a limited number of levels.  So we can't just
3742  * push indiscriminately.
3743  */
3744 int
3745 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3746                              int keybits, hammer2_blockref_t *base, int count)
3747 {
3748         hammer2_chain_t *chain;
3749         hammer2_blockref_t *bref;
3750         hammer2_key_t key;
3751         hammer2_key_t key_beg;
3752         hammer2_key_t key_end;
3753         hammer2_key_t key_next;
3754         int cache_index;
3755         int locount;
3756         int hicount;
3757         int maxloops = 300000;
3758
3759         key = *keyp;
3760         locount = 0;
3761         hicount = 0;
3762         keybits = 64;
3763
3764         /*
3765          * Calculate the range of keys in the array being careful to skip
3766          * slots which are overridden with a deletion.
3767          */
3768         key_beg = 0;
3769         key_end = HAMMER2_KEY_MAX;
3770         cache_index = 0;
3771         hammer2_spin_ex(&parent->core.spin);
3772
3773         for (;;) {
3774                 if (--maxloops == 0) {
3775                         panic("indkey_freemap shit %p %p:%d\n",
3776                               parent, base, count);
3777                 }
3778                 chain = hammer2_combined_find(parent, base, count,
3779                                               &cache_index, &key_next,
3780                                               key_beg, key_end,
3781                                               &bref);
3782
3783                 /*
3784                  * Exhausted search
3785                  */
3786                 if (bref == NULL)
3787                         break;
3788
3789                 /*
3790                  * Skip deleted chains.
3791                  */
3792                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3793                         if (key_next == 0 || key_next > key_end)
3794                                 break;
3795                         key_beg = key_next;
3796                         continue;
3797                 }
3798
3799                 /*
3800                  * Use the full live (not deleted) element for the scan
3801                  * iteration.  HAMMER2 does not allow partial replacements.
3802                  *
3803                  * XXX should be built into hammer2_combined_find().
3804                  */
3805                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3806
3807                 if (keybits > bref->keybits) {
3808                         key = bref->key;
3809                         keybits = bref->keybits;
3810                 } else if (keybits == bref->keybits && bref->key < key) {
3811                         key = bref->key;
3812                 }
3813                 if (key_next == 0)
3814                         break;
3815                 key_beg = key_next;
3816         }
3817         hammer2_spin_unex(&parent->core.spin);
3818
3819         /*
3820          * Return the keybits for a higher-level FREEMAP_NODE covering
3821          * this node.
3822          */
3823         switch(keybits) {
3824         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3825                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3826                 break;
3827         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3828                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3829                 break;
3830         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3831                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3832                 break;
3833         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3834                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3835                 break;
3836         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3837                 keybits = HAMMER2_FREEMAP_LEVEL5_RADIX;
3838                 break;
3839         case HAMMER2_FREEMAP_LEVEL5_RADIX:
3840                 panic("hammer2_chain_indkey_freemap: level too high");
3841                 break;
3842         default:
3843                 panic("hammer2_chain_indkey_freemap: bad radix");
3844                 break;
3845         }
3846         *keyp = key;
3847
3848         return (keybits);
3849 }
3850
3851 /*
3852  * File indirect blocks
3853  *
3854  * Calculate the key/keybits for the indirect block to create by scanning
3855  * existing keys.  The key being created is also passed in *keyp and can be
3856  * inside or outside the indirect block.  Regardless, the indirect block
3857  * must hold at least two keys in order to guarantee sufficient space.
3858  *
3859  * We use a modified version of the freemap's fixed radix tree, but taylored
3860  * for file data.  Basically we configure an indirect block encompassing the
3861  * smallest key.
3862  */
3863 static int
3864 hammer2_chain_indkey_file(hammer2_chain_t *parent, hammer2_key_t *keyp,
3865                             int keybits, hammer2_blockref_t *base, int count,
3866                             int ncount)
3867 {
3868         hammer2_chain_t *chain;
3869         hammer2_blockref_t *bref;
3870         hammer2_key_t key;
3871         hammer2_key_t key_beg;
3872         hammer2_key_t key_end;
3873         hammer2_key_t key_next;
3874         int nradix;
3875         int cache_index;
3876         int locount;
3877         int hicount;
3878         int maxloops = 300000;
3879
3880         key = *keyp;
3881         locount = 0;
3882         hicount = 0;
3883         keybits = 64;
3884
3885         /*
3886          * Calculate the range of keys in the array being careful to skip
3887          * slots which are overridden with a deletion.
3888          *
3889          * Locate the smallest key.
3890          */
3891         key_beg = 0;
3892         key_end = HAMMER2_KEY_MAX;
3893         cache_index = 0;
3894         hammer2_spin_ex(&parent->core.spin);
3895
3896         for (;;) {
3897                 if (--maxloops == 0) {
3898                         panic("indkey_freemap shit %p %p:%d\n",
3899                               parent, base, count);
3900                 }
3901                 chain = hammer2_combined_find(parent, base, count,
3902                                               &cache_index, &key_next,
3903                                               key_beg, key_end,
3904                                               &bref);
3905
3906                 /*
3907                  * Exhausted search
3908                  */
3909                 if (bref == NULL)
3910                         break;
3911
3912                 /*
3913                  * Skip deleted chains.
3914                  */
3915                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3916                         if (key_next == 0 || key_next > key_end)
3917                                 break;
3918                         key_beg = key_next;
3919                         continue;
3920                 }
3921
3922                 /*
3923                  * Use the full live (not deleted) element for the scan
3924                  * iteration.  HAMMER2 does not allow partial replacements.
3925                  *
3926                  * XXX should be built into hammer2_combined_find().
3927                  */
3928                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3929
3930                 if (keybits > bref->keybits) {
3931                         key = bref->key;
3932                         keybits = bref->keybits;
3933                 } else if (keybits == bref->keybits && bref->key < key) {
3934                         key = bref->key;
3935                 }
3936                 if (key_next == 0)
3937                         break;
3938                 key_beg = key_next;
3939         }
3940         hammer2_spin_unex(&parent->core.spin);
3941
3942         /*
3943          * Calculate the static keybits for a higher-level indirect block
3944          * that contains the key.
3945          */
3946         *keyp = key;
3947
3948         switch(ncount) {
3949         case HAMMER2_IND_BYTES_MIN / sizeof(hammer2_blockref_t):
3950                 nradix = HAMMER2_IND_RADIX_MIN - HAMMER2_BLOCKREF_RADIX;
3951                 break;
3952         case HAMMER2_IND_BYTES_NOM / sizeof(hammer2_blockref_t):
3953                 nradix = HAMMER2_IND_RADIX_NOM - HAMMER2_BLOCKREF_RADIX;
3954                 break;
3955         case HAMMER2_IND_BYTES_MAX / sizeof(hammer2_blockref_t):
3956                 nradix = HAMMER2_IND_RADIX_MAX - HAMMER2_BLOCKREF_RADIX;
3957                 break;
3958         default:
3959                 panic("bad ncount %d\n", ncount);
3960                 nradix = 0;
3961                 break;
3962         }
3963
3964         /*
3965          * The largest radix that can be returned for an indirect block is
3966          * 63 bits.  (The largest practical indirect block radix is actually
3967          * 62 bits because the top-level inode or volume root contains four
3968          * entries, but allow 63 to be returned).
3969          */
3970         if (nradix >= 64)
3971                 nradix = 63;
3972
3973         return keybits + nradix;
3974 }
3975
3976 #if 1
3977
3978 /*
3979  * Directory indirect blocks.
3980  *
3981  * Covers both the inode index (directory of inodes), and directory contents
3982  * (filenames hardlinked to inodes).
3983  *
3984  * Because directory keys are hashed we generally try to cut the space in
3985  * half.  We accomodate the inode index (which tends to have linearly
3986  * increasing inode numbers) by ensuring that the keyspace is at least large
3987  * enough to fill up the indirect block being created.
3988  */
3989 static int
3990 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
3991                          int keybits, hammer2_blockref_t *base, int count,
3992                          int ncount)
3993 {
3994         hammer2_blockref_t *bref;
3995         hammer2_chain_t *chain;
3996         hammer2_key_t key_beg;
3997         hammer2_key_t key_end;
3998         hammer2_key_t key_next;
3999         hammer2_key_t key;
4000         int nkeybits;
4001         int locount;
4002         int hicount;
4003         int cache_index;
4004         int maxloops = 300000;
4005
4006         /*
4007          * Shortcut if the parent is the inode.  In this situation the
4008          * parent has 4+1 directory entries and we are creating an indirect
4009          * block capable of holding many more.
4010          */
4011         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4012                 return 63;
4013         }
4014
4015         key = *keyp;
4016         locount = 0;
4017         hicount = 0;
4018
4019         /*
4020          * Calculate the range of keys in the array being careful to skip
4021          * slots which are overridden with a deletion.
4022          */
4023         key_beg = 0;
4024         key_end = HAMMER2_KEY_MAX;
4025         cache_index = 0;
4026         hammer2_spin_ex(&parent->core.spin);
4027
4028         for (;;) {
4029                 if (--maxloops == 0) {
4030                         panic("indkey_freemap shit %p %p:%d\n",
4031                               parent, base, count);
4032                 }
4033                 chain = hammer2_combined_find(parent, base, count,
4034                                               &cache_index, &key_next,
4035                                               key_beg, key_end,
4036                                               &bref);
4037
4038                 /*
4039                  * Exhausted search
4040                  */
4041                 if (bref == NULL)
4042                         break;
4043
4044                 /*
4045                  * Deleted object
4046                  */
4047                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4048                         if (key_next == 0 || key_next > key_end)
4049                                 break;
4050                         key_beg = key_next;
4051                         continue;
4052                 }
4053
4054                 /*
4055                  * Use the full live (not deleted) element for the scan
4056                  * iteration.  HAMMER2 does not allow partial replacements.
4057                  *
4058                  * XXX should be built into hammer2_combined_find().
4059                  */
4060                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4061
4062                 /*
4063                  * Expand our calculated key range (key, keybits) to fit
4064                  * the scanned key.  nkeybits represents the full range
4065                  * that we will later cut in half (two halves @ nkeybits - 1).
4066                  */
4067                 nkeybits = keybits;
4068                 if (nkeybits < bref->keybits) {
4069                         if (bref->keybits > 64) {
4070                                 kprintf("bad bref chain %p bref %p\n",
4071                                         chain, bref);
4072                                 Debugger("fubar");
4073                         }
4074                         nkeybits = bref->keybits;
4075                 }
4076                 while (nkeybits < 64 &&
4077                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
4078                         (key ^ bref->key)) != 0) {
4079                         ++nkeybits;
4080                 }
4081
4082                 /*
4083                  * If the new key range is larger we have to determine
4084                  * which side of the new key range the existing keys fall
4085                  * under by checking the high bit, then collapsing the
4086                  * locount into the hicount or vise-versa.
4087                  */
4088                 if (keybits != nkeybits) {
4089                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4090                                 hicount += locount;
4091                                 locount = 0;
4092                         } else {
4093                                 locount += hicount;
4094                                 hicount = 0;
4095                         }
4096                         keybits = nkeybits;
4097                 }
4098
4099                 /*
4100                  * The newly scanned key will be in the lower half or the
4101                  * upper half of the (new) key range.
4102                  */
4103                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4104                         ++hicount;
4105                 else
4106                         ++locount;
4107
4108                 if (key_next == 0)
4109                         break;
4110                 key_beg = key_next;
4111         }
4112         hammer2_spin_unex(&parent->core.spin);
4113         bref = NULL;    /* now invalid (safety) */
4114
4115         /*
4116          * Adjust keybits to represent half of the full range calculated
4117          * above (radix 63 max) for our new indirect block.
4118          */
4119         --keybits;
4120
4121         /*
4122          * Expand keybits to hold at least ncount elements.  ncount will be
4123          * a power of 2.  This is to try to completely fill leaf nodes (at
4124          * least for keys which are not hashes).
4125          *
4126          * We aren't counting 'in' or 'out', we are counting 'high side'
4127          * and 'low side' based on the bit at (1LL << keybits).  We want
4128          * everything to be inside in these cases so shift it all to
4129          * the low or high side depending on the new high bit.
4130          */
4131         while (((hammer2_key_t)1 << keybits) < ncount) {
4132                 ++keybits;
4133                 if (key & ((hammer2_key_t)1 << keybits)) {
4134                         hicount += locount;
4135                         locount = 0;
4136                 } else {
4137                         locount += hicount;
4138                         hicount = 0;
4139                 }
4140         }
4141
4142         if (hicount > locount)
4143                 key |= (hammer2_key_t)1 << keybits;
4144         else
4145                 key &= ~(hammer2_key_t)1 << keybits;
4146
4147         *keyp = key;
4148
4149         return (keybits);
4150 }
4151
4152 #else
4153
4154 /*
4155  * Directory indirect blocks.
4156  *
4157  * Covers both the inode index (directory of inodes), and directory contents
4158  * (filenames hardlinked to inodes).
4159  *
4160  * Because directory keys are hashed we generally try to cut the space in
4161  * half.  We accomodate the inode index (which tends to have linearly
4162  * increasing inode numbers) by ensuring that the keyspace is at least large
4163  * enough to fill up the indirect block being created.
4164  */
4165 static int
4166 hammer2_chain_indkey_dir(hammer2_chain_t *parent, hammer2_key_t *keyp,
4167                          int keybits, hammer2_blockref_t *base, int count,
4168                          int ncount)
4169 {
4170         hammer2_blockref_t *bref;
4171         hammer2_chain_t *chain;
4172         hammer2_key_t key_beg;
4173         hammer2_key_t key_end;
4174         hammer2_key_t key_next;
4175         hammer2_key_t key;
4176         int nkeybits;
4177         int locount;
4178         int hicount;
4179         int cache_index;
4180         int maxloops = 300000;
4181
4182         /*
4183          * Shortcut if the parent is the inode.  In this situation the
4184          * parent has 4+1 directory entries and we are creating an indirect
4185          * block capable of holding many more.
4186          */
4187         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE) {
4188                 return 63;
4189         }
4190
4191         key = *keyp;
4192         locount = 0;
4193         hicount = 0;
4194
4195         /*
4196          * Calculate the range of keys in the array being careful to skip
4197          * slots which are overridden with a deletion.
4198          */
4199         key_beg = 0;
4200         key_end = HAMMER2_KEY_MAX;
4201         cache_index = 0;
4202         hammer2_spin_ex(&parent->core.spin);
4203
4204         for (;;) {
4205                 if (--maxloops == 0) {
4206                         panic("indkey_freemap shit %p %p:%d\n",
4207                               parent, base, count);
4208                 }
4209                 chain = hammer2_combined_find(parent, base, count,
4210                                               &cache_index, &key_next,
4211                                               key_beg, key_end,
4212                                               &bref);
4213
4214                 /*
4215                  * Exhausted search
4216                  */
4217                 if (bref == NULL)
4218                         break;
4219
4220                 /*
4221                  * Deleted object
4222                  */
4223                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
4224                         if (key_next == 0 || key_next > key_end)
4225                                 break;
4226                         key_beg = key_next;
4227                         continue;
4228                 }
4229
4230                 /*
4231                  * Use the full live (not deleted) element for the scan
4232                  * iteration.  HAMMER2 does not allow partial replacements.
4233                  *
4234                  * XXX should be built into hammer2_combined_find().
4235                  */
4236                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
4237
4238                 /*
4239                  * Expand our calculated key range (key, keybits) to fit
4240                  * the scanned key.  nkeybits represents the full range
4241                  * that we will later cut in half (two halves @ nkeybits - 1).
4242                  */
4243                 nkeybits = keybits;
4244                 if (nkeybits < bref->keybits) {
4245                         if (bref->keybits > 64) {
4246                                 kprintf("bad bref chain %p bref %p\n",
4247                                         chain, bref);
4248                                 Debugger("fubar");
4249                         }
4250                         nkeybits = bref->keybits;
4251                 }
4252                 while (nkeybits < 64 &&
4253                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
4254                         (key ^ bref->key)) != 0) {
4255                         ++nkeybits;
4256                 }
4257
4258                 /*
4259                  * If the new key range is larger we have to determine
4260                  * which side of the new key range the existing keys fall
4261                  * under by checking the high bit, then collapsing the
4262                  * locount into the hicount or vise-versa.
4263                  */
4264                 if (keybits != nkeybits) {
4265                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
4266                                 hicount += locount;
4267                                 locount = 0;
4268                         } else {
4269                                 locount += hicount;
4270                                 hicount = 0;
4271                         }
4272                         keybits = nkeybits;
4273                 }
4274
4275                 /*
4276                  * The newly scanned key will be in the lower half or the
4277                  * upper half of the (new) key range.
4278                  */
4279                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
4280                         ++hicount;
4281                 else
4282                         ++locount;
4283
4284                 if (key_next == 0)
4285                         break;
4286                 key_beg = key_next;
4287         }
4288         hammer2_spin_unex(&parent->core.spin);
4289         bref = NULL;    /* now invalid (safety) */
4290
4291         /*
4292          * Adjust keybits to represent half of the full range calculated
4293          * above (radix 63 max) for our new indirect block.
4294          */
4295         --keybits;
4296
4297         /*
4298          * Expand keybits to hold at least ncount elements.  ncount will be
4299          * a power of 2.  This is to try to completely fill leaf nodes (at
4300          * least for keys which are not hashes).
4301          *
4302          * We aren't counting 'in' or 'out', we are counting 'high side'
4303          * and 'low side' based on the bit at (1LL << keybits).  We want
4304          * everything to be inside in these cases so shift it all to
4305          * the low or high side depending on the new high bit.
4306          */
4307         while (((hammer2_key_t)1 << keybits) < ncount) {
4308                 ++keybits;
4309                 if (key & ((hammer2_key_t)1 << keybits)) {
4310                         hicount += locount;
4311                         locount = 0;
4312                 } else {
4313                         locount += hicount;
4314                         hicount = 0;
4315                 }
4316         }
4317
4318         if (hicount > locount)
4319                 key |= (hammer2_key_t)1 << keybits;
4320         else
4321                 key &= ~(hammer2_key_t)1 << keybits;
4322
4323         *keyp = key;
4324
4325         return (keybits);
4326 }
4327
4328 #endif
4329
4330 /*
4331  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
4332  * it exists.
4333  *
4334  * Both parent and chain must be locked exclusively.
4335  *
4336  * This function will modify the parent if the blockref requires removal
4337  * from the parent's block table.
4338  *
4339  * This function is NOT recursive.  Any entity already pushed into the
4340  * chain (such as an inode) may still need visibility into its contents,
4341  * as well as the ability to read and modify the contents.  For example,
4342  * for an unlinked file which is still open.
4343  *
4344  * Also note that the flusher is responsible for cleaning up empty
4345  * indirect blocks.
4346  */
4347 void
4348 hammer2_chain_delete(hammer2_chain_t *parent, hammer2_chain_t *chain,
4349                      hammer2_tid_t mtid, int flags)
4350 {
4351         KKASSERT(hammer2_mtx_owned(&chain->lock));
4352
4353         /*
4354          * Nothing to do if already marked.
4355          *
4356          * We need the spinlock on the core whos RBTREE contains chain
4357          * to protect against races.
4358          */
4359         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
4360                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
4361                          chain->parent == parent);
4362                 _hammer2_chain_delete_helper(parent, chain, mtid, flags);
4363         }
4364
4365         /*
4366          * Permanent deletions mark the chain as destroyed.
4367          */
4368         if (flags & HAMMER2_DELETE_PERMANENT) {
4369                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
4370         } else {
4371                 /* XXX might not be needed */
4372                 hammer2_chain_setflush(chain);
4373         }
4374 }
4375
4376 /*
4377  * Returns the index of the nearest element in the blockref array >= elm.
4378  * Returns (count) if no element could be found.
4379  *
4380  * Sets *key_nextp to the next key for loop purposes but does not modify
4381  * it if the next key would be higher than the current value of *key_nextp.
4382  * Note that *key_nexp can overflow to 0, which should be tested by the
4383  * caller.
4384  *
4385  * (*cache_indexp) is a heuristic and can be any value without effecting
4386  * the result.
4387  *
4388  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
4389  *           held through the operation.
4390  */
4391 static int
4392 hammer2_base_find(hammer2_chain_t *parent,
4393                   hammer2_blockref_t *base, int count,
4394                   int *cache_indexp, hammer2_key_t *key_nextp,
4395                   hammer2_key_t key_beg, hammer2_key_t key_end)
4396 {
4397         hammer2_blockref_t *scan;
4398         hammer2_key_t scan_end;
4399         int i;
4400         int limit;
4401
4402         /*
4403          * Require the live chain's already have their core's counted
4404          * so we can optimize operations.
4405          */
4406         KKASSERT(parent->flags & HAMMER2_CHAIN_COUNTEDBREFS);
4407
4408         /*
4409          * Degenerate case
4410          */
4411         if (count == 0 || base == NULL)
4412                 return(count);
4413
4414         /*
4415          * Sequential optimization using *cache_indexp.  This is the most
4416          * likely scenario.
4417          *
4418          * We can avoid trailing empty entries on live chains, otherwise
4419          * we might have to check the whole block array.
4420          */
4421         i = *cache_indexp;
4422         cpu_ccfence();
4423         limit = parent->core.live_zero;
4424         if (i >= limit)
4425                 i = limit - 1;
4426         if (i < 0)
4427                 i = 0;
4428         KKASSERT(i < count);
4429
4430         /*
4431          * Search backwards
4432          */
4433         scan = &base[i];
4434         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4435                 --scan;
4436                 --i;
4437         }
4438         *cache_indexp = i;
4439
4440         /*
4441          * Search forwards, stop when we find a scan element which
4442          * encloses the key or until we know that there are no further
4443          * elements.
4444          */
4445         while (i < count) {
4446                 if (scan->type != 0) {
4447                         scan_end = scan->key +
4448                                    ((hammer2_key_t)1 << scan->keybits) - 1;
4449                         if (scan->key > key_beg || scan_end >= key_beg)
4450                                 break;
4451                 }
4452                 if (i >= limit)
4453                         return (count);
4454                 ++scan;
4455                 ++i;
4456         }
4457         if (i != count) {
4458                 *cache_indexp = i;
4459                 if (i >= limit) {
4460                         i = count;
4461                 } else {
4462                         scan_end = scan->key +
4463                                    ((hammer2_key_t)1 << scan->keybits);
4464                         if (scan_end && (*key_nextp > scan_end ||
4465                                          *key_nextp == 0)) {
4466                                 *key_nextp = scan_end;
4467                         }
4468                 }
4469         }
4470         return (i);
4471 }
4472
4473 /*
4474  * Do a combined search and return the next match either from the blockref
4475  * array or from the in-memory chain.  Sets *bresp to the returned bref in
4476  * both cases, or sets it to NULL if the search exhausted.  Only returns
4477  * a non-NULL chain if the search matched from the in-memory chain.
4478  *
4479  * When no in-memory chain has been found and a non-NULL bref is returned
4480  * in *bresp.
4481  *
4482  *
4483  * The returned chain is not locked or referenced.  Use the returned bref
4484  * to determine if the search exhausted or not.  Iterate if the base find
4485  * is chosen but matches a deleted chain.
4486  *
4487  * WARNING!  Must be called with parent's spinlock held.  Spinlock remains
4488  *           held through the operation.
4489  */
4490 static hammer2_chain_t *
4491 hammer2_combined_find(hammer2_chain_t *parent,
4492                       hammer2_blockref_t *base, int count,
4493                       int *cache_indexp, hammer2_key_t *key_nextp,
4494                       hammer2_key_t key_beg, hammer2_key_t key_end,
4495                       hammer2_blockref_t **bresp)
4496 {
4497         hammer2_blockref_t *bref;
4498         hammer2_chain_t *chain;
4499         int i;
4500
4501         /*
4502          * Lookup in block array and in rbtree.
4503          */
4504         *key_nextp = key_end + 1;
4505         i = hammer2_base_find(parent, base, count, cache_indexp,
4506                               key_nextp, key_beg, key_end);
4507         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4508
4509         /*
4510          * Neither matched
4511          */
4512         if (i == count && chain == NULL) {
4513                 *bresp = NULL;
4514                 return(NULL);
4515         }
4516
4517         /*
4518          * Only chain matched.
4519          */
4520         if (i == count) {
4521                 bref = &chain->bref;
4522                 goto found;
4523         }
4524
4525         /*
4526          * Only blockref matched.
4527          */
4528         if (chain == NULL) {
4529                 bref = &base[i];
4530                 goto found;
4531         }
4532
4533         /*
4534          * Both in-memory and blockref matched, select the nearer element.
4535          *
4536          * If both are flush with the left-hand side or both are the
4537          * same distance away, select the chain.  In this situation the
4538          * chain must have been loaded from the matching blockmap.
4539          */
4540         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4541             chain->bref.key == base[i].key) {
4542                 KKASSERT(chain->bref.key == base[i].key);
4543                 bref = &chain->bref;
4544                 goto found;
4545         }
4546
4547         /*
4548          * Select the nearer key
4549          */
4550         if (chain->bref.key < base[i].key) {
4551                 bref = &chain->bref;
4552         } else {
4553                 bref = &base[i];
4554                 chain = NULL;
4555         }
4556
4557         /*
4558          * If the bref is out of bounds we've exhausted our search.
4559          */
4560 found:
4561         if (bref->key > key_end) {
4562                 *bresp = NULL;
4563                 chain = NULL;
4564         } else {
4565                 *bresp = bref;
4566         }
4567         return(chain);
4568 }
4569
4570 /*
4571  * Locate the specified block array element and delete it.  The element
4572  * must exist.
4573  *
4574  * The spin lock on the related chain must be held.
4575  *
4576  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4577  *       need to be adjusted when we commit the media change.
4578  */
4579 void
4580 hammer2_base_delete(hammer2_chain_t *parent,
4581                     hammer2_blockref_t *base, int count,
4582                     int *cache_indexp, hammer2_chain_t *chain)
4583 {
4584         hammer2_blockref_t *elm = &chain->bref;
4585         hammer2_blockref_t *scan;
4586         hammer2_key_t key_next;
4587         int i;
4588
4589         /*
4590          * Delete element.  Expect the element to exist.
4591          *
4592          * XXX see caller, flush code not yet sophisticated enough to prevent
4593          *     re-flushed in some cases.
4594          */
4595         key_next = 0; /* max range */
4596         i = hammer2_base_find(parent, base, count, cache_indexp,
4597                               &key_next, elm->key, elm->key);
4598         scan = &base[i];
4599         if (i == count || scan->type == 0 ||
4600             scan->key != elm->key ||
4601             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
4602              scan->keybits != elm->keybits)) {
4603                 hammer2_spin_unex(&parent->core.spin);
4604                 panic("delete base %p element not found at %d/%d elm %p\n",
4605                       base, i, count, elm);
4606                 return;
4607         }
4608
4609         /*
4610          * Update stats and zero the entry.
4611          *
4612          * NOTE: Handle radix == 0 (0 bytes) case.
4613          */
4614         if ((int)(scan->data_off & HAMMER2_OFF_MASK_RADIX)) {
4615                 parent->bref.embed.stats.data_count -= (hammer2_off_t)1 <<
4616                                 (int)(scan->data_off & HAMMER2_OFF_MASK_RADIX);
4617         }
4618         switch(scan->type) {
4619         case HAMMER2_BREF_TYPE_INODE:
4620                 parent->bref.embed.stats.inode_count -= 1;
4621                 /* fall through */
4622         case HAMMER2_BREF_TYPE_DATA:
4623         case HAMMER2_BREF_TYPE_INDIRECT:
4624                 parent->bref.embed.stats.data_count -=
4625                         scan->embed.stats.data_count;
4626                 parent->bref.embed.stats.inode_count -=
4627                         scan->embed.stats.inode_count;
4628                 break;
4629         default:
4630                 break;
4631         }
4632
4633         bzero(scan, sizeof(*scan));
4634
4635         /*
4636          * We can only optimize parent->core.live_zero for live chains.
4637          */
4638         if (parent->core.live_zero == i + 1) {
4639                 while (--i >= 0 && base[i].type == 0)
4640                         ;
4641                 parent->core.live_zero = i + 1;
4642         }
4643
4644         /*
4645          * Clear appropriate blockmap flags in chain.
4646          */
4647         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
4648                                         HAMMER2_CHAIN_BMAPUPD);
4649 }
4650
4651 /*
4652  * Insert the specified element.  The block array must not already have the
4653  * element and must have space available for the insertion.
4654  *
4655  * The spin lock on the related chain must be held.
4656  *
4657  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4658  *       need to be adjusted when we commit the media change.
4659  */
4660 void
4661 hammer2_base_insert(hammer2_chain_t *parent,
4662                     hammer2_blockref_t *base, int count,
4663                     int *cache_indexp, hammer2_chain_t *chain)
4664 {
4665         hammer2_blockref_t *elm = &chain->bref;
4666         hammer2_key_t key_next;
4667         hammer2_key_t xkey;
4668         int i;
4669         int j;
4670         int k;
4671         int l;
4672         int u = 1;
4673
4674         /*
4675          * Insert new element.  Expect the element to not already exist
4676          * unless we are replacing it.
4677          *
4678          * XXX see caller, flush code not yet sophisticated enough to prevent
4679          *     re-flushed in some cases.
4680          */
4681         key_next = 0; /* max range */
4682         i = hammer2_base_find(parent, base, count, cache_indexp,
4683                               &key_next, elm->key, elm->key);
4684
4685         /*
4686          * Shortcut fill optimization, typical ordered insertion(s) may not
4687          * require a search.
4688          */
4689         KKASSERT(i >= 0 && i <= count);
4690
4691         /*
4692          * Set appropriate blockmap flags in chain.
4693          */
4694         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
4695
4696         /*
4697          * Update stats and zero the entry
4698          */
4699         if ((int)(elm->data_off & HAMMER2_OFF_MASK_RADIX)) {
4700                 parent->bref.embed.stats.data_count += (hammer2_off_t)1 <<
4701                                 (int)(elm->data_off & HAMMER2_OFF_MASK_RADIX);
4702         }
4703         switch(elm->type) {
4704         case HAMMER2_BREF_TYPE_INODE:
4705                 parent->bref.embed.stats.inode_count += 1;
4706                 /* fall through */
4707         case HAMMER2_BREF_TYPE_DATA:
4708         case HAMMER2_BREF_TYPE_INDIRECT:
4709                 parent->bref.embed.stats.data_count +=
4710                         elm->embed.stats.data_count;
4711                 parent->bref.embed.stats.inode_count +=
4712                         elm->embed.stats.inode_count;
4713                 break;
4714         default:
4715                 break;
4716         }
4717
4718
4719         /*
4720          * We can only optimize parent->core.live_zero for live chains.
4721          */
4722         if (i == count && parent->core.live_zero < count) {
4723                 i = parent->core.live_zero++;
4724                 base[i] = *elm;
4725                 return;
4726         }
4727
4728         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4729         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4730                 hammer2_spin_unex(&parent->core.spin);
4731                 panic("insert base %p overlapping elements at %d elm %p\n",
4732                       base, i, elm);
4733         }
4734
4735         /*
4736          * Try to find an empty slot before or after.
4737          */
4738         j = i;
4739         k = i;
4740         while (j > 0 || k < count) {
4741                 --j;
4742                 if (j >= 0 && base[j].type == 0) {
4743                         if (j == i - 1) {
4744                                 base[j] = *elm;
4745                         } else {
4746                                 bcopy(&base[j+1], &base[j],
4747                                       (i - j - 1) * sizeof(*base));
4748                                 base[i - 1] = *elm;
4749                         }
4750                         goto validate;
4751                 }
4752                 ++k;
4753                 if (k < count && base[k].type == 0) {
4754                         bcopy(&base[i], &base[i+1],
4755                               (k - i) * sizeof(hammer2_blockref_t));
4756                         base[i] = *elm;
4757
4758                         /*
4759                          * We can only update parent->core.live_zero for live
4760                          * chains.
4761                          */
4762                         if (parent->core.live_zero <= k)
4763                                 parent->core.live_zero = k + 1;
4764                         u = 2;
4765                         goto validate;
4766                 }
4767         }
4768         panic("hammer2_base_insert: no room!");
4769
4770         /*
4771          * Debugging
4772          */
4773 validate:
4774         key_next = 0;
4775         for (l = 0; l < count; ++l) {
4776                 if (base[l].type) {
4777                         key_next = base[l].key +
4778                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4779                         break;
4780                 }
4781         }
4782         while (++l < count) {
4783                 if (base[l].type) {
4784                         if (base[l].key <= key_next)
4785                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4786                         key_next = base[l].key +
4787                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4788
4789                 }
4790         }
4791
4792 }
4793
4794 #if 0
4795
4796 /*
4797  * Sort the blockref array for the chain.  Used by the flush code to
4798  * sort the blockref[] array.
4799  *
4800  * The chain must be exclusively locked AND spin-locked.
4801  */
4802 typedef hammer2_blockref_t *hammer2_blockref_p;
4803
4804 static
4805 int
4806 hammer2_base_sort_callback(const void *v1, const void *v2)
4807 {
4808         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4809         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4810
4811         /*
4812          * Make sure empty elements are placed at the end of the array
4813          */
4814         if (bref1->type == 0) {
4815                 if (bref2->type == 0)
4816                         return(0);
4817                 return(1);
4818         } else if (bref2->type == 0) {
4819                 return(-1);
4820         }
4821
4822         /*
4823          * Sort by key
4824          */
4825         if (bref1->key < bref2->key)
4826                 return(-1);
4827         if (bref1->key > bref2->key)
4828                 return(1);
4829         return(0);
4830 }
4831
4832 void
4833 hammer2_base_sort(hammer2_chain_t *chain)
4834 {
4835         hammer2_blockref_t *base;
4836         int count;
4837
4838         switch(chain->bref.type) {
4839         case HAMMER2_BREF_TYPE_INODE:
4840                 /*
4841                  * Special shortcut for embedded data returns the inode
4842                  * itself.  Callers must detect this condition and access
4843                  * the embedded data (the strategy code does this for us).
4844                  *
4845                  * This is only applicable to regular files and softlinks.
4846                  */
4847                 if (chain->data->ipdata.meta.op_flags &
4848                     HAMMER2_OPFLAG_DIRECTDATA) {
4849                         return;
4850                 }
4851                 base = &chain->data->ipdata.u.blockset.blockref[0];
4852                 count = HAMMER2_SET_COUNT;
4853                 break;
4854         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4855         case HAMMER2_BREF_TYPE_INDIRECT:
4856                 /*
4857                  * Optimize indirect blocks in the INITIAL state to avoid
4858                  * I/O.
4859                  */
4860                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4861                 base = &chain->data->npdata[0];
4862                 count = chain->bytes / sizeof(hammer2_blockref_t);
4863                 break;
4864         case HAMMER2_BREF_TYPE_VOLUME:
4865                 base = &chain->data->voldata.sroot_blockset.blockref[0];
4866                 count = HAMMER2_SET_COUNT;
4867                 break;
4868         case HAMMER2_BREF_TYPE_FREEMAP:
4869                 base = &chain->data->blkset.blockref[0];
4870                 count = HAMMER2_SET_COUNT;
4871                 break;
4872         default:
4873                 kprintf("hammer2_chain_lookup: unrecognized "
4874                         "blockref(A) type: %d",
4875                         chain->bref.type);
4876                 while (1)
4877                         tsleep(&base, 0, "dead", 0);
4878                 panic("hammer2_chain_lookup: unrecognized "
4879                       "blockref(A) type: %d",
4880                       chain->bref.type);
4881                 base = NULL;    /* safety */
4882                 count = 0;      /* safety */
4883         }
4884         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4885 }
4886
4887 #endif
4888
4889 /*
4890  * Chain memory management
4891  */
4892 void
4893 hammer2_chain_wait(hammer2_chain_t *chain)
4894 {
4895         tsleep(chain, 0, "chnflw", 1);
4896 }
4897
4898 const hammer2_media_data_t *
4899 hammer2_chain_rdata(hammer2_chain_t *chain)
4900 {
4901         KKASSERT(chain->data != NULL);
4902         return (chain->data);
4903 }
4904
4905 hammer2_media_data_t *
4906 hammer2_chain_wdata(hammer2_chain_t *chain)
4907 {
4908         KKASSERT(chain->data != NULL);
4909         return (chain->data);
4910 }
4911
4912 /*
4913  * Set the check data for a chain.  This can be a heavy-weight operation
4914  * and typically only runs on-flush.  For file data check data is calculated
4915  * when the logical buffers are flushed.
4916  */
4917 void
4918 hammer2_chain_setcheck(hammer2_chain_t *chain, void *bdata)
4919 {
4920         chain->bref.flags &= ~HAMMER2_BREF_FLAG_ZERO;
4921
4922         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4923         case HAMMER2_CHECK_NONE:
4924                 break;
4925         case HAMMER2_CHECK_DISABLED:
4926                 break;
4927         case HAMMER2_CHECK_ISCSI32:
4928                 chain->bref.check.iscsi32.value =
4929                         hammer2_icrc32(bdata, chain->bytes);
4930                 break;
4931         case HAMMER2_CHECK_XXHASH64:
4932                 chain->bref.check.xxhash64.value =
4933                         XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4934                 break;
4935         case HAMMER2_CHECK_SHA192:
4936                 {
4937                         SHA256_CTX hash_ctx;
4938                         union {
4939                                 uint8_t digest[SHA256_DIGEST_LENGTH];
4940                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
4941                         } u;
4942
4943                         SHA256_Init(&hash_ctx);
4944                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
4945                         SHA256_Final(u.digest, &hash_ctx);
4946                         u.digest64[2] ^= u.digest64[3];
4947                         bcopy(u.digest,
4948                               chain->bref.check.sha192.data,
4949                               sizeof(chain->bref.check.sha192.data));
4950                 }
4951                 break;
4952         case HAMMER2_CHECK_FREEMAP:
4953                 chain->bref.check.freemap.icrc32 =
4954                         hammer2_icrc32(bdata, chain->bytes);
4955                 break;
4956         default:
4957                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
4958                         chain->bref.methods);
4959                 break;
4960         }
4961 }
4962
4963 int
4964 hammer2_chain_testcheck(hammer2_chain_t *chain, void *bdata)
4965 {
4966         uint32_t check32;
4967         uint64_t check64;
4968         int r;
4969
4970         if (chain->bref.flags & HAMMER2_BREF_FLAG_ZERO)
4971                 return 1;
4972
4973         switch(HAMMER2_DEC_CHECK(chain->bref.methods)) {
4974         case HAMMER2_CHECK_NONE:
4975                 r = 1;
4976                 break;
4977         case HAMMER2_CHECK_DISABLED:
4978                 r = 1;
4979                 break;
4980         case HAMMER2_CHECK_ISCSI32:
4981                 check32 = hammer2_icrc32(bdata, chain->bytes);
4982                 r = (chain->bref.check.iscsi32.value == check32);
4983                 if (r == 0) {
4984                         kprintf("chain %016jx.%02x meth=%02x CHECK FAIL "
4985                                 "(flags=%08x, bref/data %08x/%08x)\n",
4986                                 chain->bref.data_off,
4987                                 chain->bref.type,
4988                                 chain->bref.methods,
4989                                 chain->flags,
4990                                 chain->bref.check.iscsi32.value,
4991                                 check32);
4992                 }
4993                 hammer2_check_icrc32 += chain->bytes;
4994                 break;
4995         case HAMMER2_CHECK_XXHASH64:
4996                 check64 = XXH64(bdata, chain->bytes, XXH_HAMMER2_SEED);
4997                 r = (chain->bref.check.xxhash64.value == check64);
4998                 if (r == 0) {
4999                         kprintf("chain %016jx.%02x key=%016jx "
5000                                 "meth=%02x CHECK FAIL "
5001                                 "(flags=%08x, bref/data %016jx/%016jx)\n",
5002                                 chain->bref.data_off,
5003                                 chain->bref.type,
5004                                 chain->bref.key,
5005                                 chain->bref.methods,
5006                                 chain->flags,
5007                                 chain->bref.check.xxhash64.value,
5008                                 check64);
5009                 }
5010                 hammer2_check_xxhash64 += chain->bytes;
5011                 break;
5012         case HAMMER2_CHECK_SHA192:
5013                 {
5014                         SHA256_CTX hash_ctx;
5015                         union {
5016                                 uint8_t digest[SHA256_DIGEST_LENGTH];
5017                                 uint64_t digest64[SHA256_DIGEST_LENGTH/8];
5018                         } u;
5019
5020                         SHA256_Init(&hash_ctx);
5021                         SHA256_Update(&hash_ctx, bdata, chain->bytes);
5022                         SHA256_Final(u.digest, &hash_ctx);
5023                         u.digest64[2] ^= u.digest64[3];
5024                         if (bcmp(u.digest,
5025                                  chain->bref.check.sha192.data,
5026                                  sizeof(chain->bref.check.sha192.data)) == 0) {
5027                                 r = 1;
5028                         } else {
5029                                 r = 0;
5030                                 kprintf("chain %016jx.%02x meth=%02x "
5031                                         "CHECK FAIL\n",
5032                                         chain->bref.data_off,
5033                                         chain->bref.type,
5034                                         chain->bref.methods);
5035                         }
5036                 }
5037                 break;
5038         case HAMMER2_CHECK_FREEMAP:
5039                 r = (chain->bref.check.freemap.icrc32 ==
5040                      hammer2_icrc32(bdata, chain->bytes));
5041                 if (r == 0) {
5042                         kprintf("chain %016jx.%02x meth=%02x "
5043                                 "CHECK FAIL\n",
5044                                 chain->bref.data_off,
5045                                 chain->bref.type,
5046                                 chain->bref.methods);
5047                         kprintf("freemap.icrc %08x icrc32 %08x (%d)\n",
5048                                 chain->bref.check.freemap.icrc32,
5049                                 hammer2_icrc32(bdata, chain->bytes),
5050                                                chain->bytes);
5051                         if (chain->dio)
5052                                 kprintf("dio %p buf %016jx,%d bdata %p/%p\n",
5053                                         chain->dio, chain->dio->bp->b_loffset,
5054                                         chain->dio->bp->b_bufsize, bdata,
5055                                         chain->dio->bp->b_data);
5056                 }
5057
5058                 break;
5059         default:
5060                 kprintf("hammer2_chain_setcheck: unknown check type %02x\n",
5061                         chain->bref.methods);
5062                 r = 1;
5063                 break;
5064         }
5065         return r;
5066 }
5067
5068 /*
5069  * Acquire the chain and parent representing the specified inode for the
5070  * device at the specified cluster index.
5071  *
5072  * The flags passed in are LOOKUP flags, not RESOLVE flags.
5073  *
5074  * If we are unable to locate the hardlink, INVAL is returned and *chainp
5075  * will be NULL.  *parentp may still be set error or not, or NULL if the
5076  * parent itself could not be resolved.
5077  *
5078  * Caller must pass-in a valid or NULL *parentp or *chainp.  The passed-in
5079  * *parentp and *chainp will be unlocked if not NULL.
5080  */
5081 int
5082 hammer2_chain_inode_find(hammer2_pfs_t *pmp, hammer2_key_t inum,
5083                          int clindex, int flags,
5084                          hammer2_chain_t **parentp, hammer2_chain_t **chainp)
5085 {
5086         hammer2_chain_t *parent;
5087         hammer2_chain_t *rchain;
5088         hammer2_key_t key_dummy;
5089         int cache_index = -1;
5090         int resolve_flags;
5091
5092         resolve_flags = (flags & HAMMER2_LOOKUP_SHARED) ?
5093                         HAMMER2_RESOLVE_SHARED : 0;
5094
5095         /*
5096          * Caller expects us to replace these.
5097          */
5098         if (*chainp) {
5099                 hammer2_chain_unlock(*chainp);
5100                 hammer2_chain_drop(*chainp);
5101                 *chainp = NULL;
5102         }
5103         if (*parentp) {
5104                 hammer2_chain_unlock(*parentp);
5105                 hammer2_chain_drop(*parentp);
5106                 *parentp = NULL;
5107         }
5108
5109         /*
5110          * Inodes hang off of the iroot (bit 63 is clear, differentiating
5111          * inodes from root directory entries in the key lookup).
5112          */
5113         parent = hammer2_inode_chain(pmp->iroot, clindex, resolve_flags);
5114         rchain = NULL;
5115         if (parent) {
5116                 rchain = hammer2_chain_lookup(&parent, &key_dummy,
5117                                               inum, inum,
5118                                               &cache_index, flags);
5119         }
5120         *parentp = parent;
5121         *chainp = rchain;
5122
5123         return (rchain ? 0 : EINVAL);
5124 }
5125
5126 /*
5127  * Used by the bulkscan code to snapshot the synchronized storage for
5128  * a volume, allowing it to be scanned concurrently against normal
5129  * operation.
5130  */
5131 hammer2_chain_t *
5132 hammer2_chain_bulksnap(hammer2_chain_t *chain)
5133 {
5134         hammer2_chain_t *copy;
5135
5136         copy = hammer2_chain_alloc(chain->hmp, chain->pmp, &chain->bref);
5137         switch(chain->bref.type) {
5138         case HAMMER2_BREF_TYPE_VOLUME:
5139                 copy->data = kmalloc(sizeof(copy->data->voldata),
5140                                      chain->hmp->mchain,
5141                                      M_WAITOK | M_ZERO);
5142                 hammer2_spin_ex(&chain->core.spin);
5143                 copy->data->voldata = chain->data->voldata;
5144                 hammer2_spin_unex(&chain->core.spin);
5145                 break;
5146         case HAMMER2_BREF_TYPE_FREEMAP:
5147                 copy->data = kmalloc(sizeof(hammer2_blockset_t),
5148                                      chain->hmp->mchain,
5149                                      M_WAITOK | M_ZERO);
5150                 hammer2_spin_ex(&chain->core.spin);
5151                 copy->data->blkset = chain->data->blkset;
5152                 hammer2_spin_unex(&chain->core.spin);
5153                 break;
5154         default:
5155                 break;
5156         }
5157         return copy;
5158 }
5159
5160 void
5161 hammer2_chain_bulkdrop(hammer2_chain_t *copy)
5162 {
5163         switch(copy->bref.type) {
5164         case HAMMER2_BREF_TYPE_VOLUME:
5165         case HAMMER2_BREF_TYPE_FREEMAP:
5166                 KKASSERT(copy->data);
5167                 kfree(copy->data, copy->hmp->mchain);
5168                 copy->data = NULL;
5169                 atomic_add_long(&hammer2_chain_allocs, -1);
5170                 break;
5171         default:
5172                 break;
5173         }
5174         hammer2_chain_drop(copy);
5175 }
5176
5177 /*
5178  * Create a snapshot of the specified {parent, ochain} with the specified
5179  * label.  The originating hammer2_inode must be exclusively locked for
5180  * safety.
5181  *
5182  * The ioctl code has already synced the filesystem.
5183  */
5184 int
5185 hammer2_chain_snapshot(hammer2_chain_t *chain, hammer2_ioc_pfs_t *pmp,
5186                        hammer2_tid_t mtid)
5187 {
5188         hammer2_dev_t *hmp;
5189         const hammer2_inode_data_t *ripdata;
5190         hammer2_inode_data_t *wipdata;
5191         hammer2_chain_t *nchain;
5192         hammer2_inode_t *nip;
5193         size_t name_len;
5194         hammer2_key_t lhc;
5195         struct vattr vat;
5196 #if 0
5197         uuid_t opfs_clid;
5198 #endif
5199         int error;
5200
5201         kprintf("snapshot %s\n", pmp->name);
5202
5203         name_len = strlen(pmp->name);
5204         lhc = hammer2_dirhash(pmp->name, name_len);
5205
5206         /*
5207          * Get the clid
5208          */
5209         ripdata = &chain->data->ipdata;
5210 #if 0
5211         opfs_clid = ripdata->meta.pfs_clid;
5212 #endif
5213         hmp = chain->hmp;
5214
5215         /*
5216          * Create the snapshot directory under the super-root
5217          *
5218          * Set PFS type, generate a unique filesystem id, and generate
5219          * a cluster id.  Use the same clid when snapshotting a PFS root,
5220          * which theoretically allows the snapshot to be used as part of
5221          * the same cluster (perhaps as a cache).
5222          *
5223          * Copy the (flushed) blockref array.  Theoretically we could use
5224          * chain_duplicate() but it becomes difficult to disentangle
5225          * the shared core so for now just brute-force it.
5226          */
5227         VATTR_NULL(&vat);
5228         vat.va_type = VDIR;
5229         vat.va_mode = 0755;
5230         nip = hammer2_inode_create(hmp->spmp->iroot, hmp->spmp->iroot,
5231                                    &vat, proc0.p_ucred,
5232                                    pmp->name, name_len, 0,
5233                                    1, 0, 0,
5234                                    HAMMER2_INSERT_PFSROOT, &error);
5235
5236         if (nip) {
5237                 hammer2_inode_modify(nip);
5238                 nchain = hammer2_inode_chain(nip, 0, HAMMER2_RESOLVE_ALWAYS);
5239                 hammer2_chain_modify(nchain, mtid, 0, 0);
5240                 wipdata = &nchain->data->ipdata;
5241
5242                 nip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
5243                 nip->meta.pfs_subtype = HAMMER2_PFSSUBTYPE_SNAPSHOT;
5244                 nip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
5245                 kern_uuidgen(&nip->meta.pfs_fsid, 1);
5246
5247                 /*
5248                  * Give the snapshot its own private cluster id.  As a
5249                  * snapshot no further synchronization with the original
5250                  * cluster will be done.
5251                  */
5252 #if 0
5253                 if (chain->flags & HAMMER2_CHAIN_PFSBOUNDARY)
5254                         nip->meta.pfs_clid = opfs_clid;
5255                 else
5256                         kern_uuidgen(&nip->meta.pfs_clid, 1);
5257 #endif
5258                 kern_uuidgen(&nip->meta.pfs_clid, 1);
5259                 nchain->bref.flags |= HAMMER2_BREF_FLAG_PFSROOT;
5260
5261                 /* XXX hack blockset copy */
5262                 /* XXX doesn't work with real cluster */
5263                 wipdata->meta = nip->meta;
5264                 wipdata->u.blockset = ripdata->u.blockset;
5265                 hammer2_flush(nchain, 1);
5266                 hammer2_chain_unlock(nchain);
5267                 hammer2_chain_drop(nchain);
5268                 hammer2_inode_unlock(nip);
5269         }
5270         return (error);
5271 }
5272
5273 /*
5274  * Returns non-zero if the chain (INODE or DIRENT) matches the
5275  * filename.
5276  */
5277 int
5278 hammer2_chain_dirent_test(hammer2_chain_t *chain, const char *name,
5279                           size_t name_len)
5280 {
5281         const hammer2_inode_data_t *ripdata;
5282         const hammer2_dirent_head_t *den;
5283
5284         if (chain->bref.type == HAMMER2_BREF_TYPE_INODE) {
5285                 ripdata = &chain->data->ipdata;
5286                 if (ripdata->meta.name_len == name_len &&
5287                     bcmp(ripdata->filename, name, name_len) == 0) {
5288                         return 1;
5289                 }
5290         }
5291         if (chain->bref.type == HAMMER2_BREF_TYPE_DIRENT &&
5292            chain->bref.embed.dirent.namlen == name_len) {
5293                 den = &chain->bref.embed.dirent;
5294                 if (name_len > sizeof(chain->bref.check.buf) &&
5295                     bcmp(chain->data->buf, name, name_len) == 0) {
5296                         return 1;
5297                 }
5298                 if (name_len <= sizeof(chain->bref.check.buf) &&
5299                     bcmp(chain->bref.check.buf, name, name_len) == 0) {
5300                         return 1;
5301                 }
5302         }
5303         return 0;
5304 }