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