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