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