hammer2 - major simplification of algorithms part 1/many
[dragonfly.git] / sys / vfs / hammer2 / hammer2_chain.c
1 /*
2  * Copyright (c) 2011-2014 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 "hammer2.h"
64
65 static int hammer2_indirect_optimize;   /* XXX SYSCTL */
66
67 static hammer2_chain_t *hammer2_chain_create_indirect(
68                 hammer2_trans_t *trans, hammer2_chain_t *parent,
69                 hammer2_key_t key, int keybits, int for_type, int *errorp);
70 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
71 static hammer2_chain_t *hammer2_combined_find(
72                 hammer2_chain_t *parent,
73                 hammer2_blockref_t *base, int count,
74                 int *cache_indexp, hammer2_key_t *key_nextp,
75                 hammer2_key_t key_beg, hammer2_key_t key_end,
76                 hammer2_blockref_t **bresp);
77
78 /*
79  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
80  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
81  * dbtree or to dbq.
82  *
83  * Chains in delete-duplicate sequences can always iterate through core_entry
84  * to locate the live version of the chain.
85  */
86 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
87
88 int
89 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
90 {
91         hammer2_key_t c1_beg;
92         hammer2_key_t c1_end;
93         hammer2_key_t c2_beg;
94         hammer2_key_t c2_end;
95
96         /*
97          * Compare chains.  Overlaps are not supposed to happen and catch
98          * any software issues early we count overlaps as a match.
99          */
100         c1_beg = chain1->bref.key;
101         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
102         c2_beg = chain2->bref.key;
103         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
104
105         if (c1_end < c2_beg)    /* fully to the left */
106                 return(-1);
107         if (c1_beg > c2_end)    /* fully to the right */
108                 return(1);
109         return(0);              /* overlap (must not cross edge boundary) */
110 }
111
112 static __inline
113 int
114 hammer2_isclusterable(hammer2_chain_t *chain)
115 {
116         if (hammer2_cluster_enable) {
117                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
118                     chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
119                     chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
120                         return(1);
121                 }
122         }
123         return(0);
124 }
125
126 /*
127  * Make a chain visible to the flusher.  The flusher needs to be able to
128  * do flushes of a subdirectory chains or single files so it does a top-down
129  * recursion using the ONFLUSH flag for the recursion.  It locates MODIFIED
130  * or UPDATE chains and flushes back up the chain to the root.
131  */
132 void
133 hammer2_chain_setflush(hammer2_trans_t *trans, hammer2_chain_t *chain)
134 {
135         hammer2_chain_t *parent;
136
137         if ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
138                 spin_lock(&chain->core.cst.spin);
139                 while ((chain->flags & HAMMER2_CHAIN_ONFLUSH) == 0) {
140                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONFLUSH);
141                         if ((parent = chain->parent) == NULL)
142                                 break;
143                         spin_lock(&parent->core.cst.spin);
144                         spin_unlock(&chain->core.cst.spin);
145                         chain = parent;
146                 }
147                 spin_unlock(&chain->core.cst.spin);
148         }
149 }
150
151 /*
152  * Allocate a new disconnected chain element representing the specified
153  * bref.  chain->refs is set to 1 and the passed bref is copied to
154  * chain->bref.  chain->bytes is derived from the bref.
155  *
156  * chain->core is NOT allocated and the media data and bp pointers are left
157  * NULL.  The caller must call chain_core_alloc() to allocate or associate
158  * a core with the chain.
159  *
160  * chain->pmp inherits pmp unless the chain is an inode (other than the
161  * super-root inode).
162  *
163  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
164  */
165 hammer2_chain_t *
166 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
167                     hammer2_trans_t *trans, hammer2_blockref_t *bref)
168 {
169         hammer2_chain_t *chain;
170         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
171
172         /*
173          * Construct the appropriate system structure.
174          */
175         switch(bref->type) {
176         case HAMMER2_BREF_TYPE_INODE:
177         case HAMMER2_BREF_TYPE_INDIRECT:
178         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
179         case HAMMER2_BREF_TYPE_DATA:
180         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
181                 /*
182                  * Chain's are really only associated with the hmp but we
183                  * maintain a pmp association for per-mount memory tracking
184                  * purposes.  The pmp can be NULL.
185                  */
186                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
187                 break;
188         case HAMMER2_BREF_TYPE_VOLUME:
189         case HAMMER2_BREF_TYPE_FREEMAP:
190                 chain = NULL;
191                 panic("hammer2_chain_alloc volume type illegal for op");
192         default:
193                 chain = NULL;
194                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
195                       bref->type);
196         }
197
198         /*
199          * Initialize the new chain structure.
200          */
201         chain->pmp = pmp;
202         chain->hmp = hmp;
203         chain->bref = *bref;
204         chain->bytes = bytes;
205         chain->refs = 1;
206         chain->flags = HAMMER2_CHAIN_ALLOCATED;
207
208         /*
209          * Set the PFS boundary flag if this chain represents a PFS root.
210          */
211         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
212                 chain->flags |= HAMMER2_CHAIN_PFSBOUNDARY;
213
214         return (chain);
215 }
216
217 /*
218  * Associate an existing core with the chain or allocate a new core.
219  *
220  * The core is not locked.  No additional refs on the chain are made.
221  * (trans) must not be NULL if (core) is not NULL.
222  *
223  * When chains are delete-duplicated during flushes we insert nchain on
224  * the ownerq after ochain instead of at the end in order to give the
225  * drop code visibility in the correct order, otherwise drops can be missed.
226  */
227 void
228 hammer2_chain_core_alloc(hammer2_trans_t *trans, hammer2_chain_t *chain)
229 {
230         hammer2_chain_core_t *core = &chain->core;
231
232         /*
233          * Fresh core under nchain (no multi-homing of ochain's
234          * sub-tree).
235          */
236         RB_INIT(&core->rbtree); /* live chains */
237         ccms_cst_init(&core->cst, chain);
238 }
239
240 /*
241  * Add a reference to a chain element, preventing its destruction.
242  */
243 void
244 hammer2_chain_ref(hammer2_chain_t *chain)
245 {
246         atomic_add_int(&chain->refs, 1);
247 }
248
249 /*
250  * Insert the chain in the core rbtree.
251  *
252  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
253  * chain is a special case used by the flush code that is placed on the
254  * unstaged deleted list to avoid confusing the live view.
255  */
256 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
257 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
258 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
259
260 static
261 int
262 hammer2_chain_insert(hammer2_chain_t *parent, hammer2_chain_t *chain,
263                      int flags, int generation)
264 {
265         hammer2_chain_t *xchain;
266         int error = 0;
267
268         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
269                 spin_lock(&parent->core.cst.spin);
270
271         /*
272          * Interlocked by spinlock, check for race
273          */
274         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
275             parent->core.generation != generation) {
276                 error = EAGAIN;
277                 goto failed;
278         }
279
280         /*
281          * Insert chain
282          */
283         xchain = RB_INSERT(hammer2_chain_tree, &parent->core.rbtree, chain);
284         KASSERT(xchain == NULL,
285                 ("hammer2_chain_insert: collision %p %p", chain, xchain));
286         atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
287         chain->parent = parent;
288         ++parent->core.chain_count;
289         ++parent->core.generation;      /* XXX incs for _get() too, XXX */
290
291         /*
292          * We have to keep track of the effective live-view blockref count
293          * so the create code knows when to push an indirect block.
294          */
295         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
296                 atomic_add_int(&parent->core.live_count, 1);
297 failed:
298         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
299                 spin_unlock(&parent->core.cst.spin);
300         return error;
301 }
302
303 /*
304  * Drop the caller's reference to the chain.  When the ref count drops to
305  * zero this function will try to disassociate the chain from its parent and
306  * deallocate it, then recursely drop the parent using the implied ref
307  * from the chain's chain->parent.
308  */
309 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain);
310
311 void
312 hammer2_chain_drop(hammer2_chain_t *chain)
313 {
314         u_int refs;
315         u_int need = 0;
316
317         if (hammer2_debug & 0x200000)
318                 Debugger("drop");
319
320         if (chain->flags & HAMMER2_CHAIN_UPDATE)
321                 ++need;
322         if (chain->flags & HAMMER2_CHAIN_MODIFIED)
323                 ++need;
324         KKASSERT(chain->refs > need);
325
326         while (chain) {
327                 refs = chain->refs;
328                 cpu_ccfence();
329                 KKASSERT(refs > 0);
330
331                 if (refs == 1) {
332                         chain = hammer2_chain_lastdrop(chain);
333                 } else {
334                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
335                                 break;
336                         /* retry the same chain */
337                 }
338         }
339 }
340
341 /*
342  * Safe handling of the 1->0 transition on chain.  Returns a chain for
343  * recursive drop or NULL, possibly returning the same chain if the atomic
344  * op fails.
345  *
346  * Whem two chains need to be recursively dropped we use the chain
347  * we would otherwise free to placehold the additional chain.  It's a bit
348  * convoluted but we can't just recurse without potentially blowing out
349  * the kernel stack.
350  *
351  * The chain cannot be freed if it has a non-empty core (children) or
352  * it is not at the head of ownerq.
353  *
354  * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
355  */
356 static
357 hammer2_chain_t *
358 hammer2_chain_lastdrop(hammer2_chain_t *chain)
359 {
360         hammer2_pfsmount_t *pmp;
361         hammer2_mount_t *hmp;
362         hammer2_chain_t *parent;
363         hammer2_chain_t *rdrop;
364
365         /*
366          * Spinlock the core and check to see if it is empty.  If it is
367          * not empty we leave chain intact with refs == 0.  The elements
368          * in core->rbtree are associated with other chains contemporary
369          * with ours but not with our chain directly.
370          */
371         spin_lock(&chain->core.cst.spin);
372
373         /*
374          * We can't free non-stale chains with children until we are
375          * able to free the children because there might be a flush
376          * dependency.  Flushes of stale children (which should also
377          * have their deleted flag set) short-cut recursive flush
378          * dependencies and can be freed here.  Any flushes which run
379          * through stale children due to the flush synchronization
380          * point should have a FLUSH_* bit set in the chain and not
381          * reach lastdrop at this time.
382          *
383          * NOTE: We return (chain) on failure to retry.
384          */
385         if (chain->core.chain_count) {
386                 if (atomic_cmpset_int(&chain->refs, 1, 0)) {
387                         spin_unlock(&chain->core.cst.spin);
388                         chain = NULL;   /* success */
389                 } else {
390                         spin_unlock(&chain->core.cst.spin);
391                 }
392                 return(chain);
393         }
394         /* no chains left under us */
395
396         /*
397          * chain->core has no children left so no accessors can get to our
398          * chain from there.  Now we have to lock the parent core to interlock
399          * remaining possible accessors that might bump chain's refs before
400          * we can safely drop chain's refs with intent to free the chain.
401          */
402         hmp = chain->hmp;
403         pmp = chain->pmp;       /* can be NULL */
404         rdrop = NULL;
405
406         /*
407          * Spinlock the parent and try to drop the last ref on chain.
408          * On success remove chain from its parent, otherwise return NULL.
409          *
410          * (normal core locks are top-down recursive but we define core
411          *  spinlocks as bottom-up recursive, so this is safe).
412          */
413         if ((parent = chain->parent) != NULL) {
414                 spin_lock(&parent->core.cst.spin);
415                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
416                         /* 1->0 transition failed */
417                         spin_unlock(&parent->core.cst.spin);
418                         spin_unlock(&chain->core.cst.spin);
419                         return(chain);  /* retry */
420                 }
421
422                 /*
423                  * 1->0 transition successful, remove chain from its
424                  * above core.
425                  */
426                 if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
427                         RB_REMOVE(hammer2_chain_tree,
428                                   &parent->core.rbtree, chain);
429                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
430                         --parent->core.chain_count;
431                         chain->parent = NULL;
432                 }
433
434                 /*
435                  * If our chain was the last chain in the parent's core the
436                  * core is now empty and its parent might have to be
437                  * re-dropped if it has 0 refs.
438                  */
439                 if (parent->core.chain_count == 0) {
440                         rdrop = parent;
441                         if (atomic_cmpset_int(&rdrop->refs, 0, 1) == 0) {
442                                 rdrop = NULL;
443                         }
444                 }
445                 spin_unlock(&parent->core.cst.spin);
446                 parent = NULL;  /* safety */
447         }
448
449         /*
450          * Successful 1->0 transition and the chain can be destroyed now.
451          *
452          * We still have the core spinlock, and core's chain_count is 0.
453          * Any parent spinlock is gone.
454          */
455         spin_unlock(&chain->core.cst.spin);
456         KKASSERT(RB_EMPTY(&chain->core.rbtree) &&
457                  chain->core.chain_count == 0);
458         KKASSERT(chain->core.cst.count == 0);
459         KKASSERT(chain->core.cst.upgrade == 0);
460
461         /*
462          * All spin locks are gone, finish freeing stuff.
463          */
464         KKASSERT((chain->flags & (HAMMER2_CHAIN_UPDATE |
465                                   HAMMER2_CHAIN_MODIFIED)) == 0);
466         hammer2_chain_drop_data(chain, 1);
467
468         KKASSERT(chain->dio == NULL);
469
470         /*
471          * Once chain resources are gone we can use the now dead chain
472          * structure to placehold what might otherwise require a recursive
473          * drop, because we have potentially two things to drop and can only
474          * return one directly.
475          */
476         if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
477                 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
478                 chain->hmp = NULL;
479                 kfree(chain, hmp->mchain);
480         }
481
482         /*
483          * Possible chaining loop when parent re-drop needed.
484          */
485         return(rdrop);
486 }
487
488 /*
489  * On either last lock release or last drop
490  */
491 static void
492 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
493 {
494         /*hammer2_mount_t *hmp = chain->hmp;*/
495
496         switch(chain->bref.type) {
497         case HAMMER2_BREF_TYPE_VOLUME:
498         case HAMMER2_BREF_TYPE_FREEMAP:
499                 if (lastdrop)
500                         chain->data = NULL;
501                 break;
502         default:
503                 KKASSERT(chain->data == NULL);
504                 break;
505         }
506 }
507
508 /*
509  * Ref and lock a chain element, acquiring its data with I/O if necessary,
510  * and specify how you would like the data to be resolved.
511  *
512  * Returns 0 on success or an error code if the data could not be acquired.
513  * The chain element is locked on return regardless of whether an error
514  * occurred or not.
515  *
516  * The lock is allowed to recurse, multiple locking ops will aggregate
517  * the requested resolve types.  Once data is assigned it will not be
518  * removed until the last unlock.
519  *
520  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
521  *                         (typically used to avoid device/logical buffer
522  *                          aliasing for data)
523  *
524  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
525  *                         the INITIAL-create state (indirect blocks only).
526  *
527  *                         Do not resolve data elements for DATA chains.
528  *                         (typically used to avoid device/logical buffer
529  *                          aliasing for data)
530  *
531  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
532  *
533  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
534  *                         it will be locked exclusive.
535  *
536  * NOTE: Embedded elements (volume header, inodes) are always resolved
537  *       regardless.
538  *
539  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
540  *       element will instantiate and zero its buffer, and flush it on
541  *       release.
542  *
543  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
544  *       so as not to instantiate a device buffer, which could alias against
545  *       a logical file buffer.  However, if ALWAYS is specified the
546  *       device buffer will be instantiated anyway.
547  *
548  * WARNING! If data must be fetched a shared lock will temporarily be
549  *          upgraded to exclusive.  However, a deadlock can occur if
550  *          the caller owns more than one shared lock.
551  */
552 int
553 hammer2_chain_lock(hammer2_chain_t *chain, int how)
554 {
555         hammer2_mount_t *hmp;
556         hammer2_blockref_t *bref;
557         ccms_state_t ostate;
558         char *bdata;
559         int error;
560
561         /*
562          * Ref and lock the element.  Recursive locks are allowed.
563          */
564         if ((how & HAMMER2_RESOLVE_NOREF) == 0)
565                 hammer2_chain_ref(chain);
566         atomic_add_int(&chain->lockcnt, 1);
567
568         hmp = chain->hmp;
569         KKASSERT(hmp != NULL);
570
571         /*
572          * Get the appropriate lock.
573          */
574         if (how & HAMMER2_RESOLVE_SHARED)
575                 ccms_thread_lock(&chain->core.cst, CCMS_STATE_SHARED);
576         else
577                 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
578
579         /*
580          * If we already have a valid data pointer no further action is
581          * necessary.
582          */
583         if (chain->data)
584                 return (0);
585
586         /*
587          * Do we have to resolve the data?
588          */
589         switch(how & HAMMER2_RESOLVE_MASK) {
590         case HAMMER2_RESOLVE_NEVER:
591                 return(0);
592         case HAMMER2_RESOLVE_MAYBE:
593                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
594                         return(0);
595                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
596                         return(0);
597 #if 0
598                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
599                         return(0);
600 #endif
601                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
602                         return(0);
603                 /* fall through */
604         case HAMMER2_RESOLVE_ALWAYS:
605                 break;
606         }
607
608         /*
609          * Upgrade to an exclusive lock so we can safely manipulate the
610          * buffer cache.  If another thread got to it before us we
611          * can just return.
612          */
613         ostate = ccms_thread_lock_upgrade(&chain->core.cst);
614         if (chain->data) {
615                 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
616                 return (0);
617         }
618
619         /*
620          * We must resolve to a device buffer, either by issuing I/O or
621          * by creating a zero-fill element.  We do not mark the buffer
622          * dirty when creating a zero-fill element (the hammer2_chain_modify()
623          * API must still be used to do that).
624          *
625          * The device buffer is variable-sized in powers of 2 down
626          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
627          * chunk always contains buffers of the same size. (XXX)
628          *
629          * The minimum physical IO size may be larger than the variable
630          * block size.
631          */
632         bref = &chain->bref;
633
634         /*
635          * The getblk() optimization can only be used on newly created
636          * elements if the physical block size matches the request.
637          */
638         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
639                 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
640                                         &chain->dio);
641         } else {
642                 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
643                                          &chain->dio);
644                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
645         }
646
647         if (error) {
648                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
649                         (intmax_t)bref->data_off, error);
650                 hammer2_io_bqrelse(&chain->dio);
651                 ccms_thread_lock_downgrade(&chain->core.cst, ostate);
652                 return (error);
653         }
654
655 #if 0
656         /*
657          * No need for this, always require that hammer2_chain_modify()
658          * be called before any modifying operations.
659          */
660         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
661             !hammer2_io_isdirty(chain->dio)) {
662                 hammer2_io_setdirty(chain->dio);
663         }
664 #endif
665
666         /*
667          * Clear INITIAL.  In this case we used io_new() and the buffer has
668          * been zero'd and marked dirty.
669          */
670         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
671         if (chain->flags & HAMMER2_CHAIN_INITIAL)
672                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
673
674         /*
675          * Setup the data pointer, either pointing it to an embedded data
676          * structure and copying the data from the buffer, or pointing it
677          * into the buffer.
678          *
679          * The buffer is not retained when copying to an embedded data
680          * structure in order to avoid potential deadlocks or recursions
681          * on the same physical buffer.
682          */
683         switch (bref->type) {
684         case HAMMER2_BREF_TYPE_VOLUME:
685         case HAMMER2_BREF_TYPE_FREEMAP:
686                 /*
687                  * Copy data from bp to embedded buffer
688                  */
689                 panic("hammer2_chain_lock: called on unresolved volume header");
690                 break;
691         case HAMMER2_BREF_TYPE_INODE:
692         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
693         case HAMMER2_BREF_TYPE_INDIRECT:
694         case HAMMER2_BREF_TYPE_DATA:
695         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
696         default:
697                 /*
698                  * Point data at the device buffer and leave dio intact.
699                  */
700                 chain->data = (void *)bdata;
701                 break;
702         }
703         ccms_thread_lock_downgrade(&chain->core.cst, ostate);
704         return (0);
705 }
706
707 /*
708  * This basically calls hammer2_io_breadcb() but does some pre-processing
709  * of the chain first to handle certain cases.
710  */
711 void
712 hammer2_chain_load_async(hammer2_cluster_t *cluster,
713                          void (*callback)(hammer2_io_t *dio,
714                                           hammer2_cluster_t *cluster,
715                                           hammer2_chain_t *chain,
716                                           void *arg_p, off_t arg_o),
717                          void *arg_p)
718 {
719         hammer2_chain_t *chain;
720         hammer2_mount_t *hmp;
721         struct hammer2_io *dio;
722         hammer2_blockref_t *bref;
723         int error;
724         int i;
725
726         /*
727          * If no chain specified see if any chain data is available and use
728          * that, otherwise begin an I/O iteration using the first chain.
729          */
730         chain = NULL;
731         for (i = 0; i < cluster->nchains; ++i) {
732                 chain = cluster->array[i];
733                 if (chain && chain->data)
734                         break;
735         }
736         if (i == cluster->nchains) {
737                 chain = cluster->array[0];
738                 i = 0;
739         }
740
741         if (chain->data) {
742                 callback(NULL, cluster, chain, arg_p, (off_t)i);
743                 return;
744         }
745
746         /*
747          * We must resolve to a device buffer, either by issuing I/O or
748          * by creating a zero-fill element.  We do not mark the buffer
749          * dirty when creating a zero-fill element (the hammer2_chain_modify()
750          * API must still be used to do that).
751          *
752          * The device buffer is variable-sized in powers of 2 down
753          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
754          * chunk always contains buffers of the same size. (XXX)
755          *
756          * The minimum physical IO size may be larger than the variable
757          * block size.
758          */
759         bref = &chain->bref;
760         hmp = chain->hmp;
761
762         /*
763          * The getblk() optimization can only be used on newly created
764          * elements if the physical block size matches the request.
765          */
766         if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
767             chain->bytes == hammer2_devblksize(chain->bytes)) {
768                 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
769                 KKASSERT(error == 0);
770                 callback(dio, cluster, chain, arg_p, (off_t)i);
771                 return;
772         }
773
774         /*
775          * Otherwise issue a read
776          */
777         hammer2_adjreadcounter(&chain->bref, chain->bytes);
778         hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
779                            callback, cluster, chain, arg_p, (off_t)i);
780 }
781
782 /*
783  * Unlock and deref a chain element.
784  *
785  * On the last lock release any non-embedded data (chain->dio) will be
786  * retired.
787  */
788 void
789 hammer2_chain_unlock(hammer2_chain_t *chain)
790 {
791         ccms_state_t ostate;
792         long *counterp;
793         u_int lockcnt;
794
795         /*
796          * The core->cst lock can be shared across several chains so we
797          * need to track the per-chain lockcnt separately.
798          *
799          * If multiple locks are present (or being attempted) on this
800          * particular chain we can just unlock, drop refs, and return.
801          *
802          * Otherwise fall-through on the 1->0 transition.
803          */
804         for (;;) {
805                 lockcnt = chain->lockcnt;
806                 KKASSERT(lockcnt > 0);
807                 cpu_ccfence();
808                 if (lockcnt > 1) {
809                         if (atomic_cmpset_int(&chain->lockcnt,
810                                               lockcnt, lockcnt - 1)) {
811                                 ccms_thread_unlock(&chain->core.cst);
812                                 hammer2_chain_drop(chain);
813                                 return;
814                         }
815                 } else {
816                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
817                                 break;
818                 }
819                 /* retry */
820         }
821
822         /*
823          * On the 1->0 transition we upgrade the core lock (if necessary)
824          * to exclusive for terminal processing.  If after upgrading we find
825          * that lockcnt is non-zero, another thread is racing us and will
826          * handle the unload for us later on, so just cleanup and return
827          * leaving the data/io intact
828          *
829          * Otherwise if lockcnt is still 0 it is possible for it to become
830          * non-zero and race, but since we hold the core->cst lock
831          * exclusively all that will happen is that the chain will be
832          * reloaded after we unload it.
833          */
834         ostate = ccms_thread_lock_upgrade(&chain->core.cst);
835         if (chain->lockcnt) {
836                 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
837                 hammer2_chain_drop(chain);
838                 return;
839         }
840
841         /*
842          * Shortcut the case if the data is embedded or not resolved.
843          *
844          * Do NOT NULL out chain->data (e.g. inode data), it might be
845          * dirty.
846          */
847         if (chain->dio == NULL) {
848                 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
849                         hammer2_chain_drop_data(chain, 0);
850                 ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
851                 hammer2_chain_drop(chain);
852                 return;
853         }
854
855         /*
856          * Statistics
857          */
858         if (hammer2_io_isdirty(chain->dio) == 0) {
859                 ;
860         } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
861                 switch(chain->bref.type) {
862                 case HAMMER2_BREF_TYPE_DATA:
863                         counterp = &hammer2_ioa_file_write;
864                         break;
865                 case HAMMER2_BREF_TYPE_INODE:
866                         counterp = &hammer2_ioa_meta_write;
867                         break;
868                 case HAMMER2_BREF_TYPE_INDIRECT:
869                         counterp = &hammer2_ioa_indr_write;
870                         break;
871                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
872                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
873                         counterp = &hammer2_ioa_fmap_write;
874                         break;
875                 default:
876                         counterp = &hammer2_ioa_volu_write;
877                         break;
878                 }
879                 *counterp += chain->bytes;
880         } else {
881                 switch(chain->bref.type) {
882                 case HAMMER2_BREF_TYPE_DATA:
883                         counterp = &hammer2_iod_file_write;
884                         break;
885                 case HAMMER2_BREF_TYPE_INODE:
886                         counterp = &hammer2_iod_meta_write;
887                         break;
888                 case HAMMER2_BREF_TYPE_INDIRECT:
889                         counterp = &hammer2_iod_indr_write;
890                         break;
891                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
892                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
893                         counterp = &hammer2_iod_fmap_write;
894                         break;
895                 default:
896                         counterp = &hammer2_iod_volu_write;
897                         break;
898                 }
899                 *counterp += chain->bytes;
900         }
901
902         /*
903          * Clean out the dio.
904          *
905          * If a device buffer was used for data be sure to destroy the
906          * buffer when we are done to avoid aliases (XXX what about the
907          * underlying VM pages?).
908          *
909          * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
910          *       is possible.
911          *
912          * NOTE: The isdirty check tracks whether we have to bdwrite() the
913          *       buffer or not.  The buffer might already be dirty.  The
914          *       flag is re-set when chain_modify() is called, even if
915          *       MODIFIED is already set, allowing the OS to retire the
916          *       buffer independent of a hammer2 flush.
917          */
918         chain->data = NULL;
919         if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
920             hammer2_io_isdirty(chain->dio)) {
921                 hammer2_io_bawrite(&chain->dio);
922         } else {
923                 hammer2_io_bqrelse(&chain->dio);
924         }
925         ccms_thread_unlock_upgraded(&chain->core.cst, ostate);
926         hammer2_chain_drop(chain);
927 }
928
929 /*
930  * This counts the number of live blockrefs in a block array and
931  * also calculates the point at which all remaining blockrefs are empty.
932  * This routine can only be called on a live chain (DUPLICATED flag not set).
933  *
934  * NOTE: Flag is not set until after the count is complete, allowing
935  *       callers to test the flag without holding the spinlock.
936  *
937  * NOTE: If base is NULL the related chain is still in the INITIAL
938  *       state and there are no blockrefs to count.
939  *
940  * NOTE: live_count may already have some counts accumulated due to
941  *       creation and deletion and could even be initially negative.
942  */
943 void
944 hammer2_chain_countbrefs(hammer2_chain_t *chain,
945                          hammer2_blockref_t *base, int count)
946 {
947         spin_lock(&chain->core.cst.spin);
948         if ((chain->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
949                 if (base) {
950                         while (--count >= 0) {
951                                 if (base[count].type)
952                                         break;
953                         }
954                         chain->core.live_zero = count + 1;
955                         while (count >= 0) {
956                                 if (base[count].type)
957                                         atomic_add_int(&chain->core.live_count,
958                                                        1);
959                                 --count;
960                         }
961                 } else {
962                         chain->core.live_zero = 0;
963                 }
964                 /* else do not modify live_count */
965                 atomic_set_int(&chain->core.flags, HAMMER2_CORE_COUNTEDBREFS);
966         }
967         spin_unlock(&chain->core.cst.spin);
968 }
969
970 /*
971  * Resize the chain's physical storage allocation in-place.  This will
972  * modify the passed-in chain.  Chains can be resized smaller without
973  * reallocating the storage.  Resizing larger will reallocate the storage.
974  * Excess or prior storage is reclaimed asynchronously at a later time.
975  *
976  * Must be passed an exclusively locked parent and chain.
977  *
978  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
979  * to avoid instantiating a device buffer that conflicts with the vnode data
980  * buffer.  That is, the passed-in bp is a logical buffer, whereas any
981  * chain-oriented bp would be a device buffer.
982  *
983  * XXX return error if cannot resize.
984  */
985 void
986 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
987                      hammer2_chain_t *parent, hammer2_chain_t *chain,
988                      int nradix, int flags)
989 {
990         hammer2_mount_t *hmp;
991         size_t obytes;
992         size_t nbytes;
993
994         hmp = chain->hmp;
995
996         /*
997          * Only data and indirect blocks can be resized for now.
998          * (The volu root, inodes, and freemap elements use a fixed size).
999          */
1000         KKASSERT(chain != &hmp->vchain);
1001         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1002                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1003
1004         /*
1005          * Nothing to do if the element is already the proper size
1006          */
1007         obytes = chain->bytes;
1008         nbytes = 1U << nradix;
1009         if (obytes == nbytes)
1010                 return;
1011
1012         /*
1013          * The parent does not have to be locked for the delete/duplicate call,
1014          * but is in this particular code path.
1015          *
1016          * NOTE: If we are not crossing a synchronization point the
1017          *       duplication code will simply reuse the existing chain
1018          *       structure.
1019          *
1020          * NOTE: The modify will set BMAPUPD for us if BMAPPED is set.
1021          */
1022         hammer2_chain_modify(trans, chain, 0);
1023
1024         /*
1025          * Relocate the block, even if making it smaller (because different
1026          * block sizes may be in different regions).
1027          *
1028          * (data blocks only, we aren't copying the storage here).
1029          */
1030         hammer2_freemap_alloc(trans, chain, nbytes);
1031         chain->bytes = nbytes;
1032         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1033         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1034
1035         /*
1036          * For now just support it on DATA chains (and not on indirect
1037          * blocks).
1038          */
1039         KKASSERT(chain->dio == NULL);
1040 }
1041
1042 #if 0
1043
1044 /*
1045  * REMOVED - see cluster code
1046  *
1047  * Set a chain modified, making it read-write and duplicating it if necessary.
1048  * This function will assign a new physical block to the chain if necessary
1049  *
1050  * Duplication of already-modified chains is possible when the modification
1051  * crosses a flush synchronization boundary.
1052  *
1053  * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1054  *                   level or the COW operation will not work.
1055  *
1056  * Data blocks     - The chain is usually locked RESOLVE_NEVER so as not to
1057  *                   run the data through the device buffers.
1058  *
1059  * This function may return a different chain than was passed, in which case
1060  * the old chain will be unlocked and the new chain will be locked.
1061  *
1062  * ip->chain may be adjusted by hammer2_chain_modify_ip().
1063  */
1064 hammer2_inode_data_t *
1065 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1066                         hammer2_chain_t **chainp, int flags)
1067 {
1068         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1069         hammer2_chain_modify(trans, chainp, flags);
1070         if (ip->chain != *chainp)
1071                 hammer2_inode_repoint(ip, NULL, *chainp);
1072         if (ip->vp)
1073                 vsetisdirty(ip->vp);
1074         return(&ip->chain->data->ipdata);
1075 }
1076
1077 #endif
1078
1079 void
1080 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
1081 {
1082         hammer2_mount_t *hmp;
1083         hammer2_io_t *dio;
1084         int error;
1085         int wasinitial;
1086         int newmod;
1087         char *bdata;
1088
1089         hmp = chain->hmp;
1090
1091         /*
1092          * data is not optional for freemap chains (we must always be sure
1093          * to copy the data on COW storage allocations).
1094          */
1095         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1096             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1097                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1098                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1099         }
1100
1101         /*
1102          * Data must be resolved if already assigned unless explicitly
1103          * flagged otherwise.
1104          */
1105         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1106             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1107                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1108                 hammer2_chain_unlock(chain);
1109         }
1110
1111         /*
1112          * Otherwise do initial-chain handling.  Set MODIFIED to indicate
1113          * that the chain has been modified.  Set UPDATE to ensure that
1114          * the blockref is updated in the parent.
1115          */
1116         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1117                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1118                 hammer2_chain_ref(chain);
1119                 hammer2_pfs_memory_inc(chain->pmp);
1120                 newmod = 1;
1121         } else {
1122                 newmod = 0;
1123         }
1124         if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
1125                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
1126                 hammer2_chain_ref(chain);
1127         }
1128
1129         /*
1130          * The modification or re-modification requires an allocation and
1131          * possible COW.
1132          *
1133          * We normally always allocate new storage here.  If storage exists
1134          * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1135          */
1136         if (chain != &hmp->vchain && chain != &hmp->fchain) {
1137                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1138                      ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 && newmod)
1139                 ) {
1140                         hammer2_freemap_alloc(trans, chain, chain->bytes);
1141                         /* XXX failed allocation */
1142                 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1143                         hammer2_freemap_alloc(trans, chain, chain->bytes);
1144                         /* XXX failed allocation */
1145                 }
1146                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1147         }
1148
1149         /*
1150          * Set BMAPUPD to tell the flush code that an existing blockmap entry
1151          * requires updating as well as to tell the delete code that the
1152          * chain's blockref might not exactly match (in terms of physical size
1153          * or block offset) the one in the parent's blocktable.  The base key
1154          * of course will still match.
1155          */
1156         if (chain->flags & HAMMER2_CHAIN_BMAPPED)
1157                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPUPD);
1158
1159         /*
1160          * Do not COW BREF_TYPE_DATA when OPTDATA is set.  This is because
1161          * data modifications are done via the logical buffer cache so COWing
1162          * it here would result in unnecessary extra copies (and possibly extra
1163          * block reallocations).  The INITIAL flag remains unchanged in this
1164          * situation.
1165          *
1166          * (This is a bit of a hack).
1167          */
1168         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1169             (flags & HAMMER2_MODIFY_OPTDATA)) {
1170                 goto skip2;
1171         }
1172
1173         /*
1174          * Clearing the INITIAL flag (for indirect blocks) indicates that
1175          * we've processed the uninitialized storage allocation.
1176          *
1177          * If this flag is already clear we are likely in a copy-on-write
1178          * situation but we have to be sure NOT to bzero the storage if
1179          * no data is present.
1180          */
1181         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1182                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1183                 wasinitial = 1;
1184         } else {
1185                 wasinitial = 0;
1186         }
1187
1188         /*
1189          * Instantiate data buffer and possibly execute COW operation
1190          */
1191         switch(chain->bref.type) {
1192         case HAMMER2_BREF_TYPE_VOLUME:
1193         case HAMMER2_BREF_TYPE_FREEMAP:
1194                 /*
1195                  * The data is embedded, no copy-on-write operation is
1196                  * needed.
1197                  */
1198                 KKASSERT(chain->dio == NULL);
1199                 break;
1200         case HAMMER2_BREF_TYPE_INODE:
1201         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1202         case HAMMER2_BREF_TYPE_DATA:
1203         case HAMMER2_BREF_TYPE_INDIRECT:
1204         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1205                 /*
1206                  * Perform the copy-on-write operation
1207                  *
1208                  * zero-fill or copy-on-write depending on whether
1209                  * chain->data exists or not and set the dirty state for
1210                  * the new buffer.  hammer2_io_new() will handle the
1211                  * zero-fill.
1212                  */
1213                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1214
1215                 if (wasinitial) {
1216                         error = hammer2_io_new(hmp, chain->bref.data_off,
1217                                                chain->bytes, &dio);
1218                 } else {
1219                         error = hammer2_io_bread(hmp, chain->bref.data_off,
1220                                                  chain->bytes, &dio);
1221                 }
1222                 hammer2_adjreadcounter(&chain->bref, chain->bytes);
1223                 KKASSERT(error == 0);
1224
1225                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1226
1227                 if (chain->data) {
1228                         KKASSERT(chain->dio != NULL);
1229                         if (chain->data != (void *)bdata) {
1230                                 bcopy(chain->data, bdata, chain->bytes);
1231                         }
1232                 } else if (wasinitial == 0) {
1233                         /*
1234                          * We have a problem.  We were asked to COW but
1235                          * we don't have any data to COW with!
1236                          */
1237                         panic("hammer2_chain_modify: having a COW %p\n",
1238                               chain);
1239                 }
1240
1241                 /*
1242                  * Retire the old buffer, replace with the new
1243                  */
1244                 if (chain->dio)
1245                         hammer2_io_brelse(&chain->dio);
1246                 chain->data = (void *)bdata;
1247                 chain->dio = dio;
1248                 hammer2_io_setdirty(dio);       /* modified by bcopy above */
1249                 break;
1250         default:
1251                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1252                       chain->bref.type);
1253                 break;
1254
1255         }
1256 skip2:
1257         /*
1258          * setflush on parent indicating that the parent must recurse down
1259          * to us.  Do not call on chain itself which might already have it
1260          * set.
1261          */
1262         if (chain->parent)
1263                 hammer2_chain_setflush(trans, chain->parent);
1264 }
1265
1266 /*
1267  * Volume header data locks
1268  */
1269 void
1270 hammer2_voldata_lock(hammer2_mount_t *hmp)
1271 {
1272         lockmgr(&hmp->vollk, LK_EXCLUSIVE);
1273 }
1274
1275 void
1276 hammer2_voldata_unlock(hammer2_mount_t *hmp)
1277 {
1278         lockmgr(&hmp->vollk, LK_RELEASE);
1279 }
1280
1281 void
1282 hammer2_voldata_modify(hammer2_mount_t *hmp)
1283 {
1284         if ((hmp->vchain.flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1285                 atomic_set_int(&hmp->vchain.flags, HAMMER2_CHAIN_MODIFIED);
1286                 hammer2_chain_ref(&hmp->vchain);
1287                 hammer2_pfs_memory_inc(hmp->vchain.pmp);
1288         }
1289 }
1290
1291 /*
1292  * This function returns the chain at the nearest key within the specified
1293  * range.  The core spinlock must be held on call and the returned chain
1294  * will be referenced but not locked.
1295  *
1296  * This function will recurse through chain->rbtree as necessary and will
1297  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1298  * the iteration value is less than the current value of *key_nextp.
1299  *
1300  * The caller should use (*key_nextp) to calculate the actual range of
1301  * the returned element, which will be (key_beg to *key_nextp - 1), because
1302  * there might be another element which is superior to the returned element
1303  * and overlaps it.
1304  *
1305  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1306  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1307  * it will wind up being (key_end + 1).
1308  */
1309 struct hammer2_chain_find_info {
1310         hammer2_chain_t         *best;
1311         hammer2_key_t           key_beg;
1312         hammer2_key_t           key_end;
1313         hammer2_key_t           key_next;
1314 };
1315
1316 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1317 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1318
1319 static
1320 hammer2_chain_t *
1321 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1322                           hammer2_key_t key_beg, hammer2_key_t key_end)
1323 {
1324         struct hammer2_chain_find_info info;
1325
1326         info.best = NULL;
1327         info.key_beg = key_beg;
1328         info.key_end = key_end;
1329         info.key_next = *key_nextp;
1330
1331         RB_SCAN(hammer2_chain_tree, &parent->core.rbtree,
1332                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1333                 &info);
1334         *key_nextp = info.key_next;
1335 #if 0
1336         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1337                 parent, key_beg, key_end, *key_nextp);
1338 #endif
1339
1340         return (info.best);
1341 }
1342
1343 static
1344 int
1345 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1346 {
1347         struct hammer2_chain_find_info *info = data;
1348         hammer2_key_t child_beg;
1349         hammer2_key_t child_end;
1350
1351         child_beg = child->bref.key;
1352         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1353
1354         if (child_end < info->key_beg)
1355                 return(-1);
1356         if (child_beg > info->key_end)
1357                 return(1);
1358         return(0);
1359 }
1360
1361 static
1362 int
1363 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1364 {
1365         struct hammer2_chain_find_info *info = data;
1366         hammer2_chain_t *best;
1367         hammer2_key_t child_end;
1368
1369         /*
1370          * WARNING! Do not discard DUPLICATED chains, it is possible that
1371          *          we are catching an insertion half-way done.  If a
1372          *          duplicated chain turns out to be the best choice the
1373          *          caller will re-check its flags after locking it.
1374          *
1375          * WARNING! Layerq is scanned forwards, exact matches should keep
1376          *          the existing info->best.
1377          */
1378         if ((best = info->best) == NULL) {
1379                 /*
1380                  * No previous best.  Assign best
1381                  */
1382                 info->best = child;
1383         } else if (best->bref.key <= info->key_beg &&
1384                    child->bref.key <= info->key_beg) {
1385                 /*
1386                  * Illegal overlap.
1387                  */
1388                 KKASSERT(0);
1389                 /*info->best = child;*/
1390         } else if (child->bref.key < best->bref.key) {
1391                 /*
1392                  * Child has a nearer key and best is not flush with key_beg.
1393                  * Set best to child.  Truncate key_next to the old best key.
1394                  */
1395                 info->best = child;
1396                 if (info->key_next > best->bref.key || info->key_next == 0)
1397                         info->key_next = best->bref.key;
1398         } else if (child->bref.key == best->bref.key) {
1399                 /*
1400                  * If our current best is flush with the child then this
1401                  * is an illegal overlap.
1402                  *
1403                  * key_next will automatically be limited to the smaller of
1404                  * the two end-points.
1405                  */
1406                 KKASSERT(0);
1407                 info->best = child;
1408         } else {
1409                 /*
1410                  * Keep the current best but truncate key_next to the child's
1411                  * base.
1412                  *
1413                  * key_next will also automatically be limited to the smaller
1414                  * of the two end-points (probably not necessary for this case
1415                  * but we do it anyway).
1416                  */
1417                 if (info->key_next > child->bref.key || info->key_next == 0)
1418                         info->key_next = child->bref.key;
1419         }
1420
1421         /*
1422          * Always truncate key_next based on child's end-of-range.
1423          */
1424         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1425         if (child_end && (info->key_next > child_end || info->key_next == 0))
1426                 info->key_next = child_end;
1427
1428         return(0);
1429 }
1430
1431 /*
1432  * Retrieve the specified chain from a media blockref, creating the
1433  * in-memory chain structure which reflects it.
1434  *
1435  * To handle insertion races pass the INSERT_RACE flag along with the
1436  * generation number of the core.  NULL will be returned if the generation
1437  * number changes before we have a chance to insert the chain.  Insert
1438  * races can occur because the parent might be held shared.
1439  *
1440  * Caller must hold the parent locked shared or exclusive since we may
1441  * need the parent's bref array to find our block.
1442  *
1443  * WARNING! chain->pmp is left NULL if the bref represents a PFS mount
1444  *          point.
1445  */
1446 hammer2_chain_t *
1447 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1448                   hammer2_blockref_t *bref)
1449 {
1450         hammer2_mount_t *hmp = parent->hmp;
1451         hammer2_chain_t *chain;
1452         int error;
1453
1454         /*
1455          * Allocate a chain structure representing the existing media
1456          * entry.  Resulting chain has one ref and is not locked.
1457          */
1458         if (bref->flags & HAMMER2_BREF_FLAG_PFSROOT)
1459                 chain = hammer2_chain_alloc(hmp, NULL, NULL, bref);
1460         else
1461                 chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1462         hammer2_chain_core_alloc(NULL, chain);
1463         /* ref'd chain returned */
1464
1465         /*
1466          * Flag that the chain is in the parent's blockmap so delete/flush
1467          * knows what to do with it.
1468          */
1469         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1470
1471         /*
1472          * Link the chain into its parent.  A spinlock is required to safely
1473          * access the RBTREE, and it is possible to collide with another
1474          * hammer2_chain_get() operation because the caller might only hold
1475          * a shared lock on the parent.
1476          */
1477         KKASSERT(parent->refs > 0);
1478         error = hammer2_chain_insert(parent, chain,
1479                                      HAMMER2_CHAIN_INSERT_SPIN |
1480                                      HAMMER2_CHAIN_INSERT_RACE,
1481                                      generation);
1482         if (error) {
1483                 KKASSERT((chain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
1484                 kprintf("chain %p get race\n", chain);
1485                 hammer2_chain_drop(chain);
1486                 chain = NULL;
1487         } else {
1488                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1489         }
1490
1491         /*
1492          * Return our new chain referenced but not locked, or NULL if
1493          * a race occurred.
1494          */
1495         return (chain);
1496 }
1497
1498 /*
1499  * Lookup initialization/completion API
1500  */
1501 hammer2_chain_t *
1502 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1503 {
1504         if (flags & HAMMER2_LOOKUP_SHARED) {
1505                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1506                                            HAMMER2_RESOLVE_SHARED);
1507         } else {
1508                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1509         }
1510         return (parent);
1511 }
1512
1513 void
1514 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1515 {
1516         if (parent)
1517                 hammer2_chain_unlock(parent);
1518 }
1519
1520 static
1521 hammer2_chain_t *
1522 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1523 {
1524         hammer2_chain_t *oparent;
1525         hammer2_chain_t *nparent;
1526
1527         /*
1528          * Be careful of order, oparent must be unlocked before nparent
1529          * is locked below to avoid a deadlock.
1530          */
1531         oparent = *parentp;
1532         spin_lock(&oparent->core.cst.spin);
1533         nparent = oparent->parent;
1534         hammer2_chain_ref(nparent);
1535         spin_unlock(&oparent->core.cst.spin);
1536         if (oparent) {
1537                 hammer2_chain_unlock(oparent);
1538                 oparent = NULL;
1539         }
1540
1541         hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1542         *parentp = nparent;
1543
1544         return (nparent);
1545 }
1546
1547 /*
1548  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1549  * (*parentp) typically points to an inode but can also point to a related
1550  * indirect block and this function will recurse upwards and find the inode
1551  * again.
1552  *
1553  * (*parentp) must be exclusively locked and referenced and can be an inode
1554  * or an existing indirect block within the inode.
1555  *
1556  * On return (*parentp) will be modified to point at the deepest parent chain
1557  * element encountered during the search, as a helper for an insertion or
1558  * deletion.   The new (*parentp) will be locked and referenced and the old
1559  * will be unlocked and dereferenced (no change if they are both the same).
1560  *
1561  * The matching chain will be returned exclusively locked.  If NOLOCK is
1562  * requested the chain will be returned only referenced.
1563  *
1564  * NULL is returned if no match was found, but (*parentp) will still
1565  * potentially be adjusted.
1566  *
1567  * On return (*key_nextp) will point to an iterative value for key_beg.
1568  * (If NULL is returned (*key_nextp) is set to key_end).
1569  *
1570  * This function will also recurse up the chain if the key is not within the
1571  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1572  * can simply allow (*parentp) to float inside the loop.
1573  *
1574  * NOTE!  chain->data is not always resolved.  By default it will not be
1575  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1576  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1577  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1578  *        buffer).
1579  */
1580 hammer2_chain_t *
1581 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1582                      hammer2_key_t key_beg, hammer2_key_t key_end,
1583                      int *cache_indexp, int flags, int *ddflagp)
1584 {
1585         hammer2_mount_t *hmp;
1586         hammer2_chain_t *parent;
1587         hammer2_chain_t *chain;
1588         hammer2_blockref_t *base;
1589         hammer2_blockref_t *bref;
1590         hammer2_blockref_t bcopy;
1591         hammer2_key_t scan_beg;
1592         hammer2_key_t scan_end;
1593         int count = 0;
1594         int how_always = HAMMER2_RESOLVE_ALWAYS;
1595         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1596         int how;
1597         int generation;
1598         int maxloops = 300000;
1599
1600         *ddflagp = 0;
1601         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1602                 how_maybe = how_always;
1603                 how = HAMMER2_RESOLVE_ALWAYS;
1604         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1605                 how = HAMMER2_RESOLVE_NEVER;
1606         } else {
1607                 how = HAMMER2_RESOLVE_MAYBE;
1608         }
1609         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1610                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1611                 how_always |= HAMMER2_RESOLVE_SHARED;
1612                 how |= HAMMER2_RESOLVE_SHARED;
1613         }
1614
1615         /*
1616          * Recurse (*parentp) upward if necessary until the parent completely
1617          * encloses the key range or we hit the inode.
1618          *
1619          * This function handles races against the flusher doing a delete-
1620          * duplicate above us and re-homes the parent to the duplicate in
1621          * that case, otherwise we'd wind up recursing down a stale chain.
1622          */
1623         parent = *parentp;
1624         hmp = parent->hmp;
1625
1626         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1627                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1628                 scan_beg = parent->bref.key;
1629                 scan_end = scan_beg +
1630                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1631                 if (key_beg >= scan_beg && key_end <= scan_end)
1632                         break;
1633                 parent = hammer2_chain_getparent(parentp, how_maybe);
1634         }
1635
1636 again:
1637         if (--maxloops == 0)
1638                 panic("hammer2_chain_lookup: maxloops");
1639         /*
1640          * Locate the blockref array.  Currently we do a fully associative
1641          * search through the array.
1642          */
1643         switch(parent->bref.type) {
1644         case HAMMER2_BREF_TYPE_INODE:
1645                 /*
1646                  * Special shortcut for embedded data returns the inode
1647                  * itself.  Callers must detect this condition and access
1648                  * the embedded data (the strategy code does this for us).
1649                  *
1650                  * This is only applicable to regular files and softlinks.
1651                  */
1652                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1653                         if (flags & HAMMER2_LOOKUP_NOLOCK)
1654                                 hammer2_chain_ref(parent);
1655                         else
1656                                 hammer2_chain_lock(parent, how_always);
1657                         *key_nextp = key_end + 1;
1658                         *ddflagp = 1;
1659                         return (parent);
1660                 }
1661                 base = &parent->data->ipdata.u.blockset.blockref[0];
1662                 count = HAMMER2_SET_COUNT;
1663                 break;
1664         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1665         case HAMMER2_BREF_TYPE_INDIRECT:
1666                 /*
1667                  * Handle MATCHIND on the parent
1668                  */
1669                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1670                         scan_beg = parent->bref.key;
1671                         scan_end = scan_beg +
1672                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1673                         if (key_beg == scan_beg && key_end == scan_end) {
1674                                 chain = parent;
1675                                 hammer2_chain_lock(chain, how_maybe);
1676                                 *key_nextp = scan_end + 1;
1677                                 goto done;
1678                         }
1679                 }
1680                 /*
1681                  * Optimize indirect blocks in the INITIAL state to avoid
1682                  * I/O.
1683                  */
1684                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
1685                         base = NULL;
1686                 } else {
1687                         if (parent->data == NULL)
1688                                 panic("parent->data is NULL");
1689                         base = &parent->data->npdata[0];
1690                 }
1691                 count = parent->bytes / sizeof(hammer2_blockref_t);
1692                 break;
1693         case HAMMER2_BREF_TYPE_VOLUME:
1694                 base = &hmp->voldata.sroot_blockset.blockref[0];
1695                 count = HAMMER2_SET_COUNT;
1696                 break;
1697         case HAMMER2_BREF_TYPE_FREEMAP:
1698                 base = &hmp->voldata.freemap_blockset.blockref[0];
1699                 count = HAMMER2_SET_COUNT;
1700                 break;
1701         default:
1702                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
1703                       parent->bref.type);
1704                 base = NULL;    /* safety */
1705                 count = 0;      /* safety */
1706         }
1707
1708         /*
1709          * Merged scan to find next candidate.
1710          *
1711          * hammer2_base_*() functions require the parent->core.live_* fields
1712          * to be synchronized.
1713          *
1714          * We need to hold the spinlock to access the block array and RB tree
1715          * and to interlock chain creation.
1716          */
1717         if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
1718                 hammer2_chain_countbrefs(parent, base, count);
1719
1720         /*
1721          * Combined search
1722          */
1723         spin_lock(&parent->core.cst.spin);
1724         chain = hammer2_combined_find(parent, base, count,
1725                                       cache_indexp, key_nextp,
1726                                       key_beg, key_end,
1727                                       &bref);
1728         generation = parent->core.generation;
1729
1730         /*
1731          * Exhausted parent chain, iterate.
1732          */
1733         if (bref == NULL) {
1734                 spin_unlock(&parent->core.cst.spin);
1735                 if (key_beg == key_end) /* short cut single-key case */
1736                         return (NULL);
1737
1738                 /*
1739                  * Stop if we reached the end of the iteration.
1740                  */
1741                 if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1742                     parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1743                         return (NULL);
1744                 }
1745
1746                 /*
1747                  * Calculate next key, stop if we reached the end of the
1748                  * iteration, otherwise go up one level and loop.
1749                  */
1750                 key_beg = parent->bref.key +
1751                           ((hammer2_key_t)1 << parent->bref.keybits);
1752                 if (key_beg == 0 || key_beg > key_end)
1753                         return (NULL);
1754                 parent = hammer2_chain_getparent(parentp, how_maybe);
1755                 goto again;
1756         }
1757
1758         /*
1759          * Selected from blockref or in-memory chain.
1760          */
1761         if (chain == NULL) {
1762                 bcopy = *bref;
1763                 spin_unlock(&parent->core.cst.spin);
1764                 chain = hammer2_chain_get(parent, generation,
1765                                           &bcopy);
1766                 if (chain == NULL) {
1767                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
1768                                 parent, key_beg, key_end);
1769                         goto again;
1770                 }
1771                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
1772                         hammer2_chain_drop(chain);
1773                         goto again;
1774                 }
1775         } else {
1776                 hammer2_chain_ref(chain);
1777                 spin_unlock(&parent->core.cst.spin);
1778         }
1779
1780         /*
1781          * chain is referenced but not locked.  We must lock the chain
1782          * to obtain definitive DUPLICATED/DELETED state
1783          */
1784         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1785             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1786                 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
1787         } else {
1788                 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
1789         }
1790
1791         /*
1792          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
1793          *
1794          * NOTE: Chain's key range is not relevant as there might be
1795          *       one-offs within the range that are not deleted.
1796          *
1797          * NOTE: Lookups can race delete-duplicate because
1798          *       delete-duplicate does not lock the parent's core
1799          *       (they just use the spinlock on the core).  We must
1800          *       check for races by comparing the DUPLICATED flag before
1801          *       releasing the spinlock with the flag after locking the
1802          *       chain.
1803          */
1804         if (chain->flags & HAMMER2_CHAIN_DELETED) {
1805                 hammer2_chain_unlock(chain);
1806                 key_beg = *key_nextp;
1807                 if (key_beg == 0 || key_beg > key_end)
1808                         return(NULL);
1809                 goto again;
1810         }
1811
1812         /*
1813          * If the chain element is an indirect block it becomes the new
1814          * parent and we loop on it.  We must maintain our top-down locks
1815          * to prevent the flusher from interfering (i.e. doing a
1816          * delete-duplicate and leaving us recursing down a deleted chain).
1817          *
1818          * The parent always has to be locked with at least RESOLVE_MAYBE
1819          * so we can access its data.  It might need a fixup if the caller
1820          * passed incompatible flags.  Be careful not to cause a deadlock
1821          * as a data-load requires an exclusive lock.
1822          *
1823          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
1824          * range is within the requested key range we return the indirect
1825          * block and do NOT loop.  This is usually only used to acquire
1826          * freemap nodes.
1827          */
1828         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1829             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1830                 hammer2_chain_unlock(parent);
1831                 *parentp = parent = chain;
1832                 goto again;
1833         }
1834 done:
1835         /*
1836          * All done, return the chain
1837          */
1838         return (chain);
1839 }
1840
1841 /*
1842  * After having issued a lookup we can iterate all matching keys.
1843  *
1844  * If chain is non-NULL we continue the iteration from just after it's index.
1845  *
1846  * If chain is NULL we assume the parent was exhausted and continue the
1847  * iteration at the next parent.
1848  *
1849  * parent must be locked on entry and remains locked throughout.  chain's
1850  * lock status must match flags.  Chain is always at least referenced.
1851  *
1852  * WARNING!  The MATCHIND flag does not apply to this function.
1853  */
1854 hammer2_chain_t *
1855 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
1856                    hammer2_key_t *key_nextp,
1857                    hammer2_key_t key_beg, hammer2_key_t key_end,
1858                    int *cache_indexp, int flags)
1859 {
1860         hammer2_chain_t *parent;
1861         int how_maybe;
1862         int ddflag;
1863
1864         /*
1865          * Calculate locking flags for upward recursion.
1866          */
1867         how_maybe = HAMMER2_RESOLVE_MAYBE;
1868         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
1869                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1870
1871         parent = *parentp;
1872
1873         /*
1874          * Calculate the next index and recalculate the parent if necessary.
1875          */
1876         if (chain) {
1877                 key_beg = chain->bref.key +
1878                           ((hammer2_key_t)1 << chain->bref.keybits);
1879                 if (flags & HAMMER2_LOOKUP_NOLOCK)
1880                         hammer2_chain_drop(chain);
1881                 else
1882                         hammer2_chain_unlock(chain);
1883
1884                 /*
1885                  * Any scan where the lookup returned degenerate data embedded
1886                  * in the inode has an invalid index and must terminate.
1887                  */
1888                 if (chain == parent)
1889                         return(NULL);
1890                 if (key_beg == 0 || key_beg > key_end)
1891                         return(NULL);
1892                 chain = NULL;
1893         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
1894                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1895                 /*
1896                  * We reached the end of the iteration.
1897                  */
1898                 return (NULL);
1899         } else {
1900                 /*
1901                  * Continue iteration with next parent unless the current
1902                  * parent covers the range.
1903                  */
1904                 key_beg = parent->bref.key +
1905                           ((hammer2_key_t)1 << parent->bref.keybits);
1906                 if (key_beg == 0 || key_beg > key_end)
1907                         return (NULL);
1908                 parent = hammer2_chain_getparent(parentp, how_maybe);
1909         }
1910
1911         /*
1912          * And execute
1913          */
1914         return (hammer2_chain_lookup(parentp, key_nextp,
1915                                      key_beg, key_end,
1916                                      cache_indexp, flags, &ddflag));
1917 }
1918
1919 /*
1920  * The raw scan function is similar to lookup/next but does not seek to a key.
1921  * Blockrefs are iterated via first_chain = (parent, NULL) and
1922  * next_chain = (parent, chain).
1923  *
1924  * The passed-in parent must be locked and its data resolved.  The returned
1925  * chain will be locked.  Pass chain == NULL to acquire the first sub-chain
1926  * under parent and then iterate with the passed-in chain (which this
1927  * function will unlock).
1928  */
1929 hammer2_chain_t *
1930 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
1931                    int *cache_indexp, int flags)
1932 {
1933         hammer2_mount_t *hmp;
1934         hammer2_blockref_t *base;
1935         hammer2_blockref_t *bref;
1936         hammer2_blockref_t bcopy;
1937         hammer2_key_t key;
1938         hammer2_key_t next_key;
1939         int count = 0;
1940         int how_always = HAMMER2_RESOLVE_ALWAYS;
1941         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1942         int how;
1943         int generation;
1944         int maxloops = 300000;
1945
1946         hmp = parent->hmp;
1947
1948         /*
1949          * Scan flags borrowed from lookup
1950          */
1951         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1952                 how_maybe = how_always;
1953                 how = HAMMER2_RESOLVE_ALWAYS;
1954         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1955                 how = HAMMER2_RESOLVE_NEVER;
1956         } else {
1957                 how = HAMMER2_RESOLVE_MAYBE;
1958         }
1959         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1960                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1961                 how_always |= HAMMER2_RESOLVE_SHARED;
1962                 how |= HAMMER2_RESOLVE_SHARED;
1963         }
1964
1965         /*
1966          * Calculate key to locate first/next element, unlocking the previous
1967          * element as we go.  Be careful, the key calculation can overflow.
1968          */
1969         if (chain) {
1970                 key = chain->bref.key +
1971                       ((hammer2_key_t)1 << chain->bref.keybits);
1972                 hammer2_chain_unlock(chain);
1973                 chain = NULL;
1974                 if (key == 0)
1975                         goto done;
1976         } else {
1977                 key = 0;
1978         }
1979
1980 again:
1981         if (--maxloops == 0)
1982                 panic("hammer2_chain_scan: maxloops");
1983         /*
1984          * Locate the blockref array.  Currently we do a fully associative
1985          * search through the array.
1986          */
1987         switch(parent->bref.type) {
1988         case HAMMER2_BREF_TYPE_INODE:
1989                 /*
1990                  * An inode with embedded data has no sub-chains.
1991                  */
1992                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
1993                         goto done;
1994                 base = &parent->data->ipdata.u.blockset.blockref[0];
1995                 count = HAMMER2_SET_COUNT;
1996                 break;
1997         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1998         case HAMMER2_BREF_TYPE_INDIRECT:
1999                 /*
2000                  * Optimize indirect blocks in the INITIAL state to avoid
2001                  * I/O.
2002                  */
2003                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2004                         base = NULL;
2005                 } else {
2006                         if (parent->data == NULL)
2007                                 panic("parent->data is NULL");
2008                         base = &parent->data->npdata[0];
2009                 }
2010                 count = parent->bytes / sizeof(hammer2_blockref_t);
2011                 break;
2012         case HAMMER2_BREF_TYPE_VOLUME:
2013                 base = &hmp->voldata.sroot_blockset.blockref[0];
2014                 count = HAMMER2_SET_COUNT;
2015                 break;
2016         case HAMMER2_BREF_TYPE_FREEMAP:
2017                 base = &hmp->voldata.freemap_blockset.blockref[0];
2018                 count = HAMMER2_SET_COUNT;
2019                 break;
2020         default:
2021                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2022                       parent->bref.type);
2023                 base = NULL;    /* safety */
2024                 count = 0;      /* safety */
2025         }
2026
2027         /*
2028          * Merged scan to find next candidate.
2029          *
2030          * hammer2_base_*() functions require the parent->core.live_* fields
2031          * to be synchronized.
2032          *
2033          * We need to hold the spinlock to access the block array and RB tree
2034          * and to interlock chain creation.
2035          */
2036         if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2037                 hammer2_chain_countbrefs(parent, base, count);
2038
2039         next_key = 0;
2040         spin_lock(&parent->core.cst.spin);
2041         chain = hammer2_combined_find(parent, base, count,
2042                                       cache_indexp, &next_key,
2043                                       key, HAMMER2_KEY_MAX,
2044                                       &bref);
2045         generation = parent->core.generation;
2046
2047         /*
2048          * Exhausted parent chain, we're done.
2049          */
2050         if (bref == NULL) {
2051                 spin_unlock(&parent->core.cst.spin);
2052                 KKASSERT(chain == NULL);
2053                 goto done;
2054         }
2055
2056         /*
2057          * Selected from blockref or in-memory chain.
2058          */
2059         if (chain == NULL) {
2060                 bcopy = *bref;
2061                 spin_unlock(&parent->core.cst.spin);
2062                 chain = hammer2_chain_get(parent, generation, &bcopy);
2063                 if (chain == NULL) {
2064                         kprintf("retry scan parent %p keys %016jx\n",
2065                                 parent, key);
2066                         goto again;
2067                 }
2068                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2069                         hammer2_chain_drop(chain);
2070                         chain = NULL;
2071                         goto again;
2072                 }
2073         } else {
2074                 hammer2_chain_ref(chain);
2075                 spin_unlock(&parent->core.cst.spin);
2076         }
2077
2078         /*
2079          * chain is referenced but not locked.  We must lock the chain
2080          * to obtain definitive DUPLICATED/DELETED state
2081          */
2082         hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2083
2084         /*
2085          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2086          *
2087          * NOTE: chain's key range is not relevant as there might be
2088          *       one-offs within the range that are not deleted.
2089          *
2090          * NOTE: XXX this could create problems with scans used in
2091          *       situations other than mount-time recovery.
2092          *
2093          * NOTE: Lookups can race delete-duplicate because
2094          *       delete-duplicate does not lock the parent's core
2095          *       (they just use the spinlock on the core).  We must
2096          *       check for races by comparing the DUPLICATED flag before
2097          *       releasing the spinlock with the flag after locking the
2098          *       chain.
2099          */
2100         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2101                 hammer2_chain_unlock(chain);
2102                 chain = NULL;
2103
2104                 key = next_key;
2105                 if (key == 0)
2106                         goto done;
2107                 goto again;
2108         }
2109
2110 done:
2111         /*
2112          * All done, return the chain or NULL
2113          */
2114         return (chain);
2115 }
2116
2117 /*
2118  * Create and return a new hammer2 system memory structure of the specified
2119  * key, type and size and insert it under (*parentp).  This is a full
2120  * insertion, based on the supplied key/keybits, and may involve creating
2121  * indirect blocks and moving other chains around via delete/duplicate.
2122  *
2123  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2124  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2125  * FULL.  This typically means that the caller is creating the chain after
2126  * doing a hammer2_chain_lookup().
2127  *
2128  * (*parentp) must be exclusive locked and may be replaced on return
2129  * depending on how much work the function had to do.
2130  *
2131  * (*chainp) usually starts out NULL and returns the newly created chain,
2132  * but if the caller desires the caller may allocate a disconnected chain
2133  * and pass it in instead.
2134  *
2135  * This function should NOT be used to insert INDIRECT blocks.  It is
2136  * typically used to create/insert inodes and data blocks.
2137  *
2138  * Caller must pass-in an exclusively locked parent the new chain is to
2139  * be inserted under, and optionally pass-in a disconnected, exclusively
2140  * locked chain to insert (else we create a new chain).  The function will
2141  * adjust (*parentp) as necessary, create or connect the chain, and
2142  * return an exclusively locked chain in *chainp.
2143  */
2144 int
2145 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2146                      hammer2_chain_t **chainp, hammer2_pfsmount_t *pmp,
2147                      hammer2_key_t key, int keybits, int type, size_t bytes)
2148 {
2149         hammer2_mount_t *hmp;
2150         hammer2_chain_t *chain;
2151         hammer2_chain_t *parent;
2152         hammer2_blockref_t *base;
2153         hammer2_blockref_t dummy;
2154         int allocated = 0;
2155         int error = 0;
2156         int count;
2157         int maxloops = 300000;
2158
2159         /*
2160          * Topology may be crossing a PFS boundary.
2161          */
2162         parent = *parentp;
2163         KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2164         hmp = parent->hmp;
2165         chain = *chainp;
2166
2167         if (chain == NULL) {
2168                 /*
2169                  * First allocate media space and construct the dummy bref,
2170                  * then allocate the in-memory chain structure.  Set the
2171                  * INITIAL flag for fresh chains which do not have embedded
2172                  * data.
2173                  */
2174                 bzero(&dummy, sizeof(dummy));
2175                 dummy.type = type;
2176                 dummy.key = key;
2177                 dummy.keybits = keybits;
2178                 dummy.data_off = hammer2_getradix(bytes);
2179                 dummy.methods = parent->bref.methods;
2180                 chain = hammer2_chain_alloc(hmp, pmp, trans, &dummy);
2181                 hammer2_chain_core_alloc(trans, chain);
2182
2183                 /*
2184                  * Lock the chain manually, chain_lock will load the chain
2185                  * which we do NOT want to do.  (note: chain->refs is set
2186                  * to 1 by chain_alloc() for us, but lockcnt is not).
2187                  */
2188                 chain->lockcnt = 1;
2189                 ccms_thread_lock(&chain->core.cst, CCMS_STATE_EXCLUSIVE);
2190                 allocated = 1;
2191
2192                 /*
2193                  * We do NOT set INITIAL here (yet).  INITIAL is only
2194                  * used for indirect blocks.
2195                  *
2196                  * Recalculate bytes to reflect the actual media block
2197                  * allocation.
2198                  */
2199                 bytes = (hammer2_off_t)1 <<
2200                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2201                 chain->bytes = bytes;
2202
2203                 switch(type) {
2204                 case HAMMER2_BREF_TYPE_VOLUME:
2205                 case HAMMER2_BREF_TYPE_FREEMAP:
2206                         panic("hammer2_chain_create: called with volume type");
2207                         break;
2208                 case HAMMER2_BREF_TYPE_INDIRECT:
2209                         panic("hammer2_chain_create: cannot be used to"
2210                               "create indirect block");
2211                         break;
2212                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2213                         panic("hammer2_chain_create: cannot be used to"
2214                               "create freemap root or node");
2215                         break;
2216                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2217                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2218                         /* fall through */
2219                 case HAMMER2_BREF_TYPE_INODE:
2220                 case HAMMER2_BREF_TYPE_DATA:
2221                 default:
2222                         /*
2223                          * leave chain->data NULL, set INITIAL
2224                          */
2225                         KKASSERT(chain->data == NULL);
2226                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2227                         break;
2228                 }
2229         } else {
2230                 /*
2231                  * We are reattaching a previously deleted chain, possibly
2232                  * under a new parent and possibly with a new key/keybits.
2233                  * The chain does not have to be in a modified state.  The
2234                  * UPDATE flag will be set later on in this routine.
2235                  *
2236                  * Do NOT mess with the current state of the INITIAL flag.
2237                  */
2238                 chain->bref.key = key;
2239                 chain->bref.keybits = keybits;
2240                 if (chain->flags & HAMMER2_CHAIN_DELETED)
2241                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2242                 KKASSERT(chain->parent == NULL);
2243         }
2244
2245         /*
2246          * Calculate how many entries we have in the blockref array and
2247          * determine if an indirect block is required.
2248          */
2249 again:
2250         if (--maxloops == 0)
2251                 panic("hammer2_chain_create: maxloops");
2252
2253         switch(parent->bref.type) {
2254         case HAMMER2_BREF_TYPE_INODE:
2255                 KKASSERT((parent->data->ipdata.op_flags &
2256                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2257                 KKASSERT(parent->data != NULL);
2258                 base = &parent->data->ipdata.u.blockset.blockref[0];
2259                 count = HAMMER2_SET_COUNT;
2260                 break;
2261         case HAMMER2_BREF_TYPE_INDIRECT:
2262         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2263                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2264                         base = NULL;
2265                 else
2266                         base = &parent->data->npdata[0];
2267                 count = parent->bytes / sizeof(hammer2_blockref_t);
2268                 break;
2269         case HAMMER2_BREF_TYPE_VOLUME:
2270                 KKASSERT(parent->data != NULL);
2271                 base = &hmp->voldata.sroot_blockset.blockref[0];
2272                 count = HAMMER2_SET_COUNT;
2273                 break;
2274         case HAMMER2_BREF_TYPE_FREEMAP:
2275                 KKASSERT(parent->data != NULL);
2276                 base = &hmp->voldata.freemap_blockset.blockref[0];
2277                 count = HAMMER2_SET_COUNT;
2278                 break;
2279         default:
2280                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2281                       parent->bref.type);
2282                 base = NULL;
2283                 count = 0;
2284                 break;
2285         }
2286
2287         /*
2288          * Make sure we've counted the brefs
2289          */
2290         if ((parent->core.flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2291                 hammer2_chain_countbrefs(parent, base, count);
2292
2293         KKASSERT(parent->core.live_count >= 0 &&
2294                  parent->core.live_count <= count);
2295
2296         /*
2297          * If no free blockref could be found we must create an indirect
2298          * block and move a number of blockrefs into it.  With the parent
2299          * locked we can safely lock each child in order to delete+duplicate
2300          * it without causing a deadlock.
2301          *
2302          * This may return the new indirect block or the old parent depending
2303          * on where the key falls.  NULL is returned on error.
2304          */
2305         if (parent->core.live_count == count) {
2306                 hammer2_chain_t *nparent;
2307
2308                 nparent = hammer2_chain_create_indirect(trans, parent,
2309                                                         key, keybits,
2310                                                         type, &error);
2311                 if (nparent == NULL) {
2312                         if (allocated)
2313                                 hammer2_chain_drop(chain);
2314                         chain = NULL;
2315                         goto done;
2316                 }
2317                 if (parent != nparent) {
2318                         hammer2_chain_unlock(parent);
2319                         parent = *parentp = nparent;
2320                 }
2321                 goto again;
2322         }
2323
2324         /*
2325          * Link the chain into its parent.
2326          */
2327         if (chain->parent != NULL)
2328                 panic("hammer2: hammer2_chain_create: chain already connected");
2329         KKASSERT(chain->parent == NULL);
2330         hammer2_chain_insert(parent, chain,
2331                              HAMMER2_CHAIN_INSERT_SPIN |
2332                              HAMMER2_CHAIN_INSERT_LIVE,
2333                              0);
2334
2335         if (allocated) {
2336                 /*
2337                  * Mark the newly created chain modified.  This will cause
2338                  * UPDATE to be set.
2339                  *
2340                  * Device buffers are not instantiated for DATA elements
2341                  * as these are handled by logical buffers.
2342                  *
2343                  * Indirect and freemap node indirect blocks are handled
2344                  * by hammer2_chain_create_indirect() and not by this
2345                  * function.
2346                  *
2347                  * Data for all other bref types is expected to be
2348                  * instantiated (INODE, LEAF).
2349                  */
2350                 switch(chain->bref.type) {
2351                 case HAMMER2_BREF_TYPE_DATA:
2352                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2353                 case HAMMER2_BREF_TYPE_INODE:
2354                         hammer2_chain_modify(trans, chain,
2355                                              HAMMER2_MODIFY_OPTDATA |
2356                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2357                         break;
2358                 default:
2359                         /*
2360                          * Remaining types are not supported by this function.
2361                          * In particular, INDIRECT and LEAF_NODE types are
2362                          * handled by create_indirect().
2363                          */
2364                         panic("hammer2_chain_create: bad type: %d",
2365                               chain->bref.type);
2366                         /* NOT REACHED */
2367                         break;
2368                 }
2369         } else {
2370                 /*
2371                  * When reconnecting a chain we must set UPDATE and
2372                  * setflush so the flush recognizes that it must update
2373                  * the bref in the parent.
2374                  */
2375                 if ((chain->flags & HAMMER2_CHAIN_UPDATE) == 0) {
2376                         hammer2_chain_ref(chain);
2377                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_UPDATE);
2378                 }
2379         }
2380
2381         /*
2382          * We must setflush(parent) to ensure that it recurses through to
2383          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2384          * already set in the chain (so it won't recurse up to set it in the
2385          * parent).
2386          */
2387         hammer2_chain_setflush(trans, parent);
2388
2389 done:
2390         *chainp = chain;
2391
2392         return (error);
2393 }
2394
2395 /*
2396  * Move the chain from its old parent to a new parent.  The chain must have
2397  * already been deleted or already disconnected (or never associated) with
2398  * a parent.  The chain is reassociated with the new parent and the deleted
2399  * flag will be cleared (no longer deleted).  The chain's modification state
2400  * is not altered.
2401  *
2402  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (parent) TO THE INSERTION
2403  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2404  * FULL.  This typically means that the caller is creating the chain after
2405  * doing a hammer2_chain_lookup().
2406  *
2407  * A non-NULL bref is typically passed when key and keybits must be overridden.
2408  * Note that hammer2_cluster_duplicate() *ONLY* uses the key and keybits fields
2409  * from a passed-in bref and uses the old chain's bref for everything else.
2410  *
2411  * If (parent) is non-NULL then the new duplicated chain is inserted under
2412  * the parent.
2413  *
2414  * If (parent) is NULL then the newly duplicated chain is not inserted
2415  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2416  * passing into hammer2_chain_create() after this function returns).
2417  *
2418  * WARNING! This function calls create which means it can insert indirect
2419  *          blocks.  This can cause other unrelated chains in the parent to
2420  *          be moved to a newly inserted indirect block in addition to the
2421  *          specific chain.
2422  */
2423 void
2424 hammer2_chain_rename(hammer2_trans_t *trans, hammer2_blockref_t *bref,
2425                      hammer2_chain_t **parentp, hammer2_chain_t *chain)
2426 {
2427         hammer2_mount_t *hmp;
2428         hammer2_chain_t *parent;
2429         size_t bytes;
2430
2431         /*
2432          * WARNING!  We should never resolve DATA to device buffers
2433          *           (XXX allow it if the caller did?), and since
2434          *           we currently do not have the logical buffer cache
2435          *           buffer in-hand to fix its cached physical offset
2436          *           we also force the modify code to not COW it. XXX
2437          */
2438         hmp = chain->hmp;
2439         KKASSERT(chain->parent == NULL);
2440
2441         /*
2442          * Now create a duplicate of the chain structure, associating
2443          * it with the same core, making it the same size, pointing it
2444          * to the same bref (the same media block).
2445          */
2446         if (bref == NULL)
2447                 bref = &chain->bref;
2448         bytes = (hammer2_off_t)1 <<
2449                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2450
2451         /*
2452          * If parent is not NULL the duplicated chain will be entered under
2453          * the parent and the UPDATE bit set to tell flush to update
2454          * the blockref.
2455          *
2456          * We must setflush(parent) to ensure that it recurses through to
2457          * chain.  setflush(chain) might not work because ONFLUSH is possibly
2458          * already set in the chain (so it won't recurse up to set it in the
2459          * parent).
2460          *
2461          * Having both chains locked is extremely important for atomicy.
2462          */
2463         if (parentp && (parent = *parentp) != NULL) {
2464                 KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2465                 KKASSERT(parent->refs > 0);
2466
2467                 hammer2_chain_create(trans, parentp, &chain, chain->pmp,
2468                                      bref->key, bref->keybits, bref->type,
2469                                      chain->bytes);
2470                 KKASSERT(chain->flags & HAMMER2_CHAIN_UPDATE);
2471                 hammer2_chain_setflush(trans, *parentp);
2472         }
2473 }
2474
2475 /*
2476  * Helper function for deleting chains.
2477  *
2478  * The chain is removed from the live view (the RBTREE) as well as the parent's
2479  * blockmap.  Both chain and its parent must be locked.
2480  */
2481 static void
2482 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2483                              hammer2_chain_t *parent, hammer2_chain_t *chain)
2484 {
2485         hammer2_mount_t *hmp;
2486
2487         KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0);
2488         hmp = chain->hmp;
2489
2490         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2491                 /*
2492                  * Chain is blockmapped, so there must be a parent.
2493                  * Atomically remove the chain from the parent and remove
2494                  * the blockmap entry.
2495                  */
2496                 hammer2_blockref_t *base;
2497                 int count;
2498
2499                 KKASSERT(parent != NULL);
2500                 KKASSERT((parent->flags & HAMMER2_CHAIN_INITIAL) == 0);
2501                 hammer2_chain_modify(trans, parent,
2502                                      HAMMER2_MODIFY_OPTDATA);
2503
2504                 /*
2505                  * Calculate blockmap pointer
2506                  */
2507                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2508                 spin_lock(&parent->core.cst.spin);
2509
2510                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2511                 atomic_add_int(&parent->core.live_count, -1);
2512                 ++parent->core.generation;
2513                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2514                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2515                 --parent->core.chain_count;
2516                 chain->parent = NULL;
2517
2518                 switch(parent->bref.type) {
2519                 case HAMMER2_BREF_TYPE_INODE:
2520                         /*
2521                          * Access the inode's block array.  However, there
2522                          * is no block array if the inode is flagged
2523                          * DIRECTDATA.  The DIRECTDATA case typicaly only
2524                          * occurs when a hardlink has been shifted up the
2525                          * tree and the original inode gets replaced with
2526                          * an OBJTYPE_HARDLINK placeholding inode.
2527                          */
2528                         if (parent->data &&
2529                             (parent->data->ipdata.op_flags &
2530                              HAMMER2_OPFLAG_DIRECTDATA) == 0) {
2531                                 base =
2532                                    &parent->data->ipdata.u.blockset.blockref[0];
2533                         } else {
2534                                 base = NULL;
2535                         }
2536                         count = HAMMER2_SET_COUNT;
2537                         break;
2538                 case HAMMER2_BREF_TYPE_INDIRECT:
2539                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2540                         if (parent->data)
2541                                 base = &parent->data->npdata[0];
2542                         else
2543                                 base = NULL;
2544                         count = parent->bytes / sizeof(hammer2_blockref_t);
2545                         break;
2546                 case HAMMER2_BREF_TYPE_VOLUME:
2547                         base = &hmp->voldata.sroot_blockset.blockref[0];
2548                         count = HAMMER2_SET_COUNT;
2549                         break;
2550                 case HAMMER2_BREF_TYPE_FREEMAP:
2551                         base = &parent->data->npdata[0];
2552                         count = HAMMER2_SET_COUNT;
2553                         break;
2554                 default:
2555                         base = NULL;
2556                         count = 0;
2557                         panic("hammer2_flush_pass2: "
2558                               "unrecognized blockref type: %d",
2559                               parent->bref.type);
2560                 }
2561                 if (base) {
2562                         int cache_index = -1;
2563                         hammer2_base_delete(trans, parent, base, count,
2564                                             &cache_index, chain);
2565                 }
2566                 spin_unlock(&parent->core.cst.spin);
2567         } else if (chain->flags & HAMMER2_CHAIN_ONRBTREE) {
2568                 /*
2569                  * Chain is not blockmapped but a parent is present.
2570                  * Atomically remove the chain from the parent.  There is
2571                  * no blockmap entry to remove.
2572                  */
2573                 spin_lock(&parent->core.cst.spin);
2574                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2575                 atomic_add_int(&parent->core.live_count, -1);
2576                 ++parent->core.generation;
2577                 RB_REMOVE(hammer2_chain_tree, &parent->core.rbtree, chain);
2578                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2579                 --parent->core.chain_count;
2580                 chain->parent = NULL;
2581                 spin_unlock(&parent->core.cst.spin);
2582         } else {
2583                 /*
2584                  * Chain is not blockmapped and has no parent.  This
2585                  * is a degenerate case.
2586                  */
2587                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2588         }
2589 }
2590
2591 /*
2592  * Create an indirect block that covers one or more of the elements in the
2593  * current parent.  Either returns the existing parent with no locking or
2594  * ref changes or returns the new indirect block locked and referenced
2595  * and leaving the original parent lock/ref intact as well.
2596  *
2597  * If an error occurs, NULL is returned and *errorp is set to the error.
2598  *
2599  * The returned chain depends on where the specified key falls.
2600  *
2601  * The key/keybits for the indirect mode only needs to follow three rules:
2602  *
2603  * (1) That all elements underneath it fit within its key space and
2604  *
2605  * (2) That all elements outside it are outside its key space.
2606  *
2607  * (3) When creating the new indirect block any elements in the current
2608  *     parent that fit within the new indirect block's keyspace must be
2609  *     moved into the new indirect block.
2610  *
2611  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
2612  *     keyspace the the current parent, but lookup/iteration rules will
2613  *     ensure (and must ensure) that rule (2) for all parents leading up
2614  *     to the nearest inode or the root volume header is adhered to.  This
2615  *     is accomplished by always recursing through matching keyspaces in
2616  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
2617  *
2618  * The current implementation calculates the current worst-case keyspace by
2619  * iterating the current parent and then divides it into two halves, choosing
2620  * whichever half has the most elements (not necessarily the half containing
2621  * the requested key).
2622  *
2623  * We can also opt to use the half with the least number of elements.  This
2624  * causes lower-numbered keys (aka logical file offsets) to recurse through
2625  * fewer indirect blocks and higher-numbered keys to recurse through more.
2626  * This also has the risk of not moving enough elements to the new indirect
2627  * block and being forced to create several indirect blocks before the element
2628  * can be inserted.
2629  *
2630  * Must be called with an exclusively locked parent.
2631  */
2632 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
2633                                 hammer2_key_t *keyp, int keybits,
2634                                 hammer2_blockref_t *base, int count);
2635 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
2636                                 hammer2_key_t *keyp, int keybits,
2637                                 hammer2_blockref_t *base, int count);
2638 static
2639 hammer2_chain_t *
2640 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
2641                               hammer2_key_t create_key, int create_bits,
2642                               int for_type, int *errorp)
2643 {
2644         hammer2_mount_t *hmp;
2645         hammer2_blockref_t *base;
2646         hammer2_blockref_t *bref;
2647         hammer2_blockref_t bcopy;
2648         hammer2_chain_t *chain;
2649         hammer2_chain_t *ichain;
2650         hammer2_chain_t dummy;
2651         hammer2_key_t key = create_key;
2652         hammer2_key_t key_beg;
2653         hammer2_key_t key_end;
2654         hammer2_key_t key_next;
2655         int keybits = create_bits;
2656         int count;
2657         int nbytes;
2658         int cache_index;
2659         int loops;
2660         int reason;
2661         int generation;
2662         int maxloops = 300000;
2663
2664         /*
2665          * Calculate the base blockref pointer or NULL if the chain
2666          * is known to be empty.  We need to calculate the array count
2667          * for RB lookups either way.
2668          */
2669         hmp = parent->hmp;
2670         *errorp = 0;
2671         KKASSERT(ccms_thread_lock_owned(&parent->core.cst));
2672
2673         /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
2674         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2675                 base = NULL;
2676
2677                 switch(parent->bref.type) {
2678                 case HAMMER2_BREF_TYPE_INODE:
2679                         count = HAMMER2_SET_COUNT;
2680                         break;
2681                 case HAMMER2_BREF_TYPE_INDIRECT:
2682                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2683                         count = parent->bytes / sizeof(hammer2_blockref_t);
2684                         break;
2685                 case HAMMER2_BREF_TYPE_VOLUME:
2686                         count = HAMMER2_SET_COUNT;
2687                         break;
2688                 case HAMMER2_BREF_TYPE_FREEMAP:
2689                         count = HAMMER2_SET_COUNT;
2690                         break;
2691                 default:
2692                         panic("hammer2_chain_create_indirect: "
2693                               "unrecognized blockref type: %d",
2694                               parent->bref.type);
2695                         count = 0;
2696                         break;
2697                 }
2698         } else {
2699                 switch(parent->bref.type) {
2700                 case HAMMER2_BREF_TYPE_INODE:
2701                         base = &parent->data->ipdata.u.blockset.blockref[0];
2702                         count = HAMMER2_SET_COUNT;
2703                         break;
2704                 case HAMMER2_BREF_TYPE_INDIRECT:
2705                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2706                         base = &parent->data->npdata[0];
2707                         count = parent->bytes / sizeof(hammer2_blockref_t);
2708                         break;
2709                 case HAMMER2_BREF_TYPE_VOLUME:
2710                         base = &hmp->voldata.sroot_blockset.blockref[0];
2711                         count = HAMMER2_SET_COUNT;
2712                         break;
2713                 case HAMMER2_BREF_TYPE_FREEMAP:
2714                         base = &hmp->voldata.freemap_blockset.blockref[0];
2715                         count = HAMMER2_SET_COUNT;
2716                         break;
2717                 default:
2718                         panic("hammer2_chain_create_indirect: "
2719                               "unrecognized blockref type: %d",
2720                               parent->bref.type);
2721                         count = 0;
2722                         break;
2723                 }
2724         }
2725
2726         /*
2727          * dummy used in later chain allocation (no longer used for lookups).
2728          */
2729         bzero(&dummy, sizeof(dummy));
2730
2731         /*
2732          * When creating an indirect block for a freemap node or leaf
2733          * the key/keybits must be fitted to static radix levels because
2734          * particular radix levels use particular reserved blocks in the
2735          * related zone.
2736          *
2737          * This routine calculates the key/radix of the indirect block
2738          * we need to create, and whether it is on the high-side or the
2739          * low-side.
2740          */
2741         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2742             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2743                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
2744                                                        base, count);
2745         } else {
2746                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
2747                                                       base, count);
2748         }
2749
2750         /*
2751          * Normalize the key for the radix being represented, keeping the
2752          * high bits and throwing away the low bits.
2753          */
2754         key &= ~(((hammer2_key_t)1 << keybits) - 1);
2755
2756         /*
2757          * How big should our new indirect block be?  It has to be at least
2758          * as large as its parent.
2759          */
2760         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
2761                 nbytes = HAMMER2_IND_BYTES_MIN;
2762         else
2763                 nbytes = HAMMER2_IND_BYTES_MAX;
2764         if (nbytes < count * sizeof(hammer2_blockref_t))
2765                 nbytes = count * sizeof(hammer2_blockref_t);
2766
2767         /*
2768          * Ok, create our new indirect block
2769          */
2770         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
2771             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
2772                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
2773         } else {
2774                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
2775         }
2776         dummy.bref.key = key;
2777         dummy.bref.keybits = keybits;
2778         dummy.bref.data_off = hammer2_getradix(nbytes);
2779         dummy.bref.methods = parent->bref.methods;
2780
2781         ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
2782         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
2783         hammer2_chain_core_alloc(trans, ichain);
2784         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
2785         hammer2_chain_drop(ichain);     /* excess ref from alloc */
2786
2787         /*
2788          * We have to mark it modified to allocate its block, but use
2789          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
2790          * it won't be acted upon by the flush code.
2791          */
2792         hammer2_chain_modify(trans, ichain, HAMMER2_MODIFY_OPTDATA);
2793
2794         /*
2795          * Iterate the original parent and move the matching brefs into
2796          * the new indirect block.
2797          *
2798          * XXX handle flushes.
2799          */
2800         key_beg = 0;
2801         key_end = HAMMER2_KEY_MAX;
2802         cache_index = 0;
2803         spin_lock(&parent->core.cst.spin);
2804         loops = 0;
2805         reason = 0;
2806
2807         for (;;) {
2808                 if (++loops > 100000) {
2809                     spin_unlock(&parent->core.cst.spin);
2810                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
2811                           reason, parent, base, count, key_next);
2812                 }
2813
2814                 /*
2815                  * NOTE: spinlock stays intact, returned chain (if not NULL)
2816                  *       is not referenced or locked which means that we
2817                  *       cannot safely check its flagged / deletion status
2818                  *       until we lock it.
2819                  */
2820                 chain = hammer2_combined_find(parent, base, count,
2821                                               &cache_index, &key_next,
2822                                               key_beg, key_end,
2823                                               &bref);
2824                 generation = parent->core.generation;
2825                 if (bref == NULL)
2826                         break;
2827                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
2828
2829                 /*
2830                  * Skip keys that are not within the key/radix of the new
2831                  * indirect block.  They stay in the parent.
2832                  */
2833                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
2834                     (key ^ bref->key)) != 0) {
2835                         goto next_key_spinlocked;
2836                 }
2837
2838                 /*
2839                  * Load the new indirect block by acquiring the related
2840                  * chains (potentially from media as it might not be
2841                  * in-memory).  Then move it to the new parent (ichain)
2842                  * via DELETE-DUPLICATE.
2843                  *
2844                  * chain is referenced but not locked.  We must lock the
2845                  * chain to obtain definitive DUPLICATED/DELETED state
2846                  */
2847                 if (chain) {
2848                         /*
2849                          * Use chain already present in the RBTREE
2850                          */
2851                         hammer2_chain_ref(chain);
2852                         spin_unlock(&parent->core.cst.spin);
2853                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2854                                                   HAMMER2_RESOLVE_NOREF);
2855                 } else {
2856                         /*
2857                          * Get chain for blockref element.  _get returns NULL
2858                          * on insertion race.
2859                          */
2860                         bcopy = *bref;
2861                         spin_unlock(&parent->core.cst.spin);
2862                         chain = hammer2_chain_get(parent, generation, &bcopy);
2863                         if (chain == NULL) {
2864                                 reason = 1;
2865                                 spin_lock(&parent->core.cst.spin);
2866                                 continue;
2867                         }
2868                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2869                                 kprintf("REASON 2\n");
2870                                 reason = 2;
2871                                 hammer2_chain_drop(chain);
2872                                 spin_lock(&parent->core.cst.spin);
2873                                 continue;
2874                         }
2875                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
2876                                                   HAMMER2_RESOLVE_NOREF);
2877                 }
2878
2879                 /*
2880                  * This is always live so if the chain has been deleted
2881                  * we raced someone and we have to retry.
2882                  *
2883                  * NOTE: Lookups can race delete-duplicate because
2884                  *       delete-duplicate does not lock the parent's core
2885                  *       (they just use the spinlock on the core).  We must
2886                  *       check for races by comparing the DUPLICATED flag before
2887                  *       releasing the spinlock with the flag after locking the
2888                  *       chain.
2889                  *
2890                  *       (note reversed logic for this one)
2891                  */
2892                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
2893                         hammer2_chain_unlock(chain);
2894                         goto next_key;
2895                 }
2896
2897                 /*
2898                  * Shift the chain to the indirect block.
2899                  *
2900                  * WARNING! Can cause held-over chains to require a refactor.
2901                  *          Fortunately we have none (our locked chains are
2902                  *          passed into and modified by the call).
2903                  */
2904                 hammer2_chain_delete(trans, parent, chain, 0);
2905                 hammer2_chain_rename(trans, NULL, &ichain, chain);
2906                 hammer2_chain_unlock(chain);
2907                 KKASSERT(parent->refs > 0);
2908                 chain = NULL;
2909 next_key:
2910                 spin_lock(&parent->core.cst.spin);
2911 next_key_spinlocked:
2912                 if (--maxloops == 0)
2913                         panic("hammer2_chain_create_indirect: maxloops");
2914                 reason = 4;
2915                 if (key_next == 0 || key_next > key_end)
2916                         break;
2917                 key_beg = key_next;
2918                 /* loop */
2919         }
2920         spin_unlock(&parent->core.cst.spin);
2921
2922         /*
2923          * Insert the new indirect block into the parent now that we've
2924          * cleared out some entries in the parent.  We calculated a good
2925          * insertion index in the loop above (ichain->index).
2926          *
2927          * We don't have to set UPDATE here because we mark ichain
2928          * modified down below (so the normal modified -> flush -> set-moved
2929          * sequence applies).
2930          *
2931          * The insertion shouldn't race as this is a completely new block
2932          * and the parent is locked.
2933          */
2934         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
2935         hammer2_chain_insert(parent, ichain,
2936                              HAMMER2_CHAIN_INSERT_SPIN |
2937                              HAMMER2_CHAIN_INSERT_LIVE,
2938                              0);
2939
2940         /*
2941          * Make sure flushes propogate after our manual insertion.
2942          */
2943         hammer2_chain_setflush(trans, ichain);
2944         hammer2_chain_setflush(trans, parent);
2945
2946         /*
2947          * Figure out what to return.
2948          */
2949         if (~(((hammer2_key_t)1 << keybits) - 1) &
2950                    (create_key ^ key)) {
2951                 /*
2952                  * Key being created is outside the key range,
2953                  * return the original parent.
2954                  */
2955                 hammer2_chain_unlock(ichain);
2956         } else {
2957                 /*
2958                  * Otherwise its in the range, return the new parent.
2959                  * (leave both the new and old parent locked).
2960                  */
2961                 parent = ichain;
2962         }
2963
2964         return(parent);
2965 }
2966
2967 /*
2968  * Calculate the keybits and highside/lowside of the freemap node the
2969  * caller is creating.
2970  *
2971  * This routine will specify the next higher-level freemap key/radix
2972  * representing the lowest-ordered set.  By doing so, eventually all
2973  * low-ordered sets will be moved one level down.
2974  *
2975  * We have to be careful here because the freemap reserves a limited
2976  * number of blocks for a limited number of levels.  So we can't just
2977  * push indiscriminately.
2978  */
2979 int
2980 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
2981                              int keybits, hammer2_blockref_t *base, int count)
2982 {
2983         hammer2_chain_t *chain;
2984         hammer2_blockref_t *bref;
2985         hammer2_key_t key;
2986         hammer2_key_t key_beg;
2987         hammer2_key_t key_end;
2988         hammer2_key_t key_next;
2989         int cache_index;
2990         int locount;
2991         int hicount;
2992         int maxloops = 300000;
2993
2994         key = *keyp;
2995         locount = 0;
2996         hicount = 0;
2997         keybits = 64;
2998
2999         /*
3000          * Calculate the range of keys in the array being careful to skip
3001          * slots which are overridden with a deletion.
3002          */
3003         key_beg = 0;
3004         key_end = HAMMER2_KEY_MAX;
3005         cache_index = 0;
3006         spin_lock(&parent->core.cst.spin);
3007
3008         for (;;) {
3009                 if (--maxloops == 0) {
3010                         panic("indkey_freemap shit %p %p:%d\n",
3011                               parent, base, count);
3012                 }
3013                 chain = hammer2_combined_find(parent, base, count,
3014                                               &cache_index, &key_next,
3015                                               key_beg, key_end,
3016                                               &bref);
3017
3018                 /*
3019                  * Exhausted search
3020                  */
3021                 if (bref == NULL)
3022                         break;
3023
3024                 /*
3025                  * Skip deleted chains.
3026                  */
3027                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3028                         if (key_next == 0 || key_next > key_end)
3029                                 break;
3030                         key_beg = key_next;
3031                         continue;
3032                 }
3033
3034                 /*
3035                  * Use the full live (not deleted) element for the scan
3036                  * iteration.  HAMMER2 does not allow partial replacements.
3037                  *
3038                  * XXX should be built into hammer2_combined_find().
3039                  */
3040                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3041
3042                 if (keybits > bref->keybits) {
3043                         key = bref->key;
3044                         keybits = bref->keybits;
3045                 } else if (keybits == bref->keybits && bref->key < key) {
3046                         key = bref->key;
3047                 }
3048                 if (key_next == 0)
3049                         break;
3050                 key_beg = key_next;
3051         }
3052         spin_unlock(&parent->core.cst.spin);
3053
3054         /*
3055          * Return the keybits for a higher-level FREEMAP_NODE covering
3056          * this node.
3057          */
3058         switch(keybits) {
3059         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3060                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3061                 break;
3062         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3063                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3064                 break;
3065         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3066                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3067                 break;
3068         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3069                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3070                 break;
3071         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3072                 panic("hammer2_chain_indkey_freemap: level too high");
3073                 break;
3074         default:
3075                 panic("hammer2_chain_indkey_freemap: bad radix");
3076                 break;
3077         }
3078         *keyp = key;
3079
3080         return (keybits);
3081 }
3082
3083 /*
3084  * Calculate the keybits and highside/lowside of the indirect block the
3085  * caller is creating.
3086  */
3087 static int
3088 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3089                             int keybits, hammer2_blockref_t *base, int count)
3090 {
3091         hammer2_blockref_t *bref;
3092         hammer2_chain_t *chain;
3093         hammer2_key_t key_beg;
3094         hammer2_key_t key_end;
3095         hammer2_key_t key_next;
3096         hammer2_key_t key;
3097         int nkeybits;
3098         int locount;
3099         int hicount;
3100         int cache_index;
3101         int maxloops = 300000;
3102
3103         key = *keyp;
3104         locount = 0;
3105         hicount = 0;
3106
3107         /*
3108          * Calculate the range of keys in the array being careful to skip
3109          * slots which are overridden with a deletion.  Once the scan
3110          * completes we will cut the key range in half and shift half the
3111          * range into the new indirect block.
3112          */
3113         key_beg = 0;
3114         key_end = HAMMER2_KEY_MAX;
3115         cache_index = 0;
3116         spin_lock(&parent->core.cst.spin);
3117
3118         for (;;) {
3119                 if (--maxloops == 0) {
3120                         panic("indkey_freemap shit %p %p:%d\n",
3121                               parent, base, count);
3122                 }
3123                 chain = hammer2_combined_find(parent, base, count,
3124                                               &cache_index, &key_next,
3125                                               key_beg, key_end,
3126                                               &bref);
3127
3128                 /*
3129                  * Exhausted search
3130                  */
3131                 if (bref == NULL)
3132                         break;
3133
3134                 /*
3135                  * NOTE: No need to check DUPLICATED here because we do
3136                  *       not release the spinlock.
3137                  */
3138                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3139                         if (key_next == 0 || key_next > key_end)
3140                                 break;
3141                         key_beg = key_next;
3142                         continue;
3143                 }
3144
3145                 /*
3146                  * Use the full live (not deleted) element for the scan
3147                  * iteration.  HAMMER2 does not allow partial replacements.
3148                  *
3149                  * XXX should be built into hammer2_combined_find().
3150                  */
3151                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3152
3153                 /*
3154                  * Expand our calculated key range (key, keybits) to fit
3155                  * the scanned key.  nkeybits represents the full range
3156                  * that we will later cut in half (two halves @ nkeybits - 1).
3157                  */
3158                 nkeybits = keybits;
3159                 if (nkeybits < bref->keybits) {
3160                         if (bref->keybits > 64) {
3161                                 kprintf("bad bref chain %p bref %p\n",
3162                                         chain, bref);
3163                                 Debugger("fubar");
3164                         }
3165                         nkeybits = bref->keybits;
3166                 }
3167                 while (nkeybits < 64 &&
3168                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3169                         (key ^ bref->key)) != 0) {
3170                         ++nkeybits;
3171                 }
3172
3173                 /*
3174                  * If the new key range is larger we have to determine
3175                  * which side of the new key range the existing keys fall
3176                  * under by checking the high bit, then collapsing the
3177                  * locount into the hicount or vise-versa.
3178                  */
3179                 if (keybits != nkeybits) {
3180                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3181                                 hicount += locount;
3182                                 locount = 0;
3183                         } else {
3184                                 locount += hicount;
3185                                 hicount = 0;
3186                         }
3187                         keybits = nkeybits;
3188                 }
3189
3190                 /*
3191                  * The newly scanned key will be in the lower half or the
3192                  * upper half of the (new) key range.
3193                  */
3194                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3195                         ++hicount;
3196                 else
3197                         ++locount;
3198
3199                 if (key_next == 0)
3200                         break;
3201                 key_beg = key_next;
3202         }
3203         spin_unlock(&parent->core.cst.spin);
3204         bref = NULL;    /* now invalid (safety) */
3205
3206         /*
3207          * Adjust keybits to represent half of the full range calculated
3208          * above (radix 63 max)
3209          */
3210         --keybits;
3211
3212         /*
3213          * Select whichever half contains the most elements.  Theoretically
3214          * we can select either side as long as it contains at least one
3215          * element (in order to ensure that a free slot is present to hold
3216          * the indirect block).
3217          */
3218         if (hammer2_indirect_optimize) {
3219                 /*
3220                  * Insert node for least number of keys, this will arrange
3221                  * the first few blocks of a large file or the first few
3222                  * inodes in a directory with fewer indirect blocks when
3223                  * created linearly.
3224                  */
3225                 if (hicount < locount && hicount != 0)
3226                         key |= (hammer2_key_t)1 << keybits;
3227                 else
3228                         key &= ~(hammer2_key_t)1 << keybits;
3229         } else {
3230                 /*
3231                  * Insert node for most number of keys, best for heavily
3232                  * fragmented files.
3233                  */
3234                 if (hicount > locount)
3235                         key |= (hammer2_key_t)1 << keybits;
3236                 else
3237                         key &= ~(hammer2_key_t)1 << keybits;
3238         }
3239         *keyp = key;
3240
3241         return (keybits);
3242 }
3243
3244 /*
3245  * Sets CHAIN_DELETED and remove the chain's blockref from the parent if
3246  * it exists.
3247  *
3248  * Both parent and chain must be locked exclusively.
3249  *
3250  * This function will modify the parent if the blockref requires removal
3251  * from the parent's block table.
3252  *
3253  * This function is NOT recursive.  Any entity already pushed into the
3254  * chain (such as an inode) may still need visibility into its contents,
3255  * as well as the ability to read and modify the contents.  For example,
3256  * for an unlinked file which is still open.
3257  */
3258 void
3259 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3260                      hammer2_chain_t *chain, int flags)
3261 {
3262         KKASSERT(ccms_thread_lock_owned(&chain->core.cst));
3263
3264         /*
3265          * Nothing to do if already marked.
3266          *
3267          * We need the spinlock on the core whos RBTREE contains chain
3268          * to protect against races.
3269          */
3270         if ((chain->flags & HAMMER2_CHAIN_DELETED) == 0) {
3271                 KKASSERT((chain->flags & HAMMER2_CHAIN_DELETED) == 0 &&
3272                          chain->parent == parent);
3273                 _hammer2_chain_delete_helper(trans, parent, chain);
3274         }
3275
3276         if (flags & HAMMER2_DELETE_PERMANENT) {
3277                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_DESTROY);
3278                 hammer2_flush(trans, chain);
3279         } else {
3280                 /* XXX might not be needed */
3281                 hammer2_chain_setflush(trans, chain);
3282         }
3283 }
3284
3285 /*
3286  * Returns the index of the nearest element in the blockref array >= elm.
3287  * Returns (count) if no element could be found.
3288  *
3289  * Sets *key_nextp to the next key for loop purposes but does not modify
3290  * it if the next key would be higher than the current value of *key_nextp.
3291  * Note that *key_nexp can overflow to 0, which should be tested by the
3292  * caller.
3293  *
3294  * (*cache_indexp) is a heuristic and can be any value without effecting
3295  * the result.
3296  *
3297  * The spin lock on the related chain must be held.
3298  */
3299 static int
3300 hammer2_base_find(hammer2_chain_t *parent,
3301                   hammer2_blockref_t *base, int count,
3302                   int *cache_indexp, hammer2_key_t *key_nextp,
3303                   hammer2_key_t key_beg, hammer2_key_t key_end)
3304 {
3305         hammer2_blockref_t *scan;
3306         hammer2_key_t scan_end;
3307         int i;
3308         int limit;
3309
3310         /*
3311          * Require the live chain's already have their core's counted
3312          * so we can optimize operations.
3313          */
3314         KKASSERT(parent->core.flags & HAMMER2_CORE_COUNTEDBREFS);
3315
3316         /*
3317          * Degenerate case
3318          */
3319         if (count == 0 || base == NULL)
3320                 return(count);
3321
3322         /*
3323          * Sequential optimization using *cache_indexp.  This is the most
3324          * likely scenario.
3325          *
3326          * We can avoid trailing empty entries on live chains, otherwise
3327          * we might have to check the whole block array.
3328          */
3329         i = *cache_indexp;
3330         cpu_ccfence();
3331         limit = parent->core.live_zero;
3332         if (i >= limit)
3333                 i = limit - 1;
3334         if (i < 0)
3335                 i = 0;
3336         KKASSERT(i < count);
3337
3338         /*
3339          * Search backwards
3340          */
3341         scan = &base[i];
3342         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
3343                 --scan;
3344                 --i;
3345         }
3346         *cache_indexp = i;
3347
3348         /*
3349          * Search forwards, stop when we find a scan element which
3350          * encloses the key or until we know that there are no further
3351          * elements.
3352          */
3353         while (i < count) {
3354                 if (scan->type != 0) {
3355                         scan_end = scan->key +
3356                                    ((hammer2_key_t)1 << scan->keybits) - 1;
3357                         if (scan->key > key_beg || scan_end >= key_beg)
3358                                 break;
3359                 }
3360                 if (i >= limit)
3361                         return (count);
3362                 ++scan;
3363                 ++i;
3364         }
3365         if (i != count) {
3366                 *cache_indexp = i;
3367                 if (i >= limit) {
3368                         i = count;
3369                 } else {
3370                         scan_end = scan->key +
3371                                    ((hammer2_key_t)1 << scan->keybits);
3372                         if (scan_end && (*key_nextp > scan_end ||
3373                                          *key_nextp == 0)) {
3374                                 *key_nextp = scan_end;
3375                         }
3376                 }
3377         }
3378         return (i);
3379 }
3380
3381 /*
3382  * Do a combined search and return the next match either from the blockref
3383  * array or from the in-memory chain.  Sets *bresp to the returned bref in
3384  * both cases, or sets it to NULL if the search exhausted.  Only returns
3385  * a non-NULL chain if the search matched from the in-memory chain.
3386  *
3387  * When no in-memory chain has been found and a non-NULL bref is returned
3388  * in *bresp.
3389  *
3390  * Must be called with parent's spinlock held.  Spinlock remains held
3391  * through the operation.
3392  *
3393  * The returned chain is not locked or referenced.  Use the returned bref
3394  * to determine if the search exhausted or not.  Iterate if the base find
3395  * is chosen but matches a deleted chain.
3396  */
3397 static hammer2_chain_t *
3398 hammer2_combined_find(hammer2_chain_t *parent,
3399                       hammer2_blockref_t *base, int count,
3400                       int *cache_indexp, hammer2_key_t *key_nextp,
3401                       hammer2_key_t key_beg, hammer2_key_t key_end,
3402                       hammer2_blockref_t **bresp)
3403 {
3404         hammer2_blockref_t *bref;
3405         hammer2_chain_t *chain;
3406         int i;
3407
3408         /*
3409          * Lookup in block array and in rbtree.
3410          */
3411         *key_nextp = key_end + 1;
3412         i = hammer2_base_find(parent, base, count, cache_indexp,
3413                               key_nextp, key_beg, key_end);
3414         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
3415
3416         /*
3417          * Neither matched
3418          */
3419         if (i == count && chain == NULL) {
3420                 *bresp = NULL;
3421                 return(NULL);
3422         }
3423
3424         /*
3425          * Only chain matched.
3426          */
3427         if (i == count) {
3428                 bref = &chain->bref;
3429                 goto found;
3430         }
3431
3432         /*
3433          * Only blockref matched.
3434          */
3435         if (chain == NULL) {
3436                 bref = &base[i];
3437                 goto found;
3438         }
3439
3440         /*
3441          * Both in-memory and blockref matched, select the nearer element.
3442          *
3443          * If both are flush with the left-hand side or both are the
3444          * same distance away, select the chain.  In this situation the
3445          * chain must have been loaded from the matching blockmap.
3446          */
3447         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
3448             chain->bref.key == base[i].key) {
3449                 KKASSERT(chain->bref.key == base[i].key);
3450                 bref = &chain->bref;
3451                 goto found;
3452         }
3453
3454         /*
3455          * Select the nearer key
3456          */
3457         if (chain->bref.key < base[i].key) {
3458                 bref = &chain->bref;
3459         } else {
3460                 bref = &base[i];
3461                 chain = NULL;
3462         }
3463
3464         /*
3465          * If the bref is out of bounds we've exhausted our search.
3466          */
3467 found:
3468         if (bref->key > key_end) {
3469                 *bresp = NULL;
3470                 chain = NULL;
3471         } else {
3472                 *bresp = bref;
3473         }
3474         return(chain);
3475 }
3476
3477 /*
3478  * Locate the specified block array element and delete it.  The element
3479  * must exist.
3480  *
3481  * The spin lock on the related chain must be held.
3482  *
3483  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3484  *       need to be adjusted when we commit the media change.
3485  */
3486 void
3487 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
3488                     hammer2_blockref_t *base, int count,
3489                     int *cache_indexp, hammer2_chain_t *chain)
3490 {
3491         hammer2_blockref_t *elm = &chain->bref;
3492         hammer2_key_t key_next;
3493         int i;
3494
3495         /*
3496          * Delete element.  Expect the element to exist.
3497          *
3498          * XXX see caller, flush code not yet sophisticated enough to prevent
3499          *     re-flushed in some cases.
3500          */
3501         key_next = 0; /* max range */
3502         i = hammer2_base_find(parent, base, count, cache_indexp,
3503                               &key_next, elm->key, elm->key);
3504         if (i == count || base[i].type == 0 ||
3505             base[i].key != elm->key ||
3506             ((chain->flags & HAMMER2_CHAIN_BMAPUPD) == 0 &&
3507              base[i].keybits != elm->keybits)) {
3508                 spin_unlock(&parent->core.cst.spin);
3509                 panic("delete base %p element not found at %d/%d elm %p\n",
3510                       base, i, count, elm);
3511                 return;
3512         }
3513         bzero(&base[i], sizeof(*base));
3514
3515         /*
3516          * We can only optimize parent->core.live_zero for live chains.
3517          */
3518         if (parent->core.live_zero == i + 1) {
3519                 while (--i >= 0 && base[i].type == 0)
3520                         ;
3521                 parent->core.live_zero = i + 1;
3522         }
3523
3524         /*
3525          * Clear appropriate blockmap flags in chain.
3526          */
3527         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_BMAPPED |
3528                                         HAMMER2_CHAIN_BMAPUPD);
3529 }
3530
3531 /*
3532  * Insert the specified element.  The block array must not already have the
3533  * element and must have space available for the insertion.
3534  *
3535  * The spin lock on the related chain must be held.
3536  *
3537  * NOTE: live_count was adjusted when the chain was deleted, so it does not
3538  *       need to be adjusted when we commit the media change.
3539  */
3540 void
3541 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
3542                     hammer2_blockref_t *base, int count,
3543                     int *cache_indexp, hammer2_chain_t *chain)
3544 {
3545         hammer2_blockref_t *elm = &chain->bref;
3546         hammer2_key_t key_next;
3547         hammer2_key_t xkey;
3548         int i;
3549         int j;
3550         int k;
3551         int l;
3552         int u = 1;
3553
3554         /*
3555          * Insert new element.  Expect the element to not already exist
3556          * unless we are replacing it.
3557          *
3558          * XXX see caller, flush code not yet sophisticated enough to prevent
3559          *     re-flushed in some cases.
3560          */
3561         key_next = 0; /* max range */
3562         i = hammer2_base_find(parent, base, count, cache_indexp,
3563                               &key_next, elm->key, elm->key);
3564
3565         /*
3566          * Shortcut fill optimization, typical ordered insertion(s) may not
3567          * require a search.
3568          */
3569         KKASSERT(i >= 0 && i <= count);
3570
3571         /*
3572          * Set appropriate blockmap flags in chain.
3573          */
3574         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
3575
3576         /*
3577          * We can only optimize parent->core.live_zero for live chains.
3578          */
3579         if (i == count && parent->core.live_zero < count) {
3580                 i = parent->core.live_zero++;
3581                 base[i] = *elm;
3582                 return;
3583         }
3584
3585         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
3586         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
3587                 spin_unlock(&parent->core.cst.spin);
3588                 panic("insert base %p overlapping elements at %d elm %p\n",
3589                       base, i, elm);
3590         }
3591
3592         /*
3593          * Try to find an empty slot before or after.
3594          */
3595         j = i;
3596         k = i;
3597         while (j > 0 || k < count) {
3598                 --j;
3599                 if (j >= 0 && base[j].type == 0) {
3600                         if (j == i - 1) {
3601                                 base[j] = *elm;
3602                         } else {
3603                                 bcopy(&base[j+1], &base[j],
3604                                       (i - j - 1) * sizeof(*base));
3605                                 base[i - 1] = *elm;
3606                         }
3607                         goto validate;
3608                 }
3609                 ++k;
3610                 if (k < count && base[k].type == 0) {
3611                         bcopy(&base[i], &base[i+1],
3612                               (k - i) * sizeof(hammer2_blockref_t));
3613                         base[i] = *elm;
3614
3615                         /*
3616                          * We can only update parent->core.live_zero for live
3617                          * chains.
3618                          */
3619                         if (parent->core.live_zero <= k)
3620                                 parent->core.live_zero = k + 1;
3621                         u = 2;
3622                         goto validate;
3623                 }
3624         }
3625         panic("hammer2_base_insert: no room!");
3626
3627         /*
3628          * Debugging
3629          */
3630 validate:
3631         key_next = 0;
3632         for (l = 0; l < count; ++l) {
3633                 if (base[l].type) {
3634                         key_next = base[l].key +
3635                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3636                         break;
3637                 }
3638         }
3639         while (++l < count) {
3640                 if (base[l].type) {
3641                         if (base[l].key <= key_next)
3642                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
3643                         key_next = base[l].key +
3644                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
3645
3646                 }
3647         }
3648
3649 }
3650
3651 #if 0
3652
3653 /*
3654  * Sort the blockref array for the chain.  Used by the flush code to
3655  * sort the blockref[] array.
3656  *
3657  * The chain must be exclusively locked AND spin-locked.
3658  */
3659 typedef hammer2_blockref_t *hammer2_blockref_p;
3660
3661 static
3662 int
3663 hammer2_base_sort_callback(const void *v1, const void *v2)
3664 {
3665         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
3666         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
3667
3668         /*
3669          * Make sure empty elements are placed at the end of the array
3670          */
3671         if (bref1->type == 0) {
3672                 if (bref2->type == 0)
3673                         return(0);
3674                 return(1);
3675         } else if (bref2->type == 0) {
3676                 return(-1);
3677         }
3678
3679         /*
3680          * Sort by key
3681          */
3682         if (bref1->key < bref2->key)
3683                 return(-1);
3684         if (bref1->key > bref2->key)
3685                 return(1);
3686         return(0);
3687 }
3688
3689 void
3690 hammer2_base_sort(hammer2_chain_t *chain)
3691 {
3692         hammer2_blockref_t *base;
3693         int count;
3694
3695         switch(chain->bref.type) {
3696         case HAMMER2_BREF_TYPE_INODE:
3697                 /*
3698                  * Special shortcut for embedded data returns the inode
3699                  * itself.  Callers must detect this condition and access
3700                  * the embedded data (the strategy code does this for us).
3701                  *
3702                  * This is only applicable to regular files and softlinks.
3703                  */
3704                 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
3705                         return;
3706                 base = &chain->data->ipdata.u.blockset.blockref[0];
3707                 count = HAMMER2_SET_COUNT;
3708                 break;
3709         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3710         case HAMMER2_BREF_TYPE_INDIRECT:
3711                 /*
3712                  * Optimize indirect blocks in the INITIAL state to avoid
3713                  * I/O.
3714                  */
3715                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
3716                 base = &chain->data->npdata[0];
3717                 count = chain->bytes / sizeof(hammer2_blockref_t);
3718                 break;
3719         case HAMMER2_BREF_TYPE_VOLUME:
3720                 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
3721                 count = HAMMER2_SET_COUNT;
3722                 break;
3723         case HAMMER2_BREF_TYPE_FREEMAP:
3724                 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
3725                 count = HAMMER2_SET_COUNT;
3726                 break;
3727         default:
3728                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
3729                       chain->bref.type);
3730                 base = NULL;    /* safety */
3731                 count = 0;      /* safety */
3732         }
3733         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
3734 }
3735
3736 #endif
3737
3738 /*
3739  * Chain memory management
3740  */
3741 void
3742 hammer2_chain_wait(hammer2_chain_t *chain)
3743 {
3744         tsleep(chain, 0, "chnflw", 1);
3745 }