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