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