hammer2 - Stabilization pass
[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  * by 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  * A chain is topologically stable once it has been inserted into the
44  * in-memory topology.  Modifications which copy, move, or resize the chain
45  * are handled via the DELETE-DUPLICATE mechanic where the original chain
46  * stays intact but is marked deleted and a new chain is allocated which
47  * shares the old chain's children.
48  *
49  * This sharing is handled via the hammer2_chain_core structure.
50  *
51  * The DELETE-DUPLICATE mechanism allows the same topological level to contain
52  * many overloadings.  However, our RBTREE mechanics require that there be
53  * no overlaps so we accomplish the overloading by moving conflicting chains
54  * with smaller or equal radii into a sub-RBTREE under the chain being
55  * overloaded.
56  *
57  * DELETE-DUPLICATE is also used when a modification to a chain crosses a
58  * flush synchronization boundary, allowing the flush code to continue flushing
59  * the older version of the topology and not be disrupted by new frontend
60  * operations.
61  *
62  *                              LIVE VS FLUSH VIEW
63  *
64  * All lookup and iterate operations and most modifications are done on the
65  * live view.  During flushes lookups are not normally done and modifications
66  * may be run on the flush view.  However, flushes often needs to allocate
67  * blocks and the freemap_alloc/free code issues lookups.  This code is
68  * special cased to use the live view when called from a flush.
69  *
70  * General chain lookup/iteration functions are NOT aware of the flush view,
71  * they only know about live views.
72  */
73 #include <sys/cdefs.h>
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/types.h>
77 #include <sys/lock.h>
78 #include <sys/kern_syscall.h>
79 #include <sys/uuid.h>
80
81 #include "hammer2.h"
82
83 static int hammer2_indirect_optimize;   /* XXX SYSCTL */
84
85 static hammer2_chain_t *hammer2_chain_create_indirect(
86                 hammer2_trans_t *trans, hammer2_chain_t *parent,
87                 hammer2_key_t key, int keybits, int for_type, int *errorp);
88 static void hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop);
89 static void adjreadcounter(hammer2_blockref_t *bref, size_t bytes);
90 static hammer2_chain_t *hammer2_combined_find(
91                 hammer2_chain_t *parent,
92                 hammer2_blockref_t *base, int count,
93                 int *cache_indexp, hammer2_key_t *key_nextp,
94                 hammer2_key_t key_beg, hammer2_key_t key_end,
95                 hammer2_blockref_t **bresp);
96
97 /*
98  * Basic RBTree for chains (core->rbtree and core->dbtree).  Chains cannot
99  * overlap in the RB trees.  Deleted chains are moved from rbtree to either
100  * dbtree or to dbq.
101  *
102  * Chains in delete-duplicate sequences can always iterate through core_entry
103  * to locate the live version of the chain.
104  */
105 RB_GENERATE(hammer2_chain_tree, hammer2_chain, rbnode, hammer2_chain_cmp);
106
107 int
108 hammer2_chain_cmp(hammer2_chain_t *chain1, hammer2_chain_t *chain2)
109 {
110         hammer2_key_t c1_beg;
111         hammer2_key_t c1_end;
112         hammer2_key_t c2_beg;
113         hammer2_key_t c2_end;
114
115         /*
116          * Compare chains.  Overlaps are not supposed to happen and catch
117          * any software issues early we count overlaps as a match.
118          */
119         c1_beg = chain1->bref.key;
120         c1_end = c1_beg + ((hammer2_key_t)1 << chain1->bref.keybits) - 1;
121         c2_beg = chain2->bref.key;
122         c2_end = c2_beg + ((hammer2_key_t)1 << chain2->bref.keybits) - 1;
123
124         if (c1_end < c2_beg)    /* fully to the left */
125                 return(-1);
126         if (c1_beg > c2_end)    /* fully to the right */
127                 return(1);
128         return(0);              /* overlap (must not cross edge boundary) */
129 }
130
131 static __inline
132 int
133 hammer2_isclusterable(hammer2_chain_t *chain)
134 {
135         if (hammer2_cluster_enable) {
136                 if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
137                     chain->bref.type == HAMMER2_BREF_TYPE_INODE ||
138                     chain->bref.type == HAMMER2_BREF_TYPE_DATA) {
139                         return(1);
140                 }
141         }
142         return(0);
143 }
144
145 /*
146  * Recursively set update_hi starting at chain up through to the root.
147  *
148  * This controls top-down visibility for flushes.  The child has just one
149  * 'above' core, but the core itself can be multi-homed with parents iterated
150  * via core->ownerq.  The last parent is the 'live' parent (all others had to
151  * have been delete-duplicated).  We always propagate upward through the live
152  * parent.
153  *
154  * This function is not used during a flush (except when the flush is
155  * allocating which requires the live tree).  The flush keeps track of its
156  * recursion itself.
157  *
158  * XXX SMP races
159  */
160 void
161 hammer2_chain_setsubmod(hammer2_trans_t *trans, hammer2_chain_t *chain)
162 {
163         hammer2_chain_core_t *above;
164
165         if (chain->update_hi < trans->sync_tid)
166                 chain->update_hi = trans->sync_tid;
167
168         while ((above = chain->above) != NULL) {
169                 spin_lock(&above->cst.spin);
170                 chain = TAILQ_LAST(&above->ownerq, h2_core_list);
171                 if (chain->update_hi < trans->sync_tid)
172                         chain->update_hi = trans->sync_tid;
173                 spin_unlock(&above->cst.spin);
174         }
175 }
176
177 /*
178  * Allocate a new disconnected chain element representing the specified
179  * bref.  chain->refs is set to 1 and the passed bref is copied to
180  * chain->bref.  chain->bytes is derived from the bref.
181  *
182  * chain->core is NOT allocated and the media data and bp pointers are left
183  * NULL.  The caller must call chain_core_alloc() to allocate or associate
184  * a core with the chain.
185  *
186  * NOTE: Returns a referenced but unlocked (because there is no core) chain.
187  */
188 hammer2_chain_t *
189 hammer2_chain_alloc(hammer2_mount_t *hmp, hammer2_pfsmount_t *pmp,
190                     hammer2_trans_t *trans, hammer2_blockref_t *bref)
191 {
192         hammer2_chain_t *chain;
193         u_int bytes = 1U << (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
194
195         /*
196          * Construct the appropriate system structure.
197          */
198         switch(bref->type) {
199         case HAMMER2_BREF_TYPE_INODE:
200         case HAMMER2_BREF_TYPE_INDIRECT:
201         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
202         case HAMMER2_BREF_TYPE_DATA:
203         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
204                 /*
205                  * Chain's are really only associated with the hmp but we
206                  * maintain a pmp association for per-mount memory tracking
207                  * purposes.  The pmp can be NULL.
208                  */
209                 chain = kmalloc(sizeof(*chain), hmp->mchain, M_WAITOK | M_ZERO);
210                 if (pmp)
211                         chain->pmp = pmp;
212                 break;
213         case HAMMER2_BREF_TYPE_VOLUME:
214         case HAMMER2_BREF_TYPE_FREEMAP:
215                 chain = NULL;
216                 panic("hammer2_chain_alloc volume type illegal for op");
217         default:
218                 chain = NULL;
219                 panic("hammer2_chain_alloc: unrecognized blockref type: %d",
220                       bref->type);
221         }
222
223         chain->hmp = hmp;
224         chain->bref = *bref;
225         chain->bytes = bytes;
226         chain->refs = 1;
227         chain->flags = HAMMER2_CHAIN_ALLOCATED;
228         chain->delete_tid = HAMMER2_MAX_TID;
229
230         /*
231          * Set modify_tid if a transaction is creating the inode.
232          * Enforce update_lo = 0 so nearby transactions do not think
233          * it has been flushed when it hasn't.
234          *
235          * NOTE: When loading a chain from backing store or creating a
236          *       snapshot, trans will be NULL and the caller is responsible
237          *       for setting these fields.
238          */
239         if (trans) {
240                 chain->modify_tid = trans->sync_tid;
241                 chain->update_lo = 0;
242         }
243
244         return (chain);
245 }
246
247 /*
248  * Associate an existing core with the chain or allocate a new core.
249  *
250  * The core is not locked.  No additional refs on the chain are made.
251  * (trans) must not be NULL if (core) is not NULL.
252  *
253  * When chains are delete-duplicated during flushes we insert nchain on
254  * the ownerq after ochain instead of at the end in order to give the
255  * drop code visibility in the correct order, otherwise drops can be missed.
256  */
257 void
258 hammer2_chain_core_alloc(hammer2_trans_t *trans,
259                          hammer2_chain_t *nchain, hammer2_chain_t *ochain)
260 {
261         hammer2_chain_core_t *core;
262
263         KKASSERT(nchain->core == NULL);
264
265         if (ochain == NULL) {
266                 /*
267                  * Fresh core under nchain (no multi-homing of ochain's
268                  * sub-tree).
269                  */
270                 core = kmalloc(sizeof(*core), nchain->hmp->mchain,
271                                M_WAITOK | M_ZERO);
272                 TAILQ_INIT(&core->ownerq);
273                 TAILQ_INIT(&core->dbq);
274                 RB_INIT(&core->rbtree); /* live chains */
275                 RB_INIT(&core->dbtree); /* deleted original (bmapped) chains */
276                 core->sharecnt = 1;
277                 core->good = 0x1234;
278                 nchain->core = core;
279                 ccms_cst_init(&core->cst, nchain);
280                 TAILQ_INSERT_TAIL(&core->ownerq, nchain, core_entry);
281         } else {
282                 /*
283                  * Propagate the PFSROOT flag which we set on all subdirs
284                  * under the super-root.
285                  */
286                 atomic_set_int(&nchain->flags,
287                                ochain->flags & HAMMER2_CHAIN_PFSROOT);
288
289                 /*
290                  * Duplicating ochain -> nchain.  Set the DUPLICATED flag on
291                  * ochain if nchain is not a snapshot.
292                  *
293                  * It is possible for the DUPLICATED flag to already be
294                  * set when called via a flush operation because flush
295                  * operations may have to work on elements with delete_tid's
296                  * beyond the flush sync_tid.  In this situation we must
297                  * ensure that nchain is placed just after ochain in the
298                  * ownerq and that the DUPLICATED flag is set on nchain so
299                  * 'live' operations skip past it to the correct chain.
300                  *
301                  * The flusher understands the blockref synchronization state
302                  * for any stale chains by observing bref.mirror_tid, which
303                  * delete-duplicate replicates.
304                  *
305                  * WARNING! However, the case is disallowed when the flusher
306                  *          is allocating freemap space because this entails
307                  *          more than just adjusting a block table.
308                  */
309                 if (ochain->flags & HAMMER2_CHAIN_DUPLICATED) {
310                         KKASSERT((trans->flags &
311                                   (HAMMER2_TRANS_ISFLUSH |
312                                    HAMMER2_TRANS_ISALLOCATING)) ==
313                                  HAMMER2_TRANS_ISFLUSH);
314                         atomic_set_int(&nchain->flags,
315                                        HAMMER2_CHAIN_DUPLICATED);
316                 }
317                 if ((nchain->flags & HAMMER2_CHAIN_SNAPSHOT) == 0) {
318                         atomic_set_int(&ochain->flags,
319                                        HAMMER2_CHAIN_DUPLICATED);
320                 }
321                 core = ochain->core;
322                 atomic_add_int(&core->sharecnt, 1);
323
324                 spin_lock(&core->cst.spin);
325                 nchain->core = core;
326
327                 /*
328                  * Maintain ordering for refactor test so we don't skip over
329                  * a snapshot.  Also, during flushes, delete-duplications
330                  * for block-table updates can occur on ochains already
331                  * deleted (delete-duplicated by a later transaction), or
332                  * on forward-indexed ochains.  We must properly insert
333                  * nchain relative to ochain.
334                  */
335                 if (trans && trans->sync_tid < ochain->modify_tid) {
336                         TAILQ_INSERT_BEFORE(ochain, nchain, core_entry);
337                 } else {
338                         TAILQ_INSERT_AFTER(&core->ownerq, ochain,
339                                            nchain, core_entry);
340                 }
341                 spin_unlock(&core->cst.spin);
342         }
343 }
344
345 /*
346  * Add a reference to a chain element, preventing its destruction.
347  */
348 void
349 hammer2_chain_ref(hammer2_chain_t *chain)
350 {
351         atomic_add_int(&chain->refs, 1);
352 }
353
354 /*
355  * Insert the chain in the core rbtree.
356  *
357  * Normal insertions are placed in the live rbtree.  Insertion of a deleted
358  * chain is a special case used by the flush code that is placed on the
359  * unstaged deleted list to avoid confusing the live view.
360  */
361 #define HAMMER2_CHAIN_INSERT_SPIN       0x0001
362 #define HAMMER2_CHAIN_INSERT_LIVE       0x0002
363 #define HAMMER2_CHAIN_INSERT_RACE       0x0004
364
365 static
366 int
367 hammer2_chain_insert(hammer2_chain_core_t *above,
368                      hammer2_chain_t *ochain, hammer2_chain_t *nchain,
369                      int flags, int generation)
370 {
371         hammer2_chain_t *xchain;
372         int error = 0;
373
374         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
375                 spin_lock(&above->cst.spin);
376
377         /*
378          * Interlocked by spinlock, check for race
379          */
380         if ((flags & HAMMER2_CHAIN_INSERT_RACE) &&
381             above->generation != generation) {
382                 error = EAGAIN;
383                 goto failed;
384         }
385
386         /*
387          * Insert nchain
388          *
389          * XXX BMAPPED might not be handled correctly for ochain/nchain
390          *     ordering in both DELETED cases (flush and non-flush-term),
391          *     so delete-duplicate code.
392          */
393         if (nchain->flags & HAMMER2_CHAIN_DELETED) {
394                 if (ochain && (ochain->flags & HAMMER2_CHAIN_BMAPPED)) {
395                         if (ochain->flags & HAMMER2_CHAIN_ONDBTREE) {
396                                 RB_REMOVE(hammer2_chain_tree,
397                                           &above->dbtree, ochain);
398                                 atomic_clear_int(&ochain->flags,
399                                                  HAMMER2_CHAIN_ONDBTREE);
400                                 TAILQ_INSERT_TAIL(&above->dbq,
401                                                   ochain, db_entry);
402                                 atomic_set_int(&ochain->flags,
403                                                 HAMMER2_CHAIN_ONDBQ);
404                         }
405                         /* clear BMAPPED (DBTREE, sometimes RBTREE) */
406                         atomic_clear_int(&ochain->flags, HAMMER2_CHAIN_BMAPPED);
407
408                         xchain = RB_INSERT(hammer2_chain_tree,
409                                            &above->dbtree, nchain);
410                         KKASSERT(xchain == NULL);
411                         atomic_set_int(&nchain->flags,
412                                        HAMMER2_CHAIN_ONDBTREE |
413                                        HAMMER2_CHAIN_BMAPPED);
414                 } else {
415                         TAILQ_INSERT_TAIL(&above->dbq, nchain, db_entry);
416                         atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONDBQ);
417                 }
418         } else {
419                 xchain = RB_INSERT(hammer2_chain_tree, &above->rbtree, nchain);
420                 KASSERT(xchain == NULL,
421                         ("hammer2_chain_insert: collision %p", nchain));
422                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_ONRBTREE);
423         }
424
425         nchain->above = above;
426         ++above->chain_count;
427         ++above->generation;
428
429         /*
430          * We have to keep track of the effective live-view blockref count
431          * so the create code knows when to push an indirect block.
432          */
433         if (flags & HAMMER2_CHAIN_INSERT_LIVE)
434                 atomic_add_int(&above->live_count, 1);
435 failed:
436         if (flags & HAMMER2_CHAIN_INSERT_SPIN)
437                 spin_unlock(&above->cst.spin);
438         return error;
439 }
440
441 /*
442  * Drop the caller's reference to the chain.  When the ref count drops to
443  * zero this function will try to disassociate the chain from its parent and
444  * deallocate it, then recursely drop the parent using the implied ref
445  * from the chain's chain->parent.
446  */
447 static hammer2_chain_t *hammer2_chain_lastdrop(hammer2_chain_t *chain,
448                                                struct h2_core_list *delayq);
449
450 void
451 hammer2_chain_drop(hammer2_chain_t *chain)
452 {
453         struct h2_core_list delayq;
454         hammer2_chain_t *scan;
455         u_int refs;
456         u_int need = 0;
457
458         if (hammer2_debug & 0x200000)
459                 Debugger("drop");
460
461         if (chain->flags & HAMMER2_CHAIN_FLUSH_CREATE)
462                 ++need;
463         if (chain->flags & HAMMER2_CHAIN_FLUSH_DELETE)
464                 ++need;
465         if (chain->flags & HAMMER2_CHAIN_MODIFIED)
466                 ++need;
467         KKASSERT(chain->refs > need);
468
469         TAILQ_INIT(&delayq);
470
471         while (chain) {
472                 refs = chain->refs;
473                 cpu_ccfence();
474                 KKASSERT(refs > 0);
475
476                 if (refs == 1) {
477                         chain = hammer2_chain_lastdrop(chain, &delayq);
478                 } else {
479                         if (atomic_cmpset_int(&chain->refs, refs, refs - 1))
480                                 break;
481                         /* retry the same chain */
482                 }
483
484                 /*
485                  * When we've exhausted lastdrop chaining pull off of delayq.
486                  * chains on delayq are dead but are used to placehold other
487                  * chains which we added a ref to for the purpose of dropping.
488                  */
489                 if (chain == NULL) {
490                         hammer2_mount_t *hmp;
491
492                         if ((scan = TAILQ_FIRST(&delayq)) != NULL) {
493                                 chain = (void *)scan->data;
494                                 TAILQ_REMOVE(&delayq, scan, core_entry);
495                                 scan->flags &= ~HAMMER2_CHAIN_ALLOCATED;
496                                 hmp = scan->hmp;
497                                 scan->hmp = NULL;
498                                 kfree(scan, hmp->mchain);
499                         }
500                 }
501         }
502 }
503
504 /*
505  * Safe handling of the 1->0 transition on chain.  Returns a chain for
506  * recursive drop or NULL, possibly returning the same chain if the atomic
507  * op fails.
508  *
509  * Whem two chains need to be recursively dropped we use the chain
510  * we would otherwise free to placehold the additional chain.  It's a bit
511  * convoluted but we can't just recurse without potentially blowing out
512  * the kernel stack.
513  *
514  * The chain cannot be freed if it has a non-empty core (children) or
515  * it is not at the head of ownerq.
516  *
517  * The cst spinlock is allowed nest child-to-parent (not parent-to-child).
518  */
519 static
520 hammer2_chain_t *
521 hammer2_chain_lastdrop(hammer2_chain_t *chain, struct h2_core_list *delayq)
522 {
523         hammer2_pfsmount_t *pmp;
524         hammer2_mount_t *hmp;
525         hammer2_chain_core_t *above;
526         hammer2_chain_core_t *core;
527         hammer2_chain_t *rdrop1;
528         hammer2_chain_t *rdrop2;
529
530         /*
531          * Spinlock the core and check to see if it is empty.  If it is
532          * not empty we leave chain intact with refs == 0.  The elements
533          * in core->rbtree are associated with other chains contemporary
534          * with ours but not with our chain directly.
535          */
536         if ((core = chain->core) != NULL) {
537                 spin_lock(&core->cst.spin);
538
539                 /*
540                  * We can't free non-stale chains with children until we are
541                  * able to free the children because there might be a flush
542                  * dependency.  Flushes of stale children (which should also
543                  * have their deleted flag set) short-cut recursive flush
544                  * dependencies and can be freed here.  Any flushes which run
545                  * through stale children due to the flush synchronization
546                  * point should have a FLUSH_* bit set in the chain and not
547                  * reach lastdrop at this time.
548                  *
549                  * NOTE: We return (chain) on failure to retry.
550                  */
551                 if (core->chain_count &&
552                     (chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
553                         if (atomic_cmpset_int(&chain->refs, 1, 0))
554                                 chain = NULL;   /* success */
555                         spin_unlock(&core->cst.spin);
556                         return(chain);
557                 }
558                 /* no chains left under us */
559
560                 /*
561                  * Various parts of the code might be holding a ref on a
562                  * stale chain as a placemarker which must be iterated to
563                  * locate a later non-stale (live) chain.  We must be sure
564                  * NOT to free the later non-stale chain (which might have
565                  * no refs).  Otherwise mass confusion may result.
566                  *
567                  * The DUPLICATED flag tells us whether the chain is stale
568                  * or not, so the rule is that any chain whos DUPLICATED flag
569                  * is NOT set must also be at the head of the ownerq.
570                  *
571                  * Note that the DELETED flag is not involved.  That is, a
572                  * live chain can represent a deletion that has not yet been
573                  * flushed (or still has refs).
574                  */
575 #if 0
576                 if (TAILQ_NEXT(chain, core_entry) == NULL &&
577                     TAILQ_FIRST(&core->ownerq) != chain) {
578 #endif
579                 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 &&
580                     TAILQ_FIRST(&core->ownerq) != chain) {
581                         if (atomic_cmpset_int(&chain->refs, 1, 0))
582                                 chain = NULL;   /* success */
583                         spin_unlock(&core->cst.spin);
584                         return(chain);
585                 }
586         }
587
588         /*
589          * chain->core has no children left so no accessors can get to our
590          * chain from there.  Now we have to lock the above core to interlock
591          * remaining possible accessors that might bump chain's refs before
592          * we can safely drop chain's refs with intent to free the chain.
593          */
594         hmp = chain->hmp;
595         pmp = chain->pmp;       /* can be NULL */
596         rdrop1 = NULL;
597         rdrop2 = NULL;
598
599         /*
600          * Spinlock the parent and try to drop the last ref on chain.
601          * On success remove chain from its parent, otherwise return NULL.
602          *
603          * (normal core locks are top-down recursive but we define core
604          *  spinlocks as bottom-up recursive, so this is safe).
605          */
606         if ((above = chain->above) != NULL) {
607                 spin_lock(&above->cst.spin);
608                 if (atomic_cmpset_int(&chain->refs, 1, 0) == 0) {
609                         /* 1->0 transition failed */
610                         spin_unlock(&above->cst.spin);
611                         if (core)
612                                 spin_unlock(&core->cst.spin);
613                         return(chain);  /* retry */
614                 }
615
616                 /*
617                  * 1->0 transition successful, remove chain from its
618                  * above core.
619                  */
620                 switch (chain->flags & (HAMMER2_CHAIN_ONRBTREE |
621                                         HAMMER2_CHAIN_ONDBTREE |
622                                         HAMMER2_CHAIN_ONDBQ)) {
623                 case HAMMER2_CHAIN_ONRBTREE:
624                         RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
625                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
626                         break;
627                 case HAMMER2_CHAIN_ONDBTREE:
628                         RB_REMOVE(hammer2_chain_tree, &above->dbtree, chain);
629                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
630                         break;
631                 case HAMMER2_CHAIN_ONDBQ:
632                         TAILQ_REMOVE(&above->dbq, chain, db_entry);
633                         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
634                         break;
635                 default:
636                         panic("hammer2_chain_lastdrop: chain %p badflags %08x",
637                               chain, chain->flags);
638                         break;
639                 }
640
641                 --above->chain_count;
642                 chain->above = NULL;
643
644                 /*
645                  * If our chain was the last chain in the parent's core the
646                  * core is now empty and its parents might now be droppable.
647                  * Try to drop the first multi-homed parent by gaining a
648                  * ref on it here and then dropping it below.
649                  */
650                 if (above->chain_count == 0) {
651                         rdrop1 = TAILQ_FIRST(&above->ownerq);
652                         if (rdrop1 &&
653                             atomic_cmpset_int(&rdrop1->refs, 0, 1) == 0) {
654                                 rdrop1 = NULL;
655                         }
656                 }
657                 spin_unlock(&above->cst.spin);
658                 above = NULL;   /* safety */
659         }
660
661         /*
662          * Successful 1->0 transition and the chain can be destroyed now.
663          *
664          * We still have the core spinlock (if core is non-NULL), and core's
665          * chain_count is 0.  The above spinlock is gone.
666          *
667          * Remove chain from ownerq.  Once core has no more owners (and no
668          * children which is already the case) we can destroy core.
669          *
670          * If core has more owners we may be able to continue a bottom-up
671          * drop with our next sibling.
672          */
673         if (core) {
674                 chain->core = NULL;
675
676                 TAILQ_REMOVE(&core->ownerq, chain, core_entry);
677                 rdrop2 = TAILQ_FIRST(&core->ownerq);
678                 if (rdrop2 && atomic_cmpset_int(&rdrop2->refs, 0, 1) == 0)
679                         rdrop2 = NULL;
680                 spin_unlock(&core->cst.spin);
681
682                 /*
683                  * We can do the final 1->0 transition with an atomic op
684                  * after releasing core's spinlock.
685                  */
686                 if (atomic_fetchadd_int(&core->sharecnt, -1) == 1) {
687                         /*
688                          * On the 1->0 transition of core we can destroy
689                          * it.
690                          */
691                         KKASSERT(TAILQ_EMPTY(&core->ownerq));
692                         KKASSERT(RB_EMPTY(&core->rbtree) &&
693                                  RB_EMPTY(&core->dbtree) &&
694                                  TAILQ_EMPTY(&core->dbq) &&
695                                  core->chain_count == 0);
696                         KKASSERT(core->cst.count == 0);
697                         KKASSERT(core->cst.upgrade == 0);
698                         core->good = 0x5678;
699                         kfree(core, hmp->mchain);
700                 }
701                 core = NULL;    /* safety */
702         }
703
704         /*
705          * All spin locks are gone, finish freeing stuff.
706          */
707         KKASSERT((chain->flags & (HAMMER2_CHAIN_FLUSH_CREATE |
708                                   HAMMER2_CHAIN_FLUSH_DELETE |
709                                   HAMMER2_CHAIN_MODIFIED)) == 0);
710         hammer2_chain_drop_data(chain, 1);
711
712         KKASSERT(chain->dio == NULL);
713
714         /*
715          * Once chain resources are gone we can use the now dead chain
716          * structure to placehold what might otherwise require a recursive
717          * drop, because we have potentially two things to drop and can only
718          * return one directly.
719          */
720         if (rdrop1 && rdrop2) {
721                 KKASSERT(chain->flags & HAMMER2_CHAIN_ALLOCATED);
722                 chain->data = (void *)rdrop1;
723                 TAILQ_INSERT_TAIL(delayq, chain, core_entry);
724                 rdrop1 = NULL;
725         } else if (chain->flags & HAMMER2_CHAIN_ALLOCATED) {
726                 chain->flags &= ~HAMMER2_CHAIN_ALLOCATED;
727                 chain->hmp = NULL;
728                 kfree(chain, hmp->mchain);
729         }
730
731         /*
732          * Either or both can be NULL.  We already handled the case where
733          * both might not have been NULL.
734          */
735         if (rdrop1)
736                 return(rdrop1);
737         else
738                 return(rdrop2);
739 }
740
741 /*
742  * On either last lock release or last drop
743  */
744 static void
745 hammer2_chain_drop_data(hammer2_chain_t *chain, int lastdrop)
746 {
747         /*hammer2_mount_t *hmp = chain->hmp;*/
748
749         switch(chain->bref.type) {
750         case HAMMER2_BREF_TYPE_VOLUME:
751         case HAMMER2_BREF_TYPE_FREEMAP:
752                 if (lastdrop)
753                         chain->data = NULL;
754                 break;
755         default:
756                 KKASSERT(chain->data == NULL);
757                 break;
758         }
759 }
760
761 /*
762  * Ref and lock a chain element, acquiring its data with I/O if necessary,
763  * and specify how you would like the data to be resolved.
764  *
765  * Returns 0 on success or an error code if the data could not be acquired.
766  * The chain element is locked on return regardless of whether an error
767  * occurred or not.
768  *
769  * The lock is allowed to recurse, multiple locking ops will aggregate
770  * the requested resolve types.  Once data is assigned it will not be
771  * removed until the last unlock.
772  *
773  * HAMMER2_RESOLVE_NEVER - Do not resolve the data element.
774  *                         (typically used to avoid device/logical buffer
775  *                          aliasing for data)
776  *
777  * HAMMER2_RESOLVE_MAYBE - Do not resolve data elements for chains in
778  *                         the INITIAL-create state (indirect blocks only).
779  *
780  *                         Do not resolve data elements for DATA chains.
781  *                         (typically used to avoid device/logical buffer
782  *                          aliasing for data)
783  *
784  * HAMMER2_RESOLVE_ALWAYS- Always resolve the data element.
785  *
786  * HAMMER2_RESOLVE_SHARED- (flag) The chain is locked shared, otherwise
787  *                         it will be locked exclusive.
788  *
789  * NOTE: Embedded elements (volume header, inodes) are always resolved
790  *       regardless.
791  *
792  * NOTE: Specifying HAMMER2_RESOLVE_ALWAYS on a newly-created non-embedded
793  *       element will instantiate and zero its buffer, and flush it on
794  *       release.
795  *
796  * NOTE: (data) elements are normally locked RESOLVE_NEVER or RESOLVE_MAYBE
797  *       so as not to instantiate a device buffer, which could alias against
798  *       a logical file buffer.  However, if ALWAYS is specified the
799  *       device buffer will be instantiated anyway.
800  *
801  * WARNING! If data must be fetched a shared lock will temporarily be
802  *          upgraded to exclusive.  However, a deadlock can occur if
803  *          the caller owns more than one shared lock.
804  */
805 int
806 hammer2_chain_lock(hammer2_chain_t *chain, int how)
807 {
808         hammer2_mount_t *hmp;
809         hammer2_chain_core_t *core;
810         hammer2_blockref_t *bref;
811         ccms_state_t ostate;
812         char *bdata;
813         int error;
814
815         /*
816          * Ref and lock the element.  Recursive locks are allowed.
817          */
818         if ((how & HAMMER2_RESOLVE_NOREF) == 0)
819                 hammer2_chain_ref(chain);
820         atomic_add_int(&chain->lockcnt, 1);
821
822         hmp = chain->hmp;
823         KKASSERT(hmp != NULL);
824
825         /*
826          * Get the appropriate lock.
827          */
828         core = chain->core;
829         if (how & HAMMER2_RESOLVE_SHARED)
830                 ccms_thread_lock(&core->cst, CCMS_STATE_SHARED);
831         else
832                 ccms_thread_lock(&core->cst, CCMS_STATE_EXCLUSIVE);
833
834         /*
835          * If we already have a valid data pointer no further action is
836          * necessary.
837          */
838         if (chain->data)
839                 return (0);
840
841         /*
842          * Do we have to resolve the data?
843          */
844         switch(how & HAMMER2_RESOLVE_MASK) {
845         case HAMMER2_RESOLVE_NEVER:
846                 return(0);
847         case HAMMER2_RESOLVE_MAYBE:
848                 if (chain->flags & HAMMER2_CHAIN_INITIAL)
849                         return(0);
850                 if (chain->bref.type == HAMMER2_BREF_TYPE_DATA)
851                         return(0);
852 #if 0
853                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE)
854                         return(0);
855 #endif
856                 if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF)
857                         return(0);
858                 /* fall through */
859         case HAMMER2_RESOLVE_ALWAYS:
860                 break;
861         }
862
863         /*
864          * Upgrade to an exclusive lock so we can safely manipulate the
865          * buffer cache.  If another thread got to it before us we
866          * can just return.
867          */
868         ostate = ccms_thread_lock_upgrade(&core->cst);
869         if (chain->data) {
870                 ccms_thread_lock_downgrade(&core->cst, ostate);
871                 return (0);
872         }
873
874         /*
875          * We must resolve to a device buffer, either by issuing I/O or
876          * by creating a zero-fill element.  We do not mark the buffer
877          * dirty when creating a zero-fill element (the hammer2_chain_modify()
878          * API must still be used to do that).
879          *
880          * The device buffer is variable-sized in powers of 2 down
881          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
882          * chunk always contains buffers of the same size. (XXX)
883          *
884          * The minimum physical IO size may be larger than the variable
885          * block size.
886          */
887         bref = &chain->bref;
888
889         /*
890          * The getblk() optimization can only be used on newly created
891          * elements if the physical block size matches the request.
892          */
893         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
894                 error = hammer2_io_new(hmp, bref->data_off, chain->bytes,
895                                         &chain->dio);
896         } else {
897                 error = hammer2_io_bread(hmp, bref->data_off, chain->bytes,
898                                          &chain->dio);
899                 adjreadcounter(&chain->bref, chain->bytes);
900         }
901
902         if (error) {
903                 kprintf("hammer2_chain_lock: I/O error %016jx: %d\n",
904                         (intmax_t)bref->data_off, error);
905                 hammer2_io_bqrelse(&chain->dio);
906                 ccms_thread_lock_downgrade(&core->cst, ostate);
907                 return (error);
908         }
909
910 #if 0
911         /*
912          * No need for this, always require that hammer2_chain_modify()
913          * be called before any modifying operations.
914          */
915         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) &&
916             !hammer2_io_isdirty(chain->dio)) {
917                 hammer2_io_setdirty(chain->dio);
918         }
919 #endif
920
921         /*
922          * We can clear the INITIAL state now, we've resolved the buffer
923          * to zeros and marked it dirty with hammer2_io_new().
924          */
925         bdata = hammer2_io_data(chain->dio, chain->bref.data_off);
926         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
927                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
928         }
929
930         /*
931          * Setup the data pointer, either pointing it to an embedded data
932          * structure and copying the data from the buffer, or pointing it
933          * into the buffer.
934          *
935          * The buffer is not retained when copying to an embedded data
936          * structure in order to avoid potential deadlocks or recursions
937          * on the same physical buffer.
938          */
939         switch (bref->type) {
940         case HAMMER2_BREF_TYPE_VOLUME:
941         case HAMMER2_BREF_TYPE_FREEMAP:
942                 /*
943                  * Copy data from bp to embedded buffer
944                  */
945                 panic("hammer2_chain_lock: called on unresolved volume header");
946                 break;
947         case HAMMER2_BREF_TYPE_INODE:
948         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
949         case HAMMER2_BREF_TYPE_INDIRECT:
950         case HAMMER2_BREF_TYPE_DATA:
951         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
952         default:
953                 /*
954                  * Point data at the device buffer and leave dio intact.
955                  */
956                 chain->data = (void *)bdata;
957                 break;
958         }
959         ccms_thread_lock_downgrade(&core->cst, ostate);
960         return (0);
961 }
962
963 /*
964  * This basically calls hammer2_io_breadcb() but does some pre-processing
965  * of the chain first to handle certain cases.
966  */
967 void
968 hammer2_chain_load_async(hammer2_chain_t *chain,
969                          void (*callback)(hammer2_io_t *dio,
970                                           hammer2_chain_t *chain,
971                                           void *arg_p, off_t arg_o),
972                          void *arg_p, off_t arg_o)
973 {
974         hammer2_mount_t *hmp;
975         struct hammer2_io *dio;
976         hammer2_blockref_t *bref;
977         int error;
978
979         if (chain->data) {
980                 callback(NULL, chain, arg_p, arg_o);
981                 return;
982         }
983
984         /*
985          * We must resolve to a device buffer, either by issuing I/O or
986          * by creating a zero-fill element.  We do not mark the buffer
987          * dirty when creating a zero-fill element (the hammer2_chain_modify()
988          * API must still be used to do that).
989          *
990          * The device buffer is variable-sized in powers of 2 down
991          * to HAMMER2_MIN_ALLOC (typically 1K).  A 64K physical storage
992          * chunk always contains buffers of the same size. (XXX)
993          *
994          * The minimum physical IO size may be larger than the variable
995          * block size.
996          */
997         bref = &chain->bref;
998         hmp = chain->hmp;
999
1000         /*
1001          * The getblk() optimization can only be used on newly created
1002          * elements if the physical block size matches the request.
1003          */
1004         if ((chain->flags & HAMMER2_CHAIN_INITIAL) &&
1005             chain->bytes == hammer2_devblksize(chain->bytes)) {
1006                 error = hammer2_io_new(hmp, bref->data_off, chain->bytes, &dio);
1007                 KKASSERT(error == 0);
1008                 callback(dio, chain, arg_p, arg_o);
1009                 return;
1010         }
1011
1012         /*
1013          * Otherwise issue a read
1014          */
1015         adjreadcounter(&chain->bref, chain->bytes);
1016         hammer2_io_breadcb(hmp, bref->data_off, chain->bytes,
1017                            callback, chain, arg_p, arg_o);
1018 }
1019
1020 /*
1021  * Unlock and deref a chain element.
1022  *
1023  * On the last lock release any non-embedded data (chain->dio) will be
1024  * retired.
1025  */
1026 void
1027 hammer2_chain_unlock(hammer2_chain_t *chain)
1028 {
1029         hammer2_chain_core_t *core = chain->core;
1030         ccms_state_t ostate;
1031         long *counterp;
1032         u_int lockcnt;
1033
1034         /*
1035          * The core->cst lock can be shared across several chains so we
1036          * need to track the per-chain lockcnt separately.
1037          *
1038          * If multiple locks are present (or being attempted) on this
1039          * particular chain we can just unlock, drop refs, and return.
1040          *
1041          * Otherwise fall-through on the 1->0 transition.
1042          */
1043         for (;;) {
1044                 lockcnt = chain->lockcnt;
1045                 KKASSERT(lockcnt > 0);
1046                 cpu_ccfence();
1047                 if (lockcnt > 1) {
1048                         if (atomic_cmpset_int(&chain->lockcnt,
1049                                               lockcnt, lockcnt - 1)) {
1050                                 ccms_thread_unlock(&core->cst);
1051                                 hammer2_chain_drop(chain);
1052                                 return;
1053                         }
1054                 } else {
1055                         if (atomic_cmpset_int(&chain->lockcnt, 1, 0))
1056                                 break;
1057                 }
1058                 /* retry */
1059         }
1060
1061         /*
1062          * On the 1->0 transition we upgrade the core lock (if necessary)
1063          * to exclusive for terminal processing.  If after upgrading we find
1064          * that lockcnt is non-zero, another thread is racing us and will
1065          * handle the unload for us later on, so just cleanup and return
1066          * leaving the data/io intact
1067          *
1068          * Otherwise if lockcnt is still 0 it is possible for it to become
1069          * non-zero and race, but since we hold the core->cst lock
1070          * exclusively all that will happen is that the chain will be
1071          * reloaded after we unload it.
1072          */
1073         ostate = ccms_thread_lock_upgrade(&core->cst);
1074         if (chain->lockcnt) {
1075                 ccms_thread_unlock_upgraded(&core->cst, ostate);
1076                 hammer2_chain_drop(chain);
1077                 return;
1078         }
1079
1080         /*
1081          * Shortcut the case if the data is embedded or not resolved.
1082          *
1083          * Do NOT NULL out chain->data (e.g. inode data), it might be
1084          * dirty.
1085          */
1086         if (chain->dio == NULL) {
1087                 if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0)
1088                         hammer2_chain_drop_data(chain, 0);
1089                 ccms_thread_unlock_upgraded(&core->cst, ostate);
1090                 hammer2_chain_drop(chain);
1091                 return;
1092         }
1093
1094         /*
1095          * Statistics
1096          */
1097         if (hammer2_io_isdirty(chain->dio) == 0) {
1098                 ;
1099         } else if (chain->flags & HAMMER2_CHAIN_IOFLUSH) {
1100                 switch(chain->bref.type) {
1101                 case HAMMER2_BREF_TYPE_DATA:
1102                         counterp = &hammer2_ioa_file_write;
1103                         break;
1104                 case HAMMER2_BREF_TYPE_INODE:
1105                         counterp = &hammer2_ioa_meta_write;
1106                         break;
1107                 case HAMMER2_BREF_TYPE_INDIRECT:
1108                         counterp = &hammer2_ioa_indr_write;
1109                         break;
1110                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1111                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1112                         counterp = &hammer2_ioa_fmap_write;
1113                         break;
1114                 default:
1115                         counterp = &hammer2_ioa_volu_write;
1116                         break;
1117                 }
1118                 *counterp += chain->bytes;
1119         } else {
1120                 switch(chain->bref.type) {
1121                 case HAMMER2_BREF_TYPE_DATA:
1122                         counterp = &hammer2_iod_file_write;
1123                         break;
1124                 case HAMMER2_BREF_TYPE_INODE:
1125                         counterp = &hammer2_iod_meta_write;
1126                         break;
1127                 case HAMMER2_BREF_TYPE_INDIRECT:
1128                         counterp = &hammer2_iod_indr_write;
1129                         break;
1130                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1131                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1132                         counterp = &hammer2_iod_fmap_write;
1133                         break;
1134                 default:
1135                         counterp = &hammer2_iod_volu_write;
1136                         break;
1137                 }
1138                 *counterp += chain->bytes;
1139         }
1140
1141         /*
1142          * Clean out the dio.
1143          *
1144          * If a device buffer was used for data be sure to destroy the
1145          * buffer when we are done to avoid aliases (XXX what about the
1146          * underlying VM pages?).
1147          *
1148          * NOTE: Freemap leaf's use reserved blocks and thus no aliasing
1149          *       is possible.
1150          *
1151          * NOTE: The isdirty check tracks whether we have to bdwrite() the
1152          *       buffer or not.  The buffer might already be dirty.  The
1153          *       flag is re-set when chain_modify() is called, even if
1154          *       MODIFIED is already set, allowing the OS to retire the
1155          *       buffer independent of a hammer2 flush.
1156          */
1157         chain->data = NULL;
1158         if ((chain->flags & HAMMER2_CHAIN_IOFLUSH) &&
1159             hammer2_io_isdirty(chain->dio)) {
1160                 hammer2_io_bawrite(&chain->dio);
1161         } else {
1162                 hammer2_io_bqrelse(&chain->dio);
1163         }
1164         ccms_thread_unlock_upgraded(&core->cst, ostate);
1165         hammer2_chain_drop(chain);
1166 }
1167
1168 /*
1169  * This counts the number of live blockrefs in a block array and
1170  * also calculates the point at which all remaining blockrefs are empty.
1171  * This routine can only be called on a live chain (DUPLICATED flag not set).
1172  *
1173  * NOTE: Flag is not set until after the count is complete, allowing
1174  *       callers to test the flag without holding the spinlock.
1175  *
1176  * NOTE: If base is NULL the related chain is still in the INITIAL
1177  *       state and there are no blockrefs to count.
1178  *
1179  * NOTE: live_count may already have some counts accumulated due to
1180  *       creation and deletion and could even be initially negative.
1181  */
1182 void
1183 hammer2_chain_countbrefs(hammer2_chain_t *chain,
1184                          hammer2_blockref_t *base, int count)
1185 {
1186         hammer2_chain_core_t *core = chain->core;
1187
1188         KKASSERT((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0);
1189
1190         spin_lock(&core->cst.spin);
1191         if ((core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0) {
1192                 if (base) {
1193                         while (--count >= 0) {
1194                                 if (base[count].type)
1195                                         break;
1196                         }
1197                         core->live_zero = count + 1;
1198                         while (count >= 0) {
1199                                 if (base[count].type)
1200                                         atomic_add_int(&core->live_count, 1);
1201                                 --count;
1202                         }
1203                 } else {
1204                         core->live_zero = 0;
1205                 }
1206                 /* else do not modify live_count */
1207                 atomic_set_int(&core->flags, HAMMER2_CORE_COUNTEDBREFS);
1208         }
1209         spin_unlock(&core->cst.spin);
1210 }
1211
1212 /*
1213  * Resize the chain's physical storage allocation in-place.  This may
1214  * replace the passed-in chain with a new chain.
1215  *
1216  * Chains can be resized smaller without reallocating the storage.
1217  * Resizing larger will reallocate the storage.
1218  *
1219  * Must be passed an exclusively locked parent and chain, returns a new
1220  * exclusively locked chain at the same index and unlocks the old chain.
1221  * Flushes the buffer if necessary.
1222  *
1223  * This function is mostly used with DATA blocks locked RESOLVE_NEVER in order
1224  * to avoid instantiating a device buffer that conflicts with the vnode
1225  * data buffer.  That is, the passed-in bp is a logical buffer, whereas
1226  * any chain-oriented bp would be a device buffer.
1227  *
1228  * XXX return error if cannot resize.
1229  */
1230 void
1231 hammer2_chain_resize(hammer2_trans_t *trans, hammer2_inode_t *ip,
1232                      hammer2_chain_t *parent, hammer2_chain_t **chainp,
1233                      int nradix, int flags)
1234 {
1235         hammer2_mount_t *hmp;
1236         hammer2_chain_t *chain;
1237         size_t obytes;
1238         size_t nbytes;
1239
1240         chain = *chainp;
1241         hmp = chain->hmp;
1242
1243         /*
1244          * Only data and indirect blocks can be resized for now.
1245          * (The volu root, inodes, and freemap elements use a fixed size).
1246          */
1247         KKASSERT(chain != &hmp->vchain);
1248         KKASSERT(chain->bref.type == HAMMER2_BREF_TYPE_DATA ||
1249                  chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT);
1250
1251         /*
1252          * Nothing to do if the element is already the proper size
1253          */
1254         obytes = chain->bytes;
1255         nbytes = 1U << nradix;
1256         if (obytes == nbytes)
1257                 return;
1258
1259         /*
1260          * Delete the old chain and duplicate it at the same (parent, index),
1261          * returning a new chain.  This allows the old chain to still be
1262          * used by the flush code.  The new chain will be returned in a
1263          * modified state.
1264          *
1265          * The parent does not have to be locked for the delete/duplicate call,
1266          * but is in this particular code path.
1267          *
1268          * NOTE: If we are not crossing a synchronization point the
1269          *       duplication code will simply reuse the existing chain
1270          *       structure.
1271          */
1272         hammer2_chain_delete_duplicate(trans, &chain, 0);
1273
1274         /*
1275          * Relocate the block, even if making it smaller (because different
1276          * block sizes may be in different regions).
1277          *
1278          * (data blocks only, we aren't copying the storage here).
1279          */
1280         hammer2_freemap_alloc(trans, chain, nbytes);
1281         chain->bytes = nbytes;
1282         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1283         /*ip->delta_dcount += (ssize_t)(nbytes - obytes);*/ /* XXX atomic */
1284
1285         /*
1286          * For now just support it on DATA chains (and not on indirect
1287          * blocks).
1288          */
1289         KKASSERT(chain->dio == NULL);
1290
1291         *chainp = chain;
1292 }
1293
1294 /*
1295  * Set a chain modified, making it read-write and duplicating it if necessary.
1296  * This function will assign a new physical block to the chain if necessary
1297  *
1298  * Duplication of already-modified chains is possible when the modification
1299  * crosses a flush synchronization boundary.
1300  *
1301  * Non-data blocks - The chain should be locked to at least the RESOLVE_MAYBE
1302  *                   level or the COW operation will not work.
1303  *
1304  * Data blocks     - The chain is usually locked RESOLVE_NEVER so as not to
1305  *                   run the data through the device buffers.
1306  *
1307  * This function may return a different chain than was passed, in which case
1308  * the old chain will be unlocked and the new chain will be locked.
1309  *
1310  * ip->chain may be adjusted by hammer2_chain_modify_ip().
1311  */
1312 hammer2_inode_data_t *
1313 hammer2_chain_modify_ip(hammer2_trans_t *trans, hammer2_inode_t *ip,
1314                         hammer2_chain_t **chainp, int flags)
1315 {
1316         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1317         hammer2_chain_modify(trans, chainp, flags);
1318         if (ip->chain != *chainp)
1319                 hammer2_inode_repoint(ip, NULL, *chainp);
1320         if (ip->vp)
1321                 vsetisdirty(ip->vp);
1322         return(&ip->chain->data->ipdata);
1323 }
1324
1325 void
1326 hammer2_chain_modify(hammer2_trans_t *trans, hammer2_chain_t **chainp,
1327                      int flags)
1328 {
1329         hammer2_mount_t *hmp;
1330         hammer2_chain_t *chain;
1331         hammer2_io_t *dio;
1332         int error;
1333         int wasinitial;
1334         char *bdata;
1335
1336         chain = *chainp;
1337         hmp = chain->hmp;
1338
1339         KKASSERT(chain->bref.mirror_tid != trans->sync_tid ||
1340                  (chain->flags & HAMMER2_CHAIN_MODIFIED));
1341
1342         /*
1343          * data is not optional for freemap chains (we must always be sure
1344          * to copy the data on COW storage allocations).
1345          */
1346         if (chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
1347             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
1348                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) ||
1349                          (flags & HAMMER2_MODIFY_OPTDATA) == 0);
1350         }
1351
1352         /*
1353          * Determine if a delete-duplicate is needed.
1354          *
1355          * (a) Modify_tid is part of a prior flush
1356          * (b) Transaction is concurrent with a flush (has higher tid)
1357          * (c) and chain is not in the initial state (freshly created)
1358          * (d) and caller didn't request an in-place modification.
1359          *
1360          * The freemap and volume header special chains are never D-Dd.
1361          */
1362         if (chain->modify_tid != trans->sync_tid &&        /* cross boundary */
1363             (flags & HAMMER2_MODIFY_INPLACE) == 0) {       /* from d-d */
1364                 if (chain != &hmp->fchain && chain != &hmp->vchain) {
1365                         KKASSERT((flags & HAMMER2_MODIFY_ASSERTNOCOPY) == 0);
1366                         hammer2_chain_delete_duplicate(trans, chainp, 0);
1367                         chain = *chainp;
1368                 }
1369         }
1370
1371         /*
1372          * Data must be resolved if already assigned unless explicitly
1373          * flagged otherwise.
1374          */
1375         if (chain->data == NULL && (flags & HAMMER2_MODIFY_OPTDATA) == 0 &&
1376             (chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX)) {
1377                 hammer2_chain_lock(chain, HAMMER2_RESOLVE_ALWAYS);
1378                 hammer2_chain_unlock(chain);
1379         }
1380
1381         /*
1382          * Otherwise do initial-chain handling.  Set MODIFIED to indicate
1383          * that the chain has been modified.  Set FLUSH_CREATE to flush
1384          * the new blockref (the D-D set FLUSH_DELETE on the old chain to
1385          * delete the old blockref).
1386          */
1387         if ((chain->flags & HAMMER2_CHAIN_MODIFIED) == 0) {
1388                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_MODIFIED);
1389                 hammer2_chain_ref(chain);
1390                 hammer2_chain_memory_inc(chain->pmp);
1391         }
1392         if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
1393                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
1394                 hammer2_chain_ref(chain);
1395         }
1396
1397         /*
1398          * The modification or re-modification requires an allocation and
1399          * possible COW.
1400          *
1401          * We normally always allocate new storage here.  If storage exists
1402          * and MODIFY_NOREALLOC is passed in, we do not allocate new storage.
1403          */
1404         if (chain != &hmp->vchain && chain != &hmp->fchain) {
1405                 if ((chain->bref.data_off & ~HAMMER2_OFF_MASK_RADIX) == 0 ||
1406                      ((flags & HAMMER2_MODIFY_NOREALLOC) == 0 &&
1407                       chain->modify_tid != trans->sync_tid)
1408                 ) {
1409                         hammer2_freemap_alloc(trans, chain, chain->bytes);
1410                         /* XXX failed allocation */
1411                 } else if (chain->flags & HAMMER2_CHAIN_FORCECOW) {
1412                         hammer2_freemap_alloc(trans, chain, chain->bytes);
1413                         /* XXX failed allocation */
1414                 }
1415                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_FORCECOW);
1416         }
1417
1418         /*
1419          * Update modify_tid.  XXX special-case vchain/fchain because they
1420          * are always modified in-place.  Otherwise the chain being modified
1421          * must not be part of a future transaction.
1422          */
1423         if (chain == &hmp->vchain || chain == &hmp->fchain) {
1424                 if (chain->modify_tid <= trans->sync_tid)
1425                         chain->modify_tid = trans->sync_tid;
1426         } else {
1427                 KKASSERT(chain->modify_tid <= trans->sync_tid);
1428                 chain->modify_tid = trans->sync_tid;
1429         }
1430
1431         if ((flags & HAMMER2_MODIFY_NO_MODIFY_TID) == 0)
1432                 chain->bref.modify_tid = trans->sync_tid;
1433
1434         /*
1435          * Do not COW BREF_TYPE_DATA when OPTDATA is set.  This is because
1436          * data modifications are done via the logical buffer cache so COWing
1437          * it here would result in unnecessary extra copies (and possibly extra
1438          * block reallocations).  The INITIAL flag remains unchanged in this
1439          * situation.
1440          *
1441          * (This is a bit of a hack).
1442          */
1443         if (chain->bref.type == HAMMER2_BREF_TYPE_DATA &&
1444             (flags & HAMMER2_MODIFY_OPTDATA)) {
1445                 goto skip2;
1446         }
1447
1448         /*
1449          * Clearing the INITIAL flag (for indirect blocks) indicates that
1450          * we've processed the uninitialized storage allocation.
1451          *
1452          * If this flag is already clear we are likely in a copy-on-write
1453          * situation but we have to be sure NOT to bzero the storage if
1454          * no data is present.
1455          */
1456         if (chain->flags & HAMMER2_CHAIN_INITIAL) {
1457                 atomic_clear_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
1458                 wasinitial = 1;
1459         } else {
1460                 wasinitial = 0;
1461         }
1462
1463         /*
1464          * Instantiate data buffer and possibly execute COW operation
1465          */
1466         switch(chain->bref.type) {
1467         case HAMMER2_BREF_TYPE_VOLUME:
1468         case HAMMER2_BREF_TYPE_FREEMAP:
1469                 /*
1470                  * The data is embedded, no copy-on-write operation is
1471                  * needed.
1472                  */
1473                 KKASSERT(chain->dio == NULL);
1474                 break;
1475         case HAMMER2_BREF_TYPE_INODE:
1476         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
1477         case HAMMER2_BREF_TYPE_DATA:
1478         case HAMMER2_BREF_TYPE_INDIRECT:
1479         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1480                 /*
1481                  * Perform the copy-on-write operation
1482                  *
1483                  * zero-fill or copy-on-write depending on whether
1484                  * chain->data exists or not and set the dirty state for
1485                  * the new buffer.  hammer2_io_new() will handle the
1486                  * zero-fill.
1487                  */
1488                 KKASSERT(chain != &hmp->vchain && chain != &hmp->fchain);
1489
1490                 if (wasinitial) {
1491                         error = hammer2_io_new(hmp, chain->bref.data_off,
1492                                                chain->bytes, &dio);
1493                 } else {
1494                         error = hammer2_io_bread(hmp, chain->bref.data_off,
1495                                                  chain->bytes, &dio);
1496                 }
1497                 adjreadcounter(&chain->bref, chain->bytes);
1498                 KKASSERT(error == 0);
1499
1500                 bdata = hammer2_io_data(dio, chain->bref.data_off);
1501
1502                 if (chain->data) {
1503                         KKASSERT(chain->dio != NULL);
1504                         if (chain->data != (void *)bdata) {
1505                                 bcopy(chain->data, bdata, chain->bytes);
1506                         }
1507                 } else if (wasinitial == 0) {
1508                         /*
1509                          * We have a problem.  We were asked to COW but
1510                          * we don't have any data to COW with!
1511                          */
1512                         panic("hammer2_chain_modify: having a COW %p\n",
1513                               chain);
1514                 }
1515
1516                 /*
1517                  * Retire the old buffer, replace with the new
1518                  */
1519                 if (chain->dio)
1520                         hammer2_io_brelse(&chain->dio);
1521                 chain->data = (void *)bdata;
1522                 chain->dio = dio;
1523                 hammer2_io_setdirty(dio);       /* modified by bcopy above */
1524                 break;
1525         default:
1526                 panic("hammer2_chain_modify: illegal non-embedded type %d",
1527                       chain->bref.type);
1528                 break;
1529
1530         }
1531 skip2:
1532         hammer2_chain_setsubmod(trans, chain);
1533 }
1534
1535 /*
1536  * Mark the volume as having been modified.  This short-cut version
1537  * does not have to lock the volume's chain, which allows the ioctl
1538  * code to make adjustments to connections without deadlocking.  XXX
1539  *
1540  * No ref is made on vchain when flagging it MODIFIED.
1541  */
1542 void
1543 hammer2_modify_volume(hammer2_mount_t *hmp)
1544 {
1545         hammer2_voldata_lock(hmp);
1546         hammer2_voldata_unlock(hmp, 1);
1547 }
1548
1549 /*
1550  * This function returns the chain at the nearest key within the specified
1551  * range with the highest delete_tid.  The core spinlock must be held on
1552  * call and the returned chain will be referenced but not locked.
1553  *
1554  * The returned chain may or may not be in a deleted state.  Note that
1555  * live chains have a delete_tid = MAX_TID.
1556  *
1557  * This function will recurse through chain->rbtree as necessary and will
1558  * return a *key_nextp suitable for iteration.  *key_nextp is only set if
1559  * the iteration value is less than the current value of *key_nextp.
1560  *
1561  * The caller should use (*key_nextp) to calculate the actual range of
1562  * the returned element, which will be (key_beg to *key_nextp - 1), because
1563  * there might be another element which is superior to the returned element
1564  * and overlaps it.
1565  *
1566  * (*key_nextp) can be passed as key_beg in an iteration only while non-NULL
1567  * chains continue to be returned.  On EOF (*key_nextp) may overflow since
1568  * it will wind up being (key_end + 1).
1569  */
1570 struct hammer2_chain_find_info {
1571         hammer2_chain_t         *best;
1572         hammer2_key_t           key_beg;
1573         hammer2_key_t           key_end;
1574         hammer2_key_t           key_next;
1575 };
1576
1577 static int hammer2_chain_find_cmp(hammer2_chain_t *child, void *data);
1578 static int hammer2_chain_find_callback(hammer2_chain_t *child, void *data);
1579
1580 static
1581 hammer2_chain_t *
1582 hammer2_chain_find(hammer2_chain_t *parent, hammer2_key_t *key_nextp,
1583                           hammer2_key_t key_beg, hammer2_key_t key_end)
1584 {
1585         struct hammer2_chain_find_info info;
1586
1587         info.best = NULL;
1588         info.key_beg = key_beg;
1589         info.key_end = key_end;
1590         info.key_next = *key_nextp;
1591
1592         KKASSERT(parent->core->good == 0x1234);
1593         RB_SCAN(hammer2_chain_tree, &parent->core->rbtree,
1594                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1595                 &info);
1596         *key_nextp = info.key_next;
1597 #if 0
1598         kprintf("chain_find %p %016jx:%016jx next=%016jx\n",
1599                 parent, key_beg, key_end, *key_nextp);
1600 #endif
1601
1602         return (info.best);
1603 }
1604
1605 /*
1606  * Find a deleted chain covering a block table entry.  Be careful to deal
1607  * with the race condition where the block table has been updated but the
1608  * chain has not yet been removed from dbtree (due to multiple parents having
1609  * to be updated).
1610  */
1611 static
1612 hammer2_chain_t *
1613 hammer2_chain_find_deleted(hammer2_chain_t *parent,
1614                           hammer2_key_t key_beg, hammer2_key_t key_end)
1615 {
1616         struct hammer2_chain_find_info info;
1617         hammer2_chain_t *child;
1618
1619         info.best = NULL;
1620         info.key_beg = key_beg;
1621         info.key_end = key_end;
1622         info.key_next = 0;
1623
1624         KKASSERT(parent->core->good == 0x1234);
1625         RB_SCAN(hammer2_chain_tree, &parent->core->dbtree,
1626                 hammer2_chain_find_cmp, hammer2_chain_find_callback,
1627                 &info);
1628         if ((child = info.best) != NULL) {
1629                 if (child->delete_tid <= parent->update_lo)
1630                         child = NULL;
1631         }
1632         return child;
1633 }
1634
1635 static
1636 int
1637 hammer2_chain_find_cmp(hammer2_chain_t *child, void *data)
1638 {
1639         struct hammer2_chain_find_info *info = data;
1640         hammer2_key_t child_beg;
1641         hammer2_key_t child_end;
1642
1643         child_beg = child->bref.key;
1644         child_end = child_beg + ((hammer2_key_t)1 << child->bref.keybits) - 1;
1645
1646         if (child_end < info->key_beg)
1647                 return(-1);
1648         if (child_beg > info->key_end)
1649                 return(1);
1650         return(0);
1651 }
1652
1653 static
1654 int
1655 hammer2_chain_find_callback(hammer2_chain_t *child, void *data)
1656 {
1657         struct hammer2_chain_find_info *info = data;
1658         hammer2_chain_t *best;
1659         hammer2_key_t child_end;
1660
1661         /*
1662          * WARNING! Do not discard DUPLICATED chains, it is possible that
1663          *          we are catching an insertion half-way done.  If a
1664          *          duplicated chain turns out to be the best choice the
1665          *          caller will re-check its flags after locking it.
1666          *
1667          * WARNING! Layerq is scanned forwards, exact matches should keep
1668          *          the existing info->best.
1669          */
1670         if ((best = info->best) == NULL) {
1671                 /*
1672                  * No previous best.  Assign best
1673                  */
1674                 info->best = child;
1675         } else if (best->bref.key <= info->key_beg &&
1676                    child->bref.key <= info->key_beg) {
1677                 /*
1678                  * If our current best is flush with key_beg and child is
1679                  * also flush with key_beg choose based on delete_tid.
1680                  *
1681                  * key_next will automatically be limited to the smaller of
1682                  * the two end-points.
1683                  */
1684                 if (child->delete_tid > best->delete_tid)
1685                         info->best = child;
1686         } else if (child->bref.key < best->bref.key) {
1687                 /*
1688                  * Child has a nearer key and best is not flush with key_beg.
1689                  * Truncate key_next to the old best key iff it had a better
1690                  * delete_tid.
1691                  */
1692                 info->best = child;
1693                 if (best->delete_tid >= child->delete_tid &&
1694                     (info->key_next > best->bref.key || info->key_next == 0))
1695                         info->key_next = best->bref.key;
1696         } else if (child->bref.key == best->bref.key) {
1697                 /*
1698                  * If our current best is flush with the child then choose
1699                  * based on delete_tid.
1700                  *
1701                  * key_next will automatically be limited to the smaller of
1702                  * the two end-points.
1703                  */
1704                 if (child->delete_tid > best->delete_tid)
1705                         info->best = child;
1706         } else {
1707                 /*
1708                  * Keep the current best but truncate key_next to the child's
1709                  * base iff the child has a higher delete_tid.
1710                  *
1711                  * key_next will also automatically be limited to the smaller
1712                  * of the two end-points (probably not necessary for this case
1713                  * but we do it anyway).
1714                  */
1715                 if (child->delete_tid >= best->delete_tid &&
1716                     (info->key_next > child->bref.key || info->key_next == 0))
1717                         info->key_next = child->bref.key;
1718         }
1719
1720         /*
1721          * Always truncate key_next based on child's end-of-range.
1722          */
1723         child_end = child->bref.key + ((hammer2_key_t)1 << child->bref.keybits);
1724         if (child_end && (info->key_next > child_end || info->key_next == 0))
1725                 info->key_next = child_end;
1726
1727         return(0);
1728 }
1729
1730 /*
1731  * Retrieve the specified chain from a media blockref, creating the
1732  * in-memory chain structure which reflects it.  modify_tid will be
1733  * left 0 which forces any modifications to issue a delete-duplicate.
1734  *
1735  * To handle insertion races pass the INSERT_RACE flag along with the
1736  * generation number of the core.  NULL will be returned if the generation
1737  * number changes before we have a chance to insert the chain.  Insert
1738  * races can occur because the parent might be held shared.
1739  *
1740  * Caller must hold the parent locked shared or exclusive since we may
1741  * need the parent's bref array to find our block.
1742  */
1743 hammer2_chain_t *
1744 hammer2_chain_get(hammer2_chain_t *parent, int generation,
1745                   hammer2_blockref_t *bref)
1746 {
1747         hammer2_mount_t *hmp = parent->hmp;
1748         hammer2_chain_core_t *above = parent->core;
1749         hammer2_chain_t *chain;
1750         int error;
1751
1752         /*
1753          * Allocate a chain structure representing the existing media
1754          * entry.  Resulting chain has one ref and is not locked.
1755          */
1756         chain = hammer2_chain_alloc(hmp, parent->pmp, NULL, bref);
1757         hammer2_chain_core_alloc(NULL, chain, NULL);
1758         /* ref'd chain returned */
1759
1760         /*
1761          * Set modify_tid and update_lo to the chain's synchronization
1762          * point from the media.
1763          */
1764         chain->modify_tid = chain->bref.mirror_tid;
1765         chain->update_lo = chain->bref.mirror_tid;
1766         atomic_set_int(&chain->flags, HAMMER2_CHAIN_BMAPPED);
1767
1768         /*
1769          * Link the chain into its parent.  A spinlock is required to safely
1770          * access the RBTREE, and it is possible to collide with another
1771          * hammer2_chain_get() operation because the caller might only hold
1772          * a shared lock on the parent.
1773          */
1774         KKASSERT(parent->refs > 0);
1775         error = hammer2_chain_insert(above, NULL, chain,
1776                                      HAMMER2_CHAIN_INSERT_SPIN |
1777                                      HAMMER2_CHAIN_INSERT_RACE,
1778                                      generation);
1779         if (error) {
1780                 KKASSERT((chain->flags & (HAMMER2_CHAIN_ONRBTREE |
1781                                           HAMMER2_CHAIN_ONDBTREE |
1782                                           HAMMER2_CHAIN_ONDBQ)) == 0);
1783                 kprintf("chain %p get race\n", chain);
1784                 hammer2_chain_drop(chain);
1785                 chain = NULL;
1786         } else {
1787                 KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
1788         }
1789
1790         /*
1791          * Return our new chain referenced but not locked, or NULL if
1792          * a race occurred.
1793          */
1794         return (chain);
1795 }
1796
1797 /*
1798  * Lookup initialization/completion API
1799  */
1800 hammer2_chain_t *
1801 hammer2_chain_lookup_init(hammer2_chain_t *parent, int flags)
1802 {
1803         if (flags & HAMMER2_LOOKUP_SHARED) {
1804                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS |
1805                                            HAMMER2_RESOLVE_SHARED);
1806         } else {
1807                 hammer2_chain_lock(parent, HAMMER2_RESOLVE_ALWAYS);
1808         }
1809         return (parent);
1810 }
1811
1812 void
1813 hammer2_chain_lookup_done(hammer2_chain_t *parent)
1814 {
1815         if (parent)
1816                 hammer2_chain_unlock(parent);
1817 }
1818
1819 static
1820 hammer2_chain_t *
1821 hammer2_chain_getparent(hammer2_chain_t **parentp, int how)
1822 {
1823         hammer2_chain_t *oparent;
1824         hammer2_chain_t *bparent;
1825         hammer2_chain_t *nparent;
1826         hammer2_chain_core_t *above;
1827
1828         oparent = *parentp;
1829         above = oparent->above;
1830
1831         spin_lock(&above->cst.spin);
1832         bparent = TAILQ_FIRST(&above->ownerq);
1833         hammer2_chain_ref(bparent);
1834
1835         /*
1836          * Be careful of order, oparent must be unlocked before nparent
1837          * is locked below to avoid a deadlock.  We might as well delay its
1838          * unlocking until we conveniently no longer have the spinlock (instead
1839          * of cycling the spinlock).
1840          *
1841          * Theoretically our ref on bparent should prevent elements of the
1842          * following chain from going away and prevent above from going away,
1843          * but we still need the spinlock to safely scan the list.
1844          */
1845         for (;;) {
1846                 nparent = bparent;
1847                 while (nparent->flags & HAMMER2_CHAIN_DUPLICATED)
1848                         nparent = TAILQ_NEXT(nparent, core_entry);
1849                 hammer2_chain_ref(nparent);
1850                 spin_unlock(&above->cst.spin);
1851
1852                 if (oparent) {
1853                         hammer2_chain_unlock(oparent);
1854                         oparent = NULL;
1855                 }
1856                 hammer2_chain_lock(nparent, how | HAMMER2_RESOLVE_NOREF);
1857                 hammer2_chain_drop(bparent);
1858
1859                 /*
1860                  * We might have raced a delete-duplicate.
1861                  */
1862                 if ((nparent->flags & HAMMER2_CHAIN_DUPLICATED) == 0)
1863                         break;
1864                 bparent = nparent;
1865                 hammer2_chain_ref(bparent);
1866                 hammer2_chain_unlock(nparent);
1867                 spin_lock(&above->cst.spin);
1868                 /* retry */
1869         }
1870         *parentp = nparent;
1871
1872         return (nparent);
1873 }
1874
1875 /*
1876  * Locate the first chain whos key range overlaps (key_beg, key_end) inclusive.
1877  * (*parentp) typically points to an inode but can also point to a related
1878  * indirect block and this function will recurse upwards and find the inode
1879  * again.
1880  *
1881  * (*parentp) must be exclusively locked and referenced and can be an inode
1882  * or an existing indirect block within the inode.
1883  *
1884  * On return (*parentp) will be modified to point at the deepest parent chain
1885  * element encountered during the search, as a helper for an insertion or
1886  * deletion.   The new (*parentp) will be locked and referenced and the old
1887  * will be unlocked and dereferenced (no change if they are both the same).
1888  *
1889  * The matching chain will be returned exclusively locked.  If NOLOCK is
1890  * requested the chain will be returned only referenced.
1891  *
1892  * NULL is returned if no match was found, but (*parentp) will still
1893  * potentially be adjusted.
1894  *
1895  * On return (*key_nextp) will point to an iterative value for key_beg.
1896  * (If NULL is returned (*key_nextp) is set to key_end).
1897  *
1898  * This function will also recurse up the chain if the key is not within the
1899  * current parent's range.  (*parentp) can never be set to NULL.  An iteration
1900  * can simply allow (*parentp) to float inside the loop.
1901  *
1902  * NOTE!  chain->data is not always resolved.  By default it will not be
1903  *        resolved for BREF_TYPE_DATA, FREEMAP_NODE, or FREEMAP_LEAF.  Use
1904  *        HAMMER2_LOOKUP_ALWAYS to force resolution (but be careful w/
1905  *        BREF_TYPE_DATA as the device buffer can alias the logical file
1906  *        buffer).
1907  */
1908 hammer2_chain_t *
1909 hammer2_chain_lookup(hammer2_chain_t **parentp, hammer2_key_t *key_nextp,
1910                      hammer2_key_t key_beg, hammer2_key_t key_end,
1911                      int *cache_indexp, int flags)
1912 {
1913         hammer2_mount_t *hmp;
1914         hammer2_chain_t *parent;
1915         hammer2_chain_t *chain;
1916         hammer2_blockref_t *base;
1917         hammer2_blockref_t *bref;
1918         hammer2_blockref_t bcopy;
1919         hammer2_key_t scan_beg;
1920         hammer2_key_t scan_end;
1921         hammer2_chain_core_t *above;
1922         int count = 0;
1923         int how_always = HAMMER2_RESOLVE_ALWAYS;
1924         int how_maybe = HAMMER2_RESOLVE_MAYBE;
1925         int how;
1926         int generation;
1927         int maxloops = 300000;
1928         int wasdup;
1929
1930         if (flags & HAMMER2_LOOKUP_ALWAYS) {
1931                 how_maybe = how_always;
1932                 how = HAMMER2_RESOLVE_ALWAYS;
1933         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
1934                 how = HAMMER2_RESOLVE_NEVER;
1935         } else {
1936                 how = HAMMER2_RESOLVE_MAYBE;
1937         }
1938         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
1939                 how_maybe |= HAMMER2_RESOLVE_SHARED;
1940                 how_always |= HAMMER2_RESOLVE_SHARED;
1941                 how |= HAMMER2_RESOLVE_SHARED;
1942         }
1943
1944         /*
1945          * Recurse (*parentp) upward if necessary until the parent completely
1946          * encloses the key range or we hit the inode.
1947          *
1948          * This function handles races against the flusher doing a delete-
1949          * duplicate above us and re-homes the parent to the duplicate in
1950          * that case, otherwise we'd wind up recursing down a stale chain.
1951          */
1952         parent = *parentp;
1953         hmp = parent->hmp;
1954
1955         while (parent->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
1956                parent->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
1957                 scan_beg = parent->bref.key;
1958                 scan_end = scan_beg +
1959                            ((hammer2_key_t)1 << parent->bref.keybits) - 1;
1960                 if (key_beg >= scan_beg && key_end <= scan_end)
1961                         break;
1962                 parent = hammer2_chain_getparent(parentp, how_maybe);
1963         }
1964
1965 again:
1966         if (--maxloops == 0)
1967                 panic("hammer2_chain_lookup: maxloops");
1968         /*
1969          * Locate the blockref array.  Currently we do a fully associative
1970          * search through the array.
1971          */
1972         switch(parent->bref.type) {
1973         case HAMMER2_BREF_TYPE_INODE:
1974                 /*
1975                  * Special shortcut for embedded data returns the inode
1976                  * itself.  Callers must detect this condition and access
1977                  * the embedded data (the strategy code does this for us).
1978                  *
1979                  * This is only applicable to regular files and softlinks.
1980                  */
1981                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA) {
1982                         if (flags & HAMMER2_LOOKUP_NOLOCK)
1983                                 hammer2_chain_ref(parent);
1984                         else
1985                                 hammer2_chain_lock(parent, how_always);
1986                         *key_nextp = key_end + 1;
1987                         return (parent);
1988                 }
1989                 base = &parent->data->ipdata.u.blockset.blockref[0];
1990                 count = HAMMER2_SET_COUNT;
1991                 break;
1992         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
1993         case HAMMER2_BREF_TYPE_INDIRECT:
1994                 /*
1995                  * Handle MATCHIND on the parent
1996                  */
1997                 if (flags & HAMMER2_LOOKUP_MATCHIND) {
1998                         scan_beg = parent->bref.key;
1999                         scan_end = scan_beg +
2000                                ((hammer2_key_t)1 << parent->bref.keybits) - 1;
2001                         if (key_beg == scan_beg && key_end == scan_end) {
2002                                 chain = parent;
2003                                 hammer2_chain_lock(chain, how_maybe);
2004                                 *key_nextp = scan_end + 1;
2005                                 goto done;
2006                         }
2007                 }
2008                 /*
2009                  * Optimize indirect blocks in the INITIAL state to avoid
2010                  * I/O.
2011                  */
2012                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2013                         base = NULL;
2014                 } else {
2015                         if (parent->data == NULL)
2016                                 panic("parent->data is NULL");
2017                         base = &parent->data->npdata[0];
2018                 }
2019                 count = parent->bytes / sizeof(hammer2_blockref_t);
2020                 break;
2021         case HAMMER2_BREF_TYPE_VOLUME:
2022                 base = &hmp->voldata.sroot_blockset.blockref[0];
2023                 count = HAMMER2_SET_COUNT;
2024                 break;
2025         case HAMMER2_BREF_TYPE_FREEMAP:
2026                 base = &hmp->voldata.freemap_blockset.blockref[0];
2027                 count = HAMMER2_SET_COUNT;
2028                 break;
2029         default:
2030                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2031                       parent->bref.type);
2032                 base = NULL;    /* safety */
2033                 count = 0;      /* safety */
2034         }
2035
2036         /*
2037          * Merged scan to find next candidate.
2038          *
2039          * hammer2_base_*() functions require the above->live_* fields
2040          * to be synchronized.
2041          *
2042          * We need to hold the spinlock to access the block array and RB tree
2043          * and to interlock chain creation.
2044          */
2045         above = parent->core;
2046         if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2047                 hammer2_chain_countbrefs(parent, base, count);
2048
2049         /*
2050          * Combined search
2051          */
2052         spin_lock(&above->cst.spin);
2053         chain = hammer2_combined_find(parent, base, count,
2054                                       cache_indexp, key_nextp,
2055                                       key_beg, key_end,
2056                                       &bref);
2057         generation = above->generation;
2058
2059         /*
2060          * Exhausted parent chain, iterate.
2061          */
2062         if (bref == NULL) {
2063                 spin_unlock(&above->cst.spin);
2064                 if (key_beg == key_end) /* short cut single-key case */
2065                         return (NULL);
2066                 return (hammer2_chain_next(parentp, NULL, key_nextp,
2067                                            key_beg, key_end,
2068                                            cache_indexp, flags));
2069         }
2070
2071         /*
2072          * Selected from blockref or in-memory chain.
2073          */
2074         if (chain == NULL) {
2075                 bcopy = *bref;
2076                 spin_unlock(&above->cst.spin);
2077                 chain = hammer2_chain_get(parent, generation,
2078                                           &bcopy);
2079                 if (chain == NULL) {
2080                         kprintf("retry lookup parent %p keys %016jx:%016jx\n",
2081                                 parent, key_beg, key_end);
2082                         goto again;
2083                 }
2084                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2085                         hammer2_chain_drop(chain);
2086                         goto again;
2087                 }
2088                 wasdup = 0;
2089         } else {
2090                 hammer2_chain_ref(chain);
2091                 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2092                 spin_unlock(&above->cst.spin);
2093         }
2094
2095         /*
2096          * chain is referenced but not locked.  We must lock the chain
2097          * to obtain definitive DUPLICATED/DELETED state
2098          */
2099         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2100             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2101                 hammer2_chain_lock(chain, how_maybe | HAMMER2_RESOLVE_NOREF);
2102         } else {
2103                 hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2104         }
2105
2106         /*
2107          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2108          *
2109          * NOTE: Chain's key range is not relevant as there might be
2110          *       one-offs within the range that are not deleted.
2111          *
2112          * NOTE: Lookups can race delete-duplicate because
2113          *       delete-duplicate does not lock the parent's core
2114          *       (they just use the spinlock on the core).  We must
2115          *       check for races by comparing the DUPLICATED flag before
2116          *       releasing the spinlock with the flag after locking the
2117          *       chain.
2118          */
2119         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2120                 hammer2_chain_unlock(chain);
2121                 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2122                         key_beg = *key_nextp;
2123                         if (key_beg == 0 || key_beg > key_end)
2124                                 return(NULL);
2125                 }
2126                 goto again;
2127         }
2128
2129         /*
2130          * If the chain element is an indirect block it becomes the new
2131          * parent and we loop on it.  We must maintain our top-down locks
2132          * to prevent the flusher from interfering (i.e. doing a
2133          * delete-duplicate and leaving us recursing down a deleted chain).
2134          *
2135          * The parent always has to be locked with at least RESOLVE_MAYBE
2136          * so we can access its data.  It might need a fixup if the caller
2137          * passed incompatible flags.  Be careful not to cause a deadlock
2138          * as a data-load requires an exclusive lock.
2139          *
2140          * If HAMMER2_LOOKUP_MATCHIND is set and the indirect block's key
2141          * range is within the requested key range we return the indirect
2142          * block and do NOT loop.  This is usually only used to acquire
2143          * freemap nodes.
2144          */
2145         if (chain->bref.type == HAMMER2_BREF_TYPE_INDIRECT ||
2146             chain->bref.type == HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2147                 hammer2_chain_unlock(parent);
2148                 *parentp = parent = chain;
2149                 goto again;
2150         }
2151 done:
2152         /*
2153          * All done, return the chain
2154          */
2155         return (chain);
2156 }
2157
2158 /*
2159  * After having issued a lookup we can iterate all matching keys.
2160  *
2161  * If chain is non-NULL we continue the iteration from just after it's index.
2162  *
2163  * If chain is NULL we assume the parent was exhausted and continue the
2164  * iteration at the next parent.
2165  *
2166  * parent must be locked on entry and remains locked throughout.  chain's
2167  * lock status must match flags.  Chain is always at least referenced.
2168  *
2169  * WARNING!  The MATCHIND flag does not apply to this function.
2170  */
2171 hammer2_chain_t *
2172 hammer2_chain_next(hammer2_chain_t **parentp, hammer2_chain_t *chain,
2173                    hammer2_key_t *key_nextp,
2174                    hammer2_key_t key_beg, hammer2_key_t key_end,
2175                    int *cache_indexp, int flags)
2176 {
2177         hammer2_chain_t *parent;
2178         int how_maybe;
2179
2180         /*
2181          * Calculate locking flags for upward recursion.
2182          */
2183         how_maybe = HAMMER2_RESOLVE_MAYBE;
2184         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK))
2185                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2186
2187         parent = *parentp;
2188
2189         /*
2190          * Calculate the next index and recalculate the parent if necessary.
2191          */
2192         if (chain) {
2193                 key_beg = chain->bref.key +
2194                           ((hammer2_key_t)1 << chain->bref.keybits);
2195                 if (flags & HAMMER2_LOOKUP_NOLOCK)
2196                         hammer2_chain_drop(chain);
2197                 else
2198                         hammer2_chain_unlock(chain);
2199
2200                 /*
2201                  * Any scan where the lookup returned degenerate data embedded
2202                  * in the inode has an invalid index and must terminate.
2203                  */
2204                 if (chain == parent)
2205                         return(NULL);
2206                 if (key_beg == 0 || key_beg > key_end)
2207                         return(NULL);
2208                 chain = NULL;
2209         } else if (parent->bref.type != HAMMER2_BREF_TYPE_INDIRECT &&
2210                    parent->bref.type != HAMMER2_BREF_TYPE_FREEMAP_NODE) {
2211                 /*
2212                  * We reached the end of the iteration.
2213                  */
2214                 return (NULL);
2215         } else {
2216                 /*
2217                  * Continue iteration with next parent unless the current
2218                  * parent covers the range.
2219                  */
2220                 key_beg = parent->bref.key +
2221                           ((hammer2_key_t)1 << parent->bref.keybits);
2222                 if (key_beg == 0 || key_beg > key_end)
2223                         return (NULL);
2224                 parent = hammer2_chain_getparent(parentp, how_maybe);
2225         }
2226
2227         /*
2228          * And execute
2229          */
2230         return (hammer2_chain_lookup(parentp, key_nextp,
2231                                      key_beg, key_end,
2232                                      cache_indexp, flags));
2233 }
2234
2235 /*
2236  * The raw scan function is similar to lookup/next but does not seek to a key.
2237  * Blockrefs are iterated via first_chain = (parent, NULL) and
2238  * next_chain = (parent, chain).
2239  *
2240  * The passed-in parent must be locked and its data resolved.  The returned
2241  * chain will be locked.  Pass chain == NULL to acquire the first sub-chain
2242  * under parent and then iterate with the passed-in chain (which this
2243  * function will unlock).
2244  */
2245 hammer2_chain_t *
2246 hammer2_chain_scan(hammer2_chain_t *parent, hammer2_chain_t *chain,
2247                    int *cache_indexp, int flags)
2248 {
2249         hammer2_mount_t *hmp;
2250         hammer2_blockref_t *base;
2251         hammer2_blockref_t *bref;
2252         hammer2_blockref_t bcopy;
2253         hammer2_chain_core_t *above;
2254         hammer2_key_t key;
2255         hammer2_key_t next_key;
2256         int count = 0;
2257         int how_always = HAMMER2_RESOLVE_ALWAYS;
2258         int how_maybe = HAMMER2_RESOLVE_MAYBE;
2259         int how;
2260         int generation;
2261         int maxloops = 300000;
2262         int wasdup;
2263
2264         hmp = parent->hmp;
2265
2266         /*
2267          * Scan flags borrowed from lookup
2268          */
2269         if (flags & HAMMER2_LOOKUP_ALWAYS) {
2270                 how_maybe = how_always;
2271                 how = HAMMER2_RESOLVE_ALWAYS;
2272         } else if (flags & (HAMMER2_LOOKUP_NODATA | HAMMER2_LOOKUP_NOLOCK)) {
2273                 how = HAMMER2_RESOLVE_NEVER;
2274         } else {
2275                 how = HAMMER2_RESOLVE_MAYBE;
2276         }
2277         if (flags & (HAMMER2_LOOKUP_SHARED | HAMMER2_LOOKUP_NOLOCK)) {
2278                 how_maybe |= HAMMER2_RESOLVE_SHARED;
2279                 how_always |= HAMMER2_RESOLVE_SHARED;
2280                 how |= HAMMER2_RESOLVE_SHARED;
2281         }
2282
2283         /*
2284          * Calculate key to locate first/next element, unlocking the previous
2285          * element as we go.  Be careful, the key calculation can overflow.
2286          */
2287         if (chain) {
2288                 key = chain->bref.key +
2289                       ((hammer2_key_t)1 << chain->bref.keybits);
2290                 hammer2_chain_unlock(chain);
2291                 chain = NULL;
2292                 if (key == 0)
2293                         goto done;
2294         } else {
2295                 key = 0;
2296         }
2297
2298 again:
2299         if (--maxloops == 0)
2300                 panic("hammer2_chain_scan: maxloops");
2301         /*
2302          * Locate the blockref array.  Currently we do a fully associative
2303          * search through the array.
2304          */
2305         switch(parent->bref.type) {
2306         case HAMMER2_BREF_TYPE_INODE:
2307                 /*
2308                  * An inode with embedded data has no sub-chains.
2309                  */
2310                 if (parent->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
2311                         goto done;
2312                 base = &parent->data->ipdata.u.blockset.blockref[0];
2313                 count = HAMMER2_SET_COUNT;
2314                 break;
2315         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2316         case HAMMER2_BREF_TYPE_INDIRECT:
2317                 /*
2318                  * Optimize indirect blocks in the INITIAL state to avoid
2319                  * I/O.
2320                  */
2321                 if (parent->flags & HAMMER2_CHAIN_INITIAL) {
2322                         base = NULL;
2323                 } else {
2324                         if (parent->data == NULL)
2325                                 panic("parent->data is NULL");
2326                         base = &parent->data->npdata[0];
2327                 }
2328                 count = parent->bytes / sizeof(hammer2_blockref_t);
2329                 break;
2330         case HAMMER2_BREF_TYPE_VOLUME:
2331                 base = &hmp->voldata.sroot_blockset.blockref[0];
2332                 count = HAMMER2_SET_COUNT;
2333                 break;
2334         case HAMMER2_BREF_TYPE_FREEMAP:
2335                 base = &hmp->voldata.freemap_blockset.blockref[0];
2336                 count = HAMMER2_SET_COUNT;
2337                 break;
2338         default:
2339                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
2340                       parent->bref.type);
2341                 base = NULL;    /* safety */
2342                 count = 0;      /* safety */
2343         }
2344
2345         /*
2346          * Merged scan to find next candidate.
2347          *
2348          * hammer2_base_*() functions require the above->live_* fields
2349          * to be synchronized.
2350          *
2351          * We need to hold the spinlock to access the block array and RB tree
2352          * and to interlock chain creation.
2353          */
2354         if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2355                 hammer2_chain_countbrefs(parent, base, count);
2356
2357         above = parent->core;
2358         next_key = 0;
2359         spin_lock(&above->cst.spin);
2360         chain = hammer2_combined_find(parent, base, count,
2361                                       cache_indexp, &next_key,
2362                                       key, HAMMER2_MAX_KEY,
2363                                       &bref);
2364         generation = above->generation;
2365
2366         /*
2367          * Exhausted parent chain, we're done.
2368          */
2369         if (bref == NULL) {
2370                 spin_unlock(&above->cst.spin);
2371                 KKASSERT(chain == NULL);
2372                 goto done;
2373         }
2374
2375         /*
2376          * Selected from blockref or in-memory chain.
2377          */
2378         if (chain == NULL) {
2379                 bcopy = *bref;
2380                 spin_unlock(&above->cst.spin);
2381                 chain = hammer2_chain_get(parent, generation, &bcopy);
2382                 if (chain == NULL) {
2383                         kprintf("retry scan parent %p keys %016jx\n",
2384                                 parent, key);
2385                         goto again;
2386                 }
2387                 if (bcmp(&bcopy, bref, sizeof(bcopy))) {
2388                         hammer2_chain_drop(chain);
2389                         chain = NULL;
2390                         goto again;
2391                 }
2392                 wasdup = 0;
2393         } else {
2394                 hammer2_chain_ref(chain);
2395                 wasdup = ((chain->flags & HAMMER2_CHAIN_DUPLICATED) != 0);
2396                 spin_unlock(&above->cst.spin);
2397         }
2398
2399         /*
2400          * chain is referenced but not locked.  We must lock the chain
2401          * to obtain definitive DUPLICATED/DELETED state
2402          */
2403         hammer2_chain_lock(chain, how | HAMMER2_RESOLVE_NOREF);
2404
2405         /*
2406          * Skip deleted chains (XXX cache 'i' end-of-block-array? XXX)
2407          *
2408          * NOTE: chain's key range is not relevant as there might be
2409          *       one-offs within the range that are not deleted.
2410          *
2411          * NOTE: XXX this could create problems with scans used in
2412          *       situations other than mount-time recovery.
2413          *
2414          * NOTE: Lookups can race delete-duplicate because
2415          *       delete-duplicate does not lock the parent's core
2416          *       (they just use the spinlock on the core).  We must
2417          *       check for races by comparing the DUPLICATED flag before
2418          *       releasing the spinlock with the flag after locking the
2419          *       chain.
2420          */
2421         if (chain->flags & HAMMER2_CHAIN_DELETED) {
2422                 hammer2_chain_unlock(chain);
2423                 chain = NULL;
2424
2425                 if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) == 0 || wasdup) {
2426                         key = next_key;
2427                         if (key == 0)
2428                                 goto done;
2429                 }
2430                 goto again;
2431         }
2432
2433 done:
2434         /*
2435          * All done, return the chain or NULL
2436          */
2437         return (chain);
2438 }
2439
2440 /*
2441  * Create and return a new hammer2 system memory structure of the specified
2442  * key, type and size and insert it under (*parentp).  This is a full
2443  * insertion, based on the supplied key/keybits, and may involve creating
2444  * indirect blocks and moving other chains around via delete/duplicate.
2445  *
2446  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2447  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2448  * FULL.  This typically means that the caller is creating the chain after
2449  * doing a hammer2_chain_lookup().
2450  *
2451  * (*parentp) must be exclusive locked and may be replaced on return
2452  * depending on how much work the function had to do.
2453  *
2454  * (*chainp) usually starts out NULL and returns the newly created chain,
2455  * but if the caller desires the caller may allocate a disconnected chain
2456  * and pass it in instead.  (It is also possible for the caller to use
2457  * chain_duplicate() to create a disconnected chain, manipulate it, then
2458  * pass it into this function to insert it).
2459  *
2460  * This function should NOT be used to insert INDIRECT blocks.  It is
2461  * typically used to create/insert inodes and data blocks.
2462  *
2463  * Caller must pass-in an exclusively locked parent the new chain is to
2464  * be inserted under, and optionally pass-in a disconnected, exclusively
2465  * locked chain to insert (else we create a new chain).  The function will
2466  * adjust (*parentp) as necessary, create or connect the chain, and
2467  * return an exclusively locked chain in *chainp.
2468  */
2469 int
2470 hammer2_chain_create(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2471                      hammer2_chain_t **chainp,
2472                      hammer2_key_t key, int keybits, int type, size_t bytes)
2473 {
2474         hammer2_mount_t *hmp;
2475         hammer2_chain_t *chain;
2476         hammer2_chain_t *parent = *parentp;
2477         hammer2_chain_core_t *above;
2478         hammer2_blockref_t *base;
2479         hammer2_blockref_t dummy;
2480         int allocated = 0;
2481         int error = 0;
2482         int count;
2483         int maxloops = 300000;
2484
2485         above = parent->core;
2486         KKASSERT(ccms_thread_lock_owned(&above->cst));
2487         hmp = parent->hmp;
2488         chain = *chainp;
2489
2490         if (chain == NULL) {
2491                 /*
2492                  * First allocate media space and construct the dummy bref,
2493                  * then allocate the in-memory chain structure.  Set the
2494                  * INITIAL flag for fresh chains which do not have embedded
2495                  * data.
2496                  */
2497                 bzero(&dummy, sizeof(dummy));
2498                 dummy.type = type;
2499                 dummy.key = key;
2500                 dummy.keybits = keybits;
2501                 dummy.data_off = hammer2_getradix(bytes);
2502                 dummy.methods = parent->bref.methods;
2503                 chain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy);
2504                 hammer2_chain_core_alloc(trans, chain, NULL);
2505
2506                 /*
2507                  * Lock the chain manually, chain_lock will load the chain
2508                  * which we do NOT want to do.  (note: chain->refs is set
2509                  * to 1 by chain_alloc() for us, but lockcnt is not).
2510                  */
2511                 chain->lockcnt = 1;
2512                 ccms_thread_lock(&chain->core->cst, CCMS_STATE_EXCLUSIVE);
2513                 allocated = 1;
2514
2515                 /*
2516                  * We do NOT set INITIAL here (yet).  INITIAL is only
2517                  * used for indirect blocks.
2518                  *
2519                  * Recalculate bytes to reflect the actual media block
2520                  * allocation.
2521                  */
2522                 bytes = (hammer2_off_t)1 <<
2523                         (int)(chain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
2524                 chain->bytes = bytes;
2525
2526                 switch(type) {
2527                 case HAMMER2_BREF_TYPE_VOLUME:
2528                 case HAMMER2_BREF_TYPE_FREEMAP:
2529                         panic("hammer2_chain_create: called with volume type");
2530                         break;
2531                 case HAMMER2_BREF_TYPE_INDIRECT:
2532                         panic("hammer2_chain_create: cannot be used to"
2533                               "create indirect block");
2534                         break;
2535                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2536                         panic("hammer2_chain_create: cannot be used to"
2537                               "create freemap root or node");
2538                         break;
2539                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2540                         KKASSERT(bytes == sizeof(chain->data->bmdata));
2541                         /* fall through */
2542                 case HAMMER2_BREF_TYPE_INODE:
2543                 case HAMMER2_BREF_TYPE_DATA:
2544                 default:
2545                         /*
2546                          * leave chain->data NULL, set INITIAL
2547                          */
2548                         KKASSERT(chain->data == NULL);
2549                         atomic_set_int(&chain->flags, HAMMER2_CHAIN_INITIAL);
2550                         break;
2551                 }
2552         } else {
2553                 /*
2554                  * We are reattaching a chain that has been duplicated and
2555                  * left disconnected under a DIFFERENT parent with potentially
2556                  * different key/keybits.
2557                  *
2558                  * The chain must be modified in the current transaction
2559                  * (the duplication code should have done that for us),
2560                  * and it's modify_tid should be greater than the parent's
2561                  * bref.mirror_tid.  This should cause it to be created under
2562                  * the new parent.
2563                  *
2564                  * If deleted in the same transaction, the create/delete TIDs
2565                  * will be the same and effective the chain will not have
2566                  * existed at all from the point of view of the parent.
2567                  *
2568                  * Do NOT mess with the current state of the INITIAL flag.
2569                  */
2570                 KKASSERT(chain->modify_tid == trans->sync_tid);
2571                 chain->bref.key = key;
2572                 chain->bref.keybits = keybits;
2573                 KKASSERT(chain->above == NULL);
2574         }
2575
2576         /*
2577          * Calculate how many entries we have in the blockref array and
2578          * determine if an indirect block is required.
2579          */
2580 again:
2581         if (--maxloops == 0)
2582                 panic("hammer2_chain_create: maxloops");
2583         above = parent->core;
2584
2585         switch(parent->bref.type) {
2586         case HAMMER2_BREF_TYPE_INODE:
2587                 KKASSERT((parent->data->ipdata.op_flags &
2588                           HAMMER2_OPFLAG_DIRECTDATA) == 0);
2589                 KKASSERT(parent->data != NULL);
2590                 base = &parent->data->ipdata.u.blockset.blockref[0];
2591                 count = HAMMER2_SET_COUNT;
2592                 break;
2593         case HAMMER2_BREF_TYPE_INDIRECT:
2594         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
2595                 if (parent->flags & HAMMER2_CHAIN_INITIAL)
2596                         base = NULL;
2597                 else
2598                         base = &parent->data->npdata[0];
2599                 count = parent->bytes / sizeof(hammer2_blockref_t);
2600                 break;
2601         case HAMMER2_BREF_TYPE_VOLUME:
2602                 KKASSERT(parent->data != NULL);
2603                 base = &hmp->voldata.sroot_blockset.blockref[0];
2604                 count = HAMMER2_SET_COUNT;
2605                 break;
2606         case HAMMER2_BREF_TYPE_FREEMAP:
2607                 KKASSERT(parent->data != NULL);
2608                 base = &hmp->voldata.freemap_blockset.blockref[0];
2609                 count = HAMMER2_SET_COUNT;
2610                 break;
2611         default:
2612                 panic("hammer2_chain_create: unrecognized blockref type: %d",
2613                       parent->bref.type);
2614                 base = NULL;
2615                 count = 0;
2616                 break;
2617         }
2618
2619         /*
2620          * Make sure we've counted the brefs
2621          */
2622         if ((parent->core->flags & HAMMER2_CORE_COUNTEDBREFS) == 0)
2623                 hammer2_chain_countbrefs(parent, base, count);
2624
2625         KKASSERT(above->live_count >= 0 && above->live_count <= count);
2626
2627         /*
2628          * If no free blockref could be found we must create an indirect
2629          * block and move a number of blockrefs into it.  With the parent
2630          * locked we can safely lock each child in order to delete+duplicate
2631          * it without causing a deadlock.
2632          *
2633          * This may return the new indirect block or the old parent depending
2634          * on where the key falls.  NULL is returned on error.
2635          */
2636         if (above->live_count == count) {
2637                 hammer2_chain_t *nparent;
2638
2639                 nparent = hammer2_chain_create_indirect(trans, parent,
2640                                                         key, keybits,
2641                                                         type, &error);
2642                 if (nparent == NULL) {
2643                         if (allocated)
2644                                 hammer2_chain_drop(chain);
2645                         chain = NULL;
2646                         goto done;
2647                 }
2648                 if (parent != nparent) {
2649                         hammer2_chain_unlock(parent);
2650                         parent = *parentp = nparent;
2651                 }
2652                 goto again;
2653         }
2654
2655         /*
2656          * Link the chain into its parent.
2657          */
2658         if (chain->above != NULL)
2659                 panic("hammer2: hammer2_chain_create: chain already connected");
2660         KKASSERT(chain->above == NULL);
2661         hammer2_chain_insert(above, NULL, chain,
2662                              HAMMER2_CHAIN_INSERT_SPIN |
2663                              HAMMER2_CHAIN_INSERT_LIVE,
2664                              0);
2665
2666         if (allocated) {
2667                 /*
2668                  * Mark the newly created chain modified.  This will cause
2669                  * FLUSH_CREATE to be set.
2670                  *
2671                  * Device buffers are not instantiated for DATA elements
2672                  * as these are handled by logical buffers.
2673                  *
2674                  * Indirect and freemap node indirect blocks are handled
2675                  * by hammer2_chain_create_indirect() and not by this
2676                  * function.
2677                  *
2678                  * Data for all other bref types is expected to be
2679                  * instantiated (INODE, LEAF).
2680                  */
2681                 switch(chain->bref.type) {
2682                 case HAMMER2_BREF_TYPE_DATA:
2683                 case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
2684                 case HAMMER2_BREF_TYPE_INODE:
2685                         hammer2_chain_modify(trans, &chain,
2686                                              HAMMER2_MODIFY_OPTDATA |
2687                                              HAMMER2_MODIFY_ASSERTNOCOPY);
2688                         break;
2689                 default:
2690                         /*
2691                          * Remaining types are not supported by this function.
2692                          * In particular, INDIRECT and LEAF_NODE types are
2693                          * handled by create_indirect().
2694                          */
2695                         panic("hammer2_chain_create: bad type: %d",
2696                               chain->bref.type);
2697                         /* NOT REACHED */
2698                         break;
2699                 }
2700         } else {
2701                 /*
2702                  * When reconnecting a chain we must set FLUSH_CREATE and
2703                  * setsubmod so the flush recognizes that it must update
2704                  * the bref in the parent.
2705                  */
2706                 if ((chain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
2707                         hammer2_chain_ref(chain);
2708                         atomic_set_int(&chain->flags,
2709                                        HAMMER2_CHAIN_FLUSH_CREATE);
2710                 }
2711         }
2712         hammer2_chain_setsubmod(trans, chain);
2713
2714 done:
2715         *chainp = chain;
2716
2717         return (error);
2718 }
2719
2720 /*
2721  * Replace (*chainp) with a duplicate in-memory chain structure which shares
2722  * the same core and media state as the orignal.  The original *chainp is
2723  * unlocked and the replacement will be returned locked.  The duplicated
2724  * chain is inserted under (*parentp).
2725  *
2726  * THE CALLER MUST HAVE ALREADY PROPERLY SEEKED (*parentp) TO THE INSERTION
2727  * POINT SANS ANY REQUIRED INDIRECT BLOCK CREATIONS DUE TO THE ARRAY BEING
2728  * FULL.  This typically means that the caller is creating the chain after
2729  * doing a hammer2_chain_lookup().
2730  *
2731  * The old chain must be in a DELETED state unless snapshot is non-zero.
2732  *
2733  * The new chain will be live (i.e. not deleted), and modified.
2734  *
2735  * If (parent) is non-NULL then the new duplicated chain is inserted under
2736  * the parent.
2737  *
2738  * If (parent) is NULL then the newly duplicated chain is not inserted
2739  * anywhere, similar to if it had just been chain_alloc()'d (suitable for
2740  * passing into hammer2_chain_create() after this function returns).
2741  *
2742  * WARNING! This function cannot take snapshots all by itself.  The caller
2743  *          needs to do other massaging for snapshots.
2744  *
2745  * WARNING! This function calls create which means it can insert indirect
2746  *          blocks.  Callers may have to refactor locked chains held across
2747  *          the call (other than the ones passed into the call).
2748  */
2749 void
2750 hammer2_chain_duplicate(hammer2_trans_t *trans, hammer2_chain_t **parentp,
2751                         hammer2_chain_t **chainp, hammer2_blockref_t *bref,
2752                         int snapshot, int duplicate_reason)
2753 {
2754         hammer2_mount_t *hmp;
2755         hammer2_chain_t *parent;
2756         hammer2_chain_t *ochain;
2757         hammer2_chain_t *nchain;
2758         hammer2_chain_core_t *above;
2759         size_t bytes;
2760
2761         /*
2762          * We want nchain to be our go-to live chain, but ochain may be in
2763          * a MODIFIED state within the current flush synchronization segment.
2764          * Force any further modifications of ochain to do another COW
2765          * operation even if modify_tid indicates that one is not needed.
2766          *
2767          * We don't want to set FORCECOW on nchain simply as an optimization,
2768          * as many duplication calls simply move chains into ichains and
2769          * then delete the original.
2770          *
2771          * WARNING!  We should never resolve DATA to device buffers
2772          *           (XXX allow it if the caller did?), and since
2773          *           we currently do not have the logical buffer cache
2774          *           buffer in-hand to fix its cached physical offset
2775          *           we also force the modify code to not COW it. XXX
2776          */
2777         ochain = *chainp;
2778         hmp = ochain->hmp;
2779         KKASSERT(snapshot == 1 || (ochain->flags & HAMMER2_CHAIN_DELETED));
2780
2781         /*
2782          * Now create a duplicate of the chain structure, associating
2783          * it with the same core, making it the same size, pointing it
2784          * to the same bref (the same media block).
2785          *
2786          * Give nchain the same modify_tid that we previously ensured was
2787          * sufficiently advanced to trigger a block table insertion on flush.
2788          *
2789          * nchain copies ochain's data and must inherit ochain->update_lo.
2790          *
2791          * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
2792          *       hammer2_chain_alloc()
2793          */
2794         if (bref == NULL)
2795                 bref = &ochain->bref;
2796         if (snapshot) {
2797                 nchain = hammer2_chain_alloc(hmp, NULL, trans, bref);
2798                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_SNAPSHOT);
2799         } else {
2800                 nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, bref);
2801         }
2802         hammer2_chain_core_alloc(trans, nchain, ochain);
2803         bytes = (hammer2_off_t)1 <<
2804                 (int)(bref->data_off & HAMMER2_OFF_MASK_RADIX);
2805         nchain->bytes = bytes;
2806         nchain->modify_tid = ochain->modify_tid;
2807         nchain->update_lo = ochain->update_lo;
2808         nchain->inode_reason = ochain->inode_reason + 0x100000;
2809         atomic_set_int(&nchain->flags,
2810                        ochain->flags & (HAMMER2_CHAIN_INITIAL |
2811                                         HAMMER2_CHAIN_FORCECOW |
2812                                         HAMMER2_CHAIN_UNLINKED));
2813         if (ochain->modify_tid == trans->sync_tid)
2814                 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
2815
2816         /*
2817          * Switch from ochain to nchain
2818          */
2819         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER |
2820                                    HAMMER2_RESOLVE_NOREF);
2821         /* nchain has 1 ref */
2822         hammer2_chain_unlock(ochain);
2823
2824         /*
2825          * Place nchain in the modified state, instantiate media data
2826          * if necessary.  Because modify_tid is already completely
2827          * synchronized this should not result in a delete-duplicate.
2828          *
2829          * We want nchain at the target to look like a new insertion.
2830          * Forcing the modification to be INPLACE accomplishes this
2831          * because we get the same nchain with an updated modify_tid.
2832          */
2833         if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
2834                 hammer2_chain_modify(trans, &nchain,
2835                                      HAMMER2_MODIFY_OPTDATA |
2836                                      HAMMER2_MODIFY_NOREALLOC |
2837                                      HAMMER2_MODIFY_INPLACE);
2838         } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
2839                 hammer2_chain_modify(trans, &nchain,
2840                                      HAMMER2_MODIFY_OPTDATA |
2841                                      HAMMER2_MODIFY_INPLACE);
2842         } else {
2843                 hammer2_chain_modify(trans, &nchain,
2844                                      HAMMER2_MODIFY_INPLACE);
2845         }
2846
2847         /*
2848          * If parent is not NULL the duplicated chain will be entered under
2849          * the parent and the FLUSH_CREATE bit set to tell flush to update
2850          * the blockref.
2851          *
2852          * Having both chains locked is extremely important for atomicy.
2853          */
2854         if (parentp && (parent = *parentp) != NULL) {
2855                 above = parent->core;
2856                 KKASSERT(ccms_thread_lock_owned(&above->cst));
2857                 KKASSERT((nchain->flags & HAMMER2_CHAIN_DELETED) == 0);
2858                 KKASSERT(parent->refs > 0);
2859
2860                 hammer2_chain_create(trans, parentp, &nchain,
2861                                      nchain->bref.key, nchain->bref.keybits,
2862                                      nchain->bref.type, nchain->bytes);
2863                 parent = NULL;
2864
2865                 KKASSERT(nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE);
2866                 hammer2_chain_setsubmod(trans, nchain);
2867         }
2868
2869         *chainp = nchain;
2870 }
2871
2872 /*
2873  * Helper function for deleting chains.
2874  *
2875  * The chain is removed from the live view (the RBTREE).
2876  *
2877  * If appropriate, the chain is added to the shadow topology and FLUSH_DELETE
2878  * is set for flusher visbility.  The caller is responsible for calling
2879  * setsubmod on chain, so we do not adjust update_hi here.
2880  */
2881 static void
2882 _hammer2_chain_delete_helper(hammer2_trans_t *trans,
2883                              hammer2_chain_core_t *above,
2884                              hammer2_chain_t *chain)
2885 {
2886         hammer2_mount_t *hmp;
2887         hammer2_chain_t *xchain;
2888
2889         KKASSERT(chain->flags & HAMMER2_CHAIN_ONRBTREE);
2890         KKASSERT(trans->sync_tid >= chain->modify_tid);
2891         KKASSERT((chain->flags & (HAMMER2_CHAIN_DELETED |
2892                                   HAMMER2_CHAIN_ONDBQ |
2893                                   HAMMER2_CHAIN_ONDBTREE |
2894                                   HAMMER2_CHAIN_FLUSH_DELETE)) == 0);
2895
2896         /*
2897          * Flag as deleted, reduce live_count and bump the above core's
2898          * generation.
2899          */
2900         chain->delete_tid = trans->sync_tid;
2901         atomic_set_int(&chain->flags, HAMMER2_CHAIN_DELETED);
2902         atomic_add_int(&above->live_count, -1);
2903         ++above->generation;
2904         hmp = chain->hmp;
2905
2906         /*
2907          * Remove from live tree
2908          */
2909         RB_REMOVE(hammer2_chain_tree, &above->rbtree, chain);
2910         atomic_clear_int(&chain->flags, HAMMER2_CHAIN_ONRBTREE);
2911
2912         if (chain->flags & HAMMER2_CHAIN_BMAPPED) {
2913                 /*
2914                  * If the chain was originally bmapped we must place on the
2915                  * deleted tree and set FLUSH_DELETE (+ref) to prevent
2916                  * destruction of the chain until the flush can reconcile
2917                  * the parent's block table.
2918                  *
2919                  * NOTE! DBTREE is only representitive of the live view,
2920                  *       the flush must check both DBTREE and DBQ.
2921                  */
2922                 xchain = RB_INSERT(hammer2_chain_tree, &above->dbtree, chain);
2923                 KKASSERT(xchain == NULL);
2924                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBTREE);
2925
2926                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
2927                 hammer2_chain_ref(chain);
2928         } else {
2929                 /*
2930                  * If the chain no longer (and never had) an actual blockmap
2931                  * entry we must place it on the dbq list and set FLUSH_DELETE
2932                  * (+ref) to prevent destruction of the chain until the flush
2933                  * can reconcile the parent's block table.
2934                  *
2935                  * NOTE! DBTREE is only representitive of the live view,
2936                  *       the flush must check both DBTREE and DBQ.
2937                  */
2938                 TAILQ_INSERT_TAIL(&above->dbq, chain, db_entry);
2939                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_ONDBQ);
2940
2941                 atomic_set_int(&chain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
2942                 hammer2_chain_ref(chain);
2943         }
2944 }
2945
2946 /*
2947  * Special in-place delete-duplicate sequence which does not require a
2948  * locked parent.  (*chainp) is marked DELETED and atomically replaced
2949  * with a duplicate.  Atomicy is at the very-fine spin-lock level in
2950  * order to ensure that lookups do not race us.
2951  *
2952  * The flush code will sometimes call this function with a deleted chain.
2953  * In this situation the old chain's memory is reallocated without
2954  * duplicating it.
2955  *
2956  * The new chain will be marked modified for the current transaction.
2957  */
2958 void
2959 hammer2_chain_delete_duplicate(hammer2_trans_t *trans, hammer2_chain_t **chainp,
2960                                int flags)
2961 {
2962         hammer2_mount_t *hmp;
2963         hammer2_chain_t *ochain;
2964         hammer2_chain_t *nchain;
2965         hammer2_chain_core_t *above;
2966         size_t bytes;
2967         uint32_t oflags;
2968
2969         if (hammer2_debug & 0x20000)
2970                 Debugger("dd");
2971
2972         /*
2973          * Note that we do not have to call setsubmod on ochain, calling it
2974          * on nchain is sufficient.
2975          */
2976         ochain = *chainp;
2977         oflags = ochain->flags;         /* flags prior to core_alloc mods */
2978         hmp = ochain->hmp;
2979
2980         if (ochain->bref.type == HAMMER2_BREF_TYPE_INODE) {
2981                 KKASSERT(ochain->data);
2982         }
2983
2984         /*
2985          * First create a duplicate of the chain structure.
2986          * (nchain is allocated with one ref).
2987          *
2988          * In the case where nchain inherits ochains core, nchain is
2989          * effectively locked due to ochain being locked (and sharing the
2990          * core), until we can give nchain its own official ock.
2991          *
2992          * WARNING! Flusher concurrency can create two cases.  The first is
2993          *          that the flusher might be working on a chain that has
2994          *          been deleted in the live view but is live in the flusher's
2995          *          view.  In the second case the flusher may be duplicating
2996          *          a forward-transacted chain.  In both situations nchain
2997          *          must be marked deleted.
2998          *
2999          * WARNING! hammer2_chain_core_alloc() also acts on these issues.
3000          */
3001         nchain = hammer2_chain_alloc(hmp, ochain->pmp, trans, &ochain->bref);
3002         if ((ochain->flags & HAMMER2_CHAIN_DELETED) ||
3003             (ochain->modify_tid > trans->sync_tid)) {
3004                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_DELETED);
3005         }
3006         if (flags & HAMMER2_DELDUP_RECORE)
3007                 hammer2_chain_core_alloc(trans, nchain, NULL);
3008         else
3009                 hammer2_chain_core_alloc(trans, nchain, ochain);
3010         above = ochain->above;
3011
3012         bytes = (hammer2_off_t)1 <<
3013                 (int)(ochain->bref.data_off & HAMMER2_OFF_MASK_RADIX);
3014         nchain->bytes = bytes;
3015
3016         /*
3017          * nchain inherits ochain's live state including its modification
3018          * state.  This function disposes of the original.  Because we are
3019          * doing this in-place under the same parent the block array
3020          * inserted/deleted state does not change.
3021          *
3022          * nchain copies ochain's data and must inherit ochain->update_lo.
3023          *
3024          * If ochain was previously marked FORCECOW we also flag nchain
3025          * FORCECOW (used during hardlink splits).  FORCECOW forces a
3026          * reallocation of the block when we modify the chain a little later,
3027          * it does not force another delete-duplicate.
3028          *
3029          * NOTE: bref.mirror_tid duplicated by virtue of bref copy in
3030          *       hammer2_chain_alloc()
3031          */
3032         nchain->data_count += ochain->data_count;
3033         nchain->inode_count += ochain->inode_count;
3034         atomic_set_int(&nchain->flags,
3035                        ochain->flags & (HAMMER2_CHAIN_INITIAL |
3036                                         HAMMER2_CHAIN_FORCECOW |
3037                                         HAMMER2_CHAIN_UNLINKED));
3038         if (ochain->modify_tid == trans->sync_tid)
3039                 atomic_set_int(&ochain->flags, HAMMER2_CHAIN_FORCECOW);
3040         nchain->inode_reason = ochain->inode_reason + 0x1000;
3041         nchain->update_lo = ochain->update_lo;
3042         nchain->dsrc = ochain->bref;                    /* DEBUG */
3043         nchain->dsrc_dupfromat = trans->sync_tid;       /* DEBUG */
3044         nchain->dsrc_dupfromflags = trans->flags;       /* DEBUG */
3045         nchain->dsrc_reason = ochain->inode_reason;     /* DEBUG */
3046         nchain->dsrc_ninserts = ochain->ninserts;       /* DEBUG */
3047         nchain->dsrc_flags = ochain->flags;             /* DEBUG */
3048         nchain->dsrc_modify = ochain->modify_tid;       /* DEBUG */
3049         nchain->dsrc_delete = ochain->delete_tid;       /* DEBUG */
3050         nchain->dsrc_update_lo = ochain->update_lo;     /* DEBUG */
3051         nchain->dsrc_original = ochain;                 /* DEBUG */
3052
3053         /*
3054          * Lock nchain so both chains are now locked (extremely important
3055          * for atomicy).  The shared core allows us to unlock ochain without
3056          * actually unlocking ochain.
3057          */
3058         hammer2_chain_lock(nchain, HAMMER2_RESOLVE_NEVER);
3059         /* extra ref still present from original allocation */
3060
3061         KKASSERT(ochain->flags & (HAMMER2_CHAIN_ONRBTREE |
3062                                   HAMMER2_CHAIN_ONDBTREE |
3063                                   HAMMER2_CHAIN_ONDBQ));
3064         spin_lock(&above->cst.spin);
3065
3066         nchain->modify_tid = ochain->modify_tid;
3067         nchain->delete_tid = HAMMER2_MAX_TID;
3068
3069         if ((nchain->flags & HAMMER2_CHAIN_DELETED) &&
3070             (oflags & HAMMER2_CHAIN_DUPLICATED)) {
3071                 /*
3072                  * Special case, used by the flush code when a chain which
3073                  * has been delete-duplicated is visible (effectively 'live')
3074                  * in the flush code.
3075                  *
3076                  * In this situations nchain will be marked deleted and
3077                  * insert before ochain.  nchain must inherit certain features
3078                  * of ochain.
3079                  */
3080                 KKASSERT(trans->flags & HAMMER2_TRANS_ISFLUSH);
3081                 KKASSERT(ochain->modify_tid < trans->sync_tid);
3082                 KKASSERT(ochain->delete_tid > trans->sync_tid);
3083                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_TEMPORARY);
3084                 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3085
3086                 if ((ochain->flags & HAMMER2_CHAIN_DELETED) &&
3087                     ochain->modify_tid < trans->sync_tid) {
3088                         nchain->delete_tid = ochain->delete_tid;
3089                         ochain->delete_tid = trans->sync_tid;
3090                 } else if (ochain->modify_tid > trans->sync_tid) {
3091                         nchain->delete_tid = ochain->modify_tid;
3092                 }
3093         } else if (nchain->flags & HAMMER2_CHAIN_DELETED) {
3094                 /*
3095                  * ochain is 'live' with respect to not having been D-D'd,
3096                  * but is flagged DELETED.  Sometimes updates to deleted
3097                  * chains must be allowed due to references which still exist
3098                  * on those chains, or due to a flush trying to retire a
3099                  * logical buffer cache buffer.
3100                  *
3101                  * In this situation the D-D operates normally, except
3102                  * ochain has already been deleted and nchain is also
3103                  * marked deleted.
3104                  */
3105                 hammer2_chain_insert(above, ochain, nchain, 0, 0);
3106                 nchain->delete_tid = trans->sync_tid;
3107         } else {
3108                 /*
3109                  * Normal case, delete-duplicate deletes ochain and nchain
3110                  * is the new live chain.
3111                  */
3112                 _hammer2_chain_delete_helper(trans, above, ochain);
3113                 hammer2_chain_insert(above, ochain, nchain,
3114                                      HAMMER2_CHAIN_INSERT_LIVE, 0);
3115         }
3116         spin_unlock(&above->cst.spin);
3117
3118         /*
3119          * ochain must be unlocked because ochain and nchain might share
3120          * a buffer cache buffer, so we need to release it so nchain can
3121          * potentially obtain it.
3122          */
3123         hammer2_chain_setsubmod(trans, ochain);
3124         hammer2_chain_unlock(ochain);
3125
3126         /*
3127          * Finishing fixing up nchain.  A new block will be allocated if
3128          * crossing a synchronization point (meta-data only).
3129          *
3130          * Calling hammer2_chain_modify() will update modify_tid to
3131          * (typically) trans->sync_tid.
3132          */
3133         if (nchain->bref.type == HAMMER2_BREF_TYPE_DATA) {
3134                 hammer2_chain_modify(trans, &nchain,
3135                                      HAMMER2_MODIFY_OPTDATA |
3136                                      HAMMER2_MODIFY_NOREALLOC |
3137                                      HAMMER2_MODIFY_INPLACE);
3138         } else if (nchain->flags & HAMMER2_CHAIN_INITIAL) {
3139                 hammer2_chain_modify(trans, &nchain,
3140                                      HAMMER2_MODIFY_OPTDATA |
3141                                      HAMMER2_MODIFY_INPLACE);
3142         } else {
3143                 hammer2_chain_modify(trans, &nchain,
3144                                      HAMMER2_MODIFY_INPLACE);
3145         }
3146         hammer2_chain_drop(nchain);
3147
3148         /*
3149          * Unconditionally set FLUSH_CREATE to force the parent blockrefs to
3150          * update as the chain_modify() above won't necessarily do it.
3151          */
3152         if ((nchain->flags & HAMMER2_CHAIN_FLUSH_CREATE) == 0) {
3153                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_CREATE);
3154                 hammer2_chain_ref(nchain);
3155         }
3156
3157         /*
3158          * If nchain is in a DELETED state we must set FLUSH_DELETE
3159          */
3160         if (nchain->flags & HAMMER2_CHAIN_DELETED)
3161                 KKASSERT((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0);
3162 #if 1
3163         if ((nchain->flags & HAMMER2_CHAIN_FLUSH_DELETE) == 0 &&
3164             (nchain->flags & HAMMER2_CHAIN_DELETED)) {
3165                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_FLUSH_DELETE);
3166                 hammer2_chain_ref(nchain);
3167         }
3168 #endif
3169         hammer2_chain_setsubmod(trans, nchain);
3170         *chainp = nchain;
3171 }
3172
3173 /*
3174  * Create a snapshot of the specified {parent, ochain} with the specified
3175  * label.  The originating hammer2_inode must be exclusively locked for
3176  * safety.
3177  *
3178  * The ioctl code has already synced the filesystem.
3179  */
3180 int
3181 hammer2_chain_snapshot(hammer2_trans_t *trans, hammer2_chain_t **ochainp,
3182                        hammer2_ioc_pfs_t *pfs)
3183 {
3184         hammer2_mount_t *hmp;
3185         hammer2_chain_t *ochain = *ochainp;
3186         hammer2_chain_t *nchain;
3187         hammer2_inode_data_t *ipdata;
3188         hammer2_inode_t *nip;
3189         size_t name_len;
3190         hammer2_key_t lhc;
3191         struct vattr vat;
3192         uuid_t opfs_clid;
3193         int error;
3194
3195         kprintf("snapshot %s ochain->refs %d ochain->flags %08x\n",
3196                 pfs->name, ochain->refs, ochain->flags);
3197
3198         name_len = strlen(pfs->name);
3199         lhc = hammer2_dirhash(pfs->name, name_len);
3200
3201         hmp = ochain->hmp;
3202         opfs_clid = ochain->data->ipdata.pfs_clid;
3203
3204         *ochainp = ochain;
3205
3206         /*
3207          * Create the snapshot directory under the super-root
3208          *
3209          * Set PFS type, generate a unique filesystem id, and generate
3210          * a cluster id.  Use the same clid when snapshotting a PFS root,
3211          * which theoretically allows the snapshot to be used as part of
3212          * the same cluster (perhaps as a cache).
3213          *
3214          * Copy the (flushed) ochain's blockref array.  Theoretically we
3215          * could use chain_duplicate() but it becomes difficult to disentangle
3216          * the shared core so for now just brute-force it.
3217          */
3218         VATTR_NULL(&vat);
3219         vat.va_type = VDIR;
3220         vat.va_mode = 0755;
3221         nchain = NULL;
3222         nip = hammer2_inode_create(trans, hmp->sroot, &vat, proc0.p_ucred,
3223                                    pfs->name, name_len, &nchain, &error);
3224
3225         if (nip) {
3226                 ipdata = hammer2_chain_modify_ip(trans, nip, &nchain, 0);
3227                 ipdata->pfs_type = HAMMER2_PFSTYPE_SNAPSHOT;
3228                 kern_uuidgen(&ipdata->pfs_fsid, 1);
3229                 if (ochain->flags & HAMMER2_CHAIN_PFSROOT)
3230                         ipdata->pfs_clid = opfs_clid;
3231                 else
3232                         kern_uuidgen(&ipdata->pfs_clid, 1);
3233                 atomic_set_int(&nchain->flags, HAMMER2_CHAIN_PFSROOT);
3234                 ipdata->u.blockset = ochain->data->ipdata.u.blockset;
3235
3236                 hammer2_inode_unlock_ex(nip, nchain);
3237         }
3238         return (error);
3239 }
3240
3241 /*
3242  * Create an indirect block that covers one or more of the elements in the
3243  * current parent.  Either returns the existing parent with no locking or
3244  * ref changes or returns the new indirect block locked and referenced
3245  * and leaving the original parent lock/ref intact as well.
3246  *
3247  * If an error occurs, NULL is returned and *errorp is set to the error.
3248  *
3249  * The returned chain depends on where the specified key falls.
3250  *
3251  * The key/keybits for the indirect mode only needs to follow three rules:
3252  *
3253  * (1) That all elements underneath it fit within its key space and
3254  *
3255  * (2) That all elements outside it are outside its key space.
3256  *
3257  * (3) When creating the new indirect block any elements in the current
3258  *     parent that fit within the new indirect block's keyspace must be
3259  *     moved into the new indirect block.
3260  *
3261  * (4) The keyspace chosen for the inserted indirect block CAN cover a wider
3262  *     keyspace the the current parent, but lookup/iteration rules will
3263  *     ensure (and must ensure) that rule (2) for all parents leading up
3264  *     to the nearest inode or the root volume header is adhered to.  This
3265  *     is accomplished by always recursing through matching keyspaces in
3266  *     the hammer2_chain_lookup() and hammer2_chain_next() API.
3267  *
3268  * The current implementation calculates the current worst-case keyspace by
3269  * iterating the current parent and then divides it into two halves, choosing
3270  * whichever half has the most elements (not necessarily the half containing
3271  * the requested key).
3272  *
3273  * We can also opt to use the half with the least number of elements.  This
3274  * causes lower-numbered keys (aka logical file offsets) to recurse through
3275  * fewer indirect blocks and higher-numbered keys to recurse through more.
3276  * This also has the risk of not moving enough elements to the new indirect
3277  * block and being forced to create several indirect blocks before the element
3278  * can be inserted.
3279  *
3280  * Must be called with an exclusively locked parent.
3281  */
3282 static int hammer2_chain_indkey_freemap(hammer2_chain_t *parent,
3283                                 hammer2_key_t *keyp, int keybits,
3284                                 hammer2_blockref_t *base, int count);
3285 static int hammer2_chain_indkey_normal(hammer2_chain_t *parent,
3286                                 hammer2_key_t *keyp, int keybits,
3287                                 hammer2_blockref_t *base, int count);
3288 static
3289 hammer2_chain_t *
3290 hammer2_chain_create_indirect(hammer2_trans_t *trans, hammer2_chain_t *parent,
3291                               hammer2_key_t create_key, int create_bits,
3292                               int for_type, int *errorp)
3293 {
3294         hammer2_mount_t *hmp;
3295         hammer2_chain_core_t *above;
3296         hammer2_chain_core_t *icore;
3297         hammer2_blockref_t *base;
3298         hammer2_blockref_t *bref;
3299         hammer2_blockref_t bcopy;
3300         hammer2_chain_t *chain;
3301         hammer2_chain_t *ichain;
3302         hammer2_chain_t dummy;
3303         hammer2_key_t key = create_key;
3304         hammer2_key_t key_beg;
3305         hammer2_key_t key_end;
3306         hammer2_key_t key_next;
3307         int keybits = create_bits;
3308         int count;
3309         int nbytes;
3310         int cache_index;
3311         int loops;
3312         int reason;
3313         int generation;
3314         int maxloops = 300000;
3315         int retry_same;
3316         int wasdup;
3317
3318         /*
3319          * Calculate the base blockref pointer or NULL if the chain
3320          * is known to be empty.  We need to calculate the array count
3321          * for RB lookups either way.
3322          */
3323         hmp = parent->hmp;
3324         *errorp = 0;
3325         KKASSERT(ccms_thread_lock_owned(&parent->core->cst));
3326         above = parent->core;
3327
3328         /*hammer2_chain_modify(trans, &parent, HAMMER2_MODIFY_OPTDATA);*/
3329         if (parent->flags & HAMMER2_CHAIN_INITIAL) {
3330                 base = NULL;
3331
3332                 switch(parent->bref.type) {
3333                 case HAMMER2_BREF_TYPE_INODE:
3334                         count = HAMMER2_SET_COUNT;
3335                         break;
3336                 case HAMMER2_BREF_TYPE_INDIRECT:
3337                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3338                         count = parent->bytes / sizeof(hammer2_blockref_t);
3339                         break;
3340                 case HAMMER2_BREF_TYPE_VOLUME:
3341                         count = HAMMER2_SET_COUNT;
3342                         break;
3343                 case HAMMER2_BREF_TYPE_FREEMAP:
3344                         count = HAMMER2_SET_COUNT;
3345                         break;
3346                 default:
3347                         panic("hammer2_chain_create_indirect: "
3348                               "unrecognized blockref type: %d",
3349                               parent->bref.type);
3350                         count = 0;
3351                         break;
3352                 }
3353         } else {
3354                 switch(parent->bref.type) {
3355                 case HAMMER2_BREF_TYPE_INODE:
3356                         base = &parent->data->ipdata.u.blockset.blockref[0];
3357                         count = HAMMER2_SET_COUNT;
3358                         break;
3359                 case HAMMER2_BREF_TYPE_INDIRECT:
3360                 case HAMMER2_BREF_TYPE_FREEMAP_NODE:
3361                         base = &parent->data->npdata[0];
3362                         count = parent->bytes / sizeof(hammer2_blockref_t);
3363                         break;
3364                 case HAMMER2_BREF_TYPE_VOLUME:
3365                         base = &hmp->voldata.sroot_blockset.blockref[0];
3366                         count = HAMMER2_SET_COUNT;
3367                         break;
3368                 case HAMMER2_BREF_TYPE_FREEMAP:
3369                         base = &hmp->voldata.freemap_blockset.blockref[0];
3370                         count = HAMMER2_SET_COUNT;
3371                         break;
3372                 default:
3373                         panic("hammer2_chain_create_indirect: "
3374                               "unrecognized blockref type: %d",
3375                               parent->bref.type);
3376                         count = 0;
3377                         break;
3378                 }
3379         }
3380
3381         /*
3382          * dummy used in later chain allocation (no longer used for lookups).
3383          */
3384         bzero(&dummy, sizeof(dummy));
3385         dummy.delete_tid = HAMMER2_MAX_TID;
3386
3387         /*
3388          * When creating an indirect block for a freemap node or leaf
3389          * the key/keybits must be fitted to static radix levels because
3390          * particular radix levels use particular reserved blocks in the
3391          * related zone.
3392          *
3393          * This routine calculates the key/radix of the indirect block
3394          * we need to create, and whether it is on the high-side or the
3395          * low-side.
3396          */
3397         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3398             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3399                 keybits = hammer2_chain_indkey_freemap(parent, &key, keybits,
3400                                                        base, count);
3401         } else {
3402                 keybits = hammer2_chain_indkey_normal(parent, &key, keybits,
3403                                                       base, count);
3404         }
3405
3406         /*
3407          * Normalize the key for the radix being represented, keeping the
3408          * high bits and throwing away the low bits.
3409          */
3410         key &= ~(((hammer2_key_t)1 << keybits) - 1);
3411
3412         /*
3413          * How big should our new indirect block be?  It has to be at least
3414          * as large as its parent.
3415          */
3416         if (parent->bref.type == HAMMER2_BREF_TYPE_INODE)
3417                 nbytes = HAMMER2_IND_BYTES_MIN;
3418         else
3419                 nbytes = HAMMER2_IND_BYTES_MAX;
3420         if (nbytes < count * sizeof(hammer2_blockref_t))
3421                 nbytes = count * sizeof(hammer2_blockref_t);
3422
3423         /*
3424          * Ok, create our new indirect block
3425          */
3426         if (for_type == HAMMER2_BREF_TYPE_FREEMAP_NODE ||
3427             for_type == HAMMER2_BREF_TYPE_FREEMAP_LEAF) {
3428                 dummy.bref.type = HAMMER2_BREF_TYPE_FREEMAP_NODE;
3429         } else {
3430                 dummy.bref.type = HAMMER2_BREF_TYPE_INDIRECT;
3431         }
3432         dummy.bref.key = key;
3433         dummy.bref.keybits = keybits;
3434         dummy.bref.data_off = hammer2_getradix(nbytes);
3435         dummy.bref.methods = parent->bref.methods;
3436
3437         ichain = hammer2_chain_alloc(hmp, parent->pmp, trans, &dummy.bref);
3438         atomic_set_int(&ichain->flags, HAMMER2_CHAIN_INITIAL);
3439         hammer2_chain_core_alloc(trans, ichain, NULL);
3440         icore = ichain->core;
3441         hammer2_chain_lock(ichain, HAMMER2_RESOLVE_MAYBE);
3442         hammer2_chain_drop(ichain);     /* excess ref from alloc */
3443
3444         /*
3445          * We have to mark it modified to allocate its block, but use
3446          * OPTDATA to allow it to remain in the INITIAL state.  Otherwise
3447          * it won't be acted upon by the flush code.
3448          */
3449         hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);
3450
3451         /*
3452          * Iterate the original parent and move the matching brefs into
3453          * the new indirect block.
3454          *
3455          * XXX handle flushes.
3456          */
3457         key_beg = 0;
3458         key_end = HAMMER2_MAX_KEY;
3459         cache_index = 0;
3460         spin_lock(&above->cst.spin);
3461         loops = 0;
3462         reason = 0;
3463         retry_same = 0;
3464
3465         for (;;) {
3466                 if (++loops > 100000) {
3467                     spin_unlock(&above->cst.spin);
3468                     panic("excessive loops r=%d p=%p base/count %p:%d %016jx\n",
3469                           reason, parent, base, count, key_next);
3470                 }
3471
3472                 /*
3473                  * NOTE: spinlock stays intact, returned chain (if not NULL)
3474                  *       is not referenced or locked which means that we
3475                  *       cannot safely check its flagged / deletion status
3476                  *       until we lock it.
3477                  */
3478                 chain = hammer2_combined_find(parent, base, count,
3479                                               &cache_index, &key_next,
3480                                               key_beg, key_end,
3481                                               &bref);
3482                 generation = above->generation;
3483                 if (bref == NULL)
3484                         break;
3485                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3486
3487                 /*
3488                  * Skip keys that are not within the key/radix of the new
3489                  * indirect block.  They stay in the parent.
3490                  */
3491                 if ((~(((hammer2_key_t)1 << keybits) - 1) &
3492                     (key ^ bref->key)) != 0) {
3493                         goto next_key_spinlocked;
3494                 }
3495
3496                 /*
3497                  * Load the new indirect block by acquiring the related
3498                  * chains (potentially from media as it might not be
3499                  * in-memory).  Then move it to the new parent (ichain)
3500                  * via DELETE-DUPLICATE.
3501                  *
3502                  * chain is referenced but not locked.  We must lock the
3503                  * chain to obtain definitive DUPLICATED/DELETED state
3504                  */
3505                 if (chain) {
3506                         /*
3507                          * Use chain already present in the RBTREE
3508                          */
3509                         hammer2_chain_ref(chain);
3510                         wasdup = ((chain->flags &
3511                                    HAMMER2_CHAIN_DUPLICATED) != 0);
3512                         spin_unlock(&above->cst.spin);
3513                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3514                                                   HAMMER2_RESOLVE_NOREF);
3515                 } else {
3516                         /*
3517                          * Get chain for blockref element.  _get returns NULL
3518                          * on insertion race.
3519                          */
3520                         bcopy = *bref;
3521                         spin_unlock(&above->cst.spin);
3522                         chain = hammer2_chain_get(parent, generation, &bcopy);
3523                         if (chain == NULL) {
3524                                 reason = 1;
3525                                 spin_lock(&above->cst.spin);
3526                                 continue;
3527                         }
3528                         if (bcmp(&bcopy, bref, sizeof(bcopy))) {
3529                                 reason = 2;
3530                                 hammer2_chain_drop(chain);
3531                                 spin_lock(&above->cst.spin);
3532                                 continue;
3533                         }
3534                         hammer2_chain_lock(chain, HAMMER2_RESOLVE_NEVER |
3535                                                   HAMMER2_RESOLVE_NOREF);
3536                         wasdup = 0;
3537                 }
3538
3539                 /*
3540                  * This is always live so if the chain has been delete-
3541                  * duplicated we raced someone and we have to retry.
3542                  *
3543                  * NOTE: Lookups can race delete-duplicate because
3544                  *       delete-duplicate does not lock the parent's core
3545                  *       (they just use the spinlock on the core).  We must
3546                  *       check for races by comparing the DUPLICATED flag before
3547                  *       releasing the spinlock with the flag after locking the
3548                  *       chain.
3549                  *
3550                  *       (note reversed logic for this one)
3551                  */
3552                 if (chain->flags & HAMMER2_CHAIN_DELETED) {
3553                         hammer2_chain_unlock(chain);
3554                         if ((chain->flags & HAMMER2_CHAIN_DUPLICATED) &&
3555                             wasdup == 0) {
3556                                 retry_same = 1;
3557                         }
3558                         goto next_key;
3559                 }
3560
3561                 /*
3562                  * Shift the chain to the indirect block.
3563                  *
3564                  * WARNING! Can cause held-over chains to require a refactor.
3565                  *          Fortunately we have none (our locked chains are
3566                  *          passed into and modified by the call).
3567                  */
3568                 hammer2_chain_delete(trans, chain, 0);
3569                 hammer2_chain_duplicate(trans, &ichain, &chain, NULL, 0, 1);
3570                 hammer2_chain_unlock(chain);
3571                 KKASSERT(parent->refs > 0);
3572                 chain = NULL;
3573 next_key:
3574                 spin_lock(&above->cst.spin);
3575 next_key_spinlocked:
3576                 if (--maxloops == 0)
3577                         panic("hammer2_chain_create_indirect: maxloops");
3578                 reason = 4;
3579                 if (retry_same == 0) {
3580                         if (key_next == 0 || key_next > key_end)
3581                                 break;
3582                         key_beg = key_next;
3583                 }
3584                 /* loop */
3585         }
3586         spin_unlock(&above->cst.spin);
3587
3588         /*
3589          * Insert the new indirect block into the parent now that we've
3590          * cleared out some entries in the parent.  We calculated a good
3591          * insertion index in the loop above (ichain->index).
3592          *
3593          * We don't have to set FLUSH_CREATE here because we mark ichain
3594          * modified down below (so the normal modified -> flush -> set-moved
3595          * sequence applies).
3596          *
3597          * The insertion shouldn't race as this is a completely new block
3598          * and the parent is locked.
3599          */
3600         KKASSERT((ichain->flags & HAMMER2_CHAIN_ONRBTREE) == 0);
3601         hammer2_chain_insert(above, NULL, ichain,
3602                              HAMMER2_CHAIN_INSERT_SPIN |
3603                              HAMMER2_CHAIN_INSERT_LIVE,
3604                              0);
3605
3606         /*
3607          * Mark the new indirect block modified after insertion, which
3608          * will propagate up through parent all the way to the root and
3609          * also allocate the physical block in ichain for our caller,
3610          * and assign ichain->data to a pre-zero'd space (because there
3611          * is not prior data to copy into it).
3612          */
3613         /*hammer2_chain_modify(trans, &ichain, HAMMER2_MODIFY_OPTDATA);*/
3614         hammer2_chain_setsubmod(trans, ichain);
3615
3616         /*
3617          * Figure out what to return.
3618          */
3619         if (~(((hammer2_key_t)1 << keybits) - 1) &
3620                    (create_key ^ key)) {
3621                 /*
3622                  * Key being created is outside the key range,
3623                  * return the original parent.
3624                  */
3625                 hammer2_chain_unlock(ichain);
3626         } else {
3627                 /*
3628                  * Otherwise its in the range, return the new parent.
3629                  * (leave both the new and old parent locked).
3630                  */
3631                 parent = ichain;
3632         }
3633
3634         return(parent);
3635 }
3636
3637 /*
3638  * Calculate the keybits and highside/lowside of the freemap node the
3639  * caller is creating.
3640  *
3641  * This routine will specify the next higher-level freemap key/radix
3642  * representing the lowest-ordered set.  By doing so, eventually all
3643  * low-ordered sets will be moved one level down.
3644  *
3645  * We have to be careful here because the freemap reserves a limited
3646  * number of blocks for a limited number of levels.  So we can't just
3647  * push indiscriminately.
3648  */
3649 int
3650 hammer2_chain_indkey_freemap(hammer2_chain_t *parent, hammer2_key_t *keyp,
3651                              int keybits, hammer2_blockref_t *base, int count)
3652 {
3653         hammer2_chain_core_t *above;
3654         hammer2_chain_t *chain;
3655         hammer2_blockref_t *bref;
3656         hammer2_key_t key;
3657         hammer2_key_t key_beg;
3658         hammer2_key_t key_end;
3659         hammer2_key_t key_next;
3660         int cache_index;
3661         int locount;
3662         int hicount;
3663         int maxloops = 300000;
3664
3665         key = *keyp;
3666         above = parent->core;
3667         locount = 0;
3668         hicount = 0;
3669         keybits = 64;
3670
3671         /*
3672          * Calculate the range of keys in the array being careful to skip
3673          * slots which are overridden with a deletion.
3674          */
3675         key_beg = 0;
3676         key_end = HAMMER2_MAX_KEY;
3677         cache_index = 0;
3678         spin_lock(&above->cst.spin);
3679
3680         for (;;) {
3681                 if (--maxloops == 0) {
3682                         panic("indkey_freemap shit %p %p:%d\n",
3683                               parent, base, count);
3684                 }
3685                 chain = hammer2_combined_find(parent, base, count,
3686                                               &cache_index, &key_next,
3687                                               key_beg, key_end,
3688                                               &bref);
3689
3690                 /*
3691                  * Exhausted search
3692                  */
3693                 if (bref == NULL)
3694                         break;
3695
3696                 /*
3697                  * NOTE: No need to check DUPLICATED here because we do
3698                  *       not release the spinlock.
3699                  */
3700                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3701                         if (key_next == 0 || key_next > key_end)
3702                                 break;
3703                         key_beg = key_next;
3704                         continue;
3705                 }
3706
3707                 /*
3708                  * Use the full live (not deleted) element for the scan
3709                  * iteration.  HAMMER2 does not allow partial replacements.
3710                  *
3711                  * XXX should be built into hammer2_combined_find().
3712                  */
3713                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3714
3715                 if (keybits > bref->keybits) {
3716                         key = bref->key;
3717                         keybits = bref->keybits;
3718                 } else if (keybits == bref->keybits && bref->key < key) {
3719                         key = bref->key;
3720                 }
3721                 if (key_next == 0)
3722                         break;
3723                 key_beg = key_next;
3724         }
3725         spin_unlock(&above->cst.spin);
3726
3727         /*
3728          * Return the keybits for a higher-level FREEMAP_NODE covering
3729          * this node.
3730          */
3731         switch(keybits) {
3732         case HAMMER2_FREEMAP_LEVEL0_RADIX:
3733                 keybits = HAMMER2_FREEMAP_LEVEL1_RADIX;
3734                 break;
3735         case HAMMER2_FREEMAP_LEVEL1_RADIX:
3736                 keybits = HAMMER2_FREEMAP_LEVEL2_RADIX;
3737                 break;
3738         case HAMMER2_FREEMAP_LEVEL2_RADIX:
3739                 keybits = HAMMER2_FREEMAP_LEVEL3_RADIX;
3740                 break;
3741         case HAMMER2_FREEMAP_LEVEL3_RADIX:
3742                 keybits = HAMMER2_FREEMAP_LEVEL4_RADIX;
3743                 break;
3744         case HAMMER2_FREEMAP_LEVEL4_RADIX:
3745                 panic("hammer2_chain_indkey_freemap: level too high");
3746                 break;
3747         default:
3748                 panic("hammer2_chain_indkey_freemap: bad radix");
3749                 break;
3750         }
3751         *keyp = key;
3752
3753         return (keybits);
3754 }
3755
3756 /*
3757  * Calculate the keybits and highside/lowside of the indirect block the
3758  * caller is creating.
3759  */
3760 static int
3761 hammer2_chain_indkey_normal(hammer2_chain_t *parent, hammer2_key_t *keyp,
3762                             int keybits, hammer2_blockref_t *base, int count)
3763 {
3764         hammer2_chain_core_t *above;
3765         hammer2_blockref_t *bref;
3766         hammer2_chain_t *chain;
3767         hammer2_key_t key_beg;
3768         hammer2_key_t key_end;
3769         hammer2_key_t key_next;
3770         hammer2_key_t key;
3771         int nkeybits;
3772         int locount;
3773         int hicount;
3774         int cache_index;
3775         int maxloops = 300000;
3776
3777         key = *keyp;
3778         above = parent->core;
3779         locount = 0;
3780         hicount = 0;
3781
3782         /*
3783          * Calculate the range of keys in the array being careful to skip
3784          * slots which are overridden with a deletion.  Once the scan
3785          * completes we will cut the key range in half and shift half the
3786          * range into the new indirect block.
3787          */
3788         key_beg = 0;
3789         key_end = HAMMER2_MAX_KEY;
3790         cache_index = 0;
3791         spin_lock(&above->cst.spin);
3792
3793         for (;;) {
3794                 if (--maxloops == 0) {
3795                         panic("indkey_freemap shit %p %p:%d\n",
3796                               parent, base, count);
3797                 }
3798                 chain = hammer2_combined_find(parent, base, count,
3799                                               &cache_index, &key_next,
3800                                               key_beg, key_end,
3801                                               &bref);
3802
3803                 /*
3804                  * Exhausted search
3805                  */
3806                 if (bref == NULL)
3807                         break;
3808
3809                 /*
3810                  * NOTE: No need to check DUPLICATED here because we do
3811                  *       not release the spinlock.
3812                  */
3813                 if (chain && (chain->flags & HAMMER2_CHAIN_DELETED)) {
3814                         if (key_next == 0 || key_next > key_end)
3815                                 break;
3816                         key_beg = key_next;
3817                         continue;
3818                 }
3819
3820                 /*
3821                  * Use the full live (not deleted) element for the scan
3822                  * iteration.  HAMMER2 does not allow partial replacements.
3823                  *
3824                  * XXX should be built into hammer2_combined_find().
3825                  */
3826                 key_next = bref->key + ((hammer2_key_t)1 << bref->keybits);
3827
3828                 /*
3829                  * Expand our calculated key range (key, keybits) to fit
3830                  * the scanned key.  nkeybits represents the full range
3831                  * that we will later cut in half (two halves @ nkeybits - 1).
3832                  */
3833                 nkeybits = keybits;
3834                 if (nkeybits < bref->keybits) {
3835                         if (bref->keybits > 64) {
3836                                 kprintf("bad bref chain %p bref %p\n",
3837                                         chain, bref);
3838                                 Debugger("fubar");
3839                         }
3840                         nkeybits = bref->keybits;
3841                 }
3842                 while (nkeybits < 64 &&
3843                        (~(((hammer2_key_t)1 << nkeybits) - 1) &
3844                         (key ^ bref->key)) != 0) {
3845                         ++nkeybits;
3846                 }
3847
3848                 /*
3849                  * If the new key range is larger we have to determine
3850                  * which side of the new key range the existing keys fall
3851                  * under by checking the high bit, then collapsing the
3852                  * locount into the hicount or vise-versa.
3853                  */
3854                 if (keybits != nkeybits) {
3855                         if (((hammer2_key_t)1 << (nkeybits - 1)) & key) {
3856                                 hicount += locount;
3857                                 locount = 0;
3858                         } else {
3859                                 locount += hicount;
3860                                 hicount = 0;
3861                         }
3862                         keybits = nkeybits;
3863                 }
3864
3865                 /*
3866                  * The newly scanned key will be in the lower half or the
3867                  * upper half of the (new) key range.
3868                  */
3869                 if (((hammer2_key_t)1 << (nkeybits - 1)) & bref->key)
3870                         ++hicount;
3871                 else
3872                         ++locount;
3873
3874                 if (key_next == 0)
3875                         break;
3876                 key_beg = key_next;
3877         }
3878         spin_unlock(&above->cst.spin);
3879         bref = NULL;    /* now invalid (safety) */
3880
3881         /*
3882          * Adjust keybits to represent half of the full range calculated
3883          * above (radix 63 max)
3884          */
3885         --keybits;
3886
3887         /*
3888          * Select whichever half contains the most elements.  Theoretically
3889          * we can select either side as long as it contains at least one
3890          * element (in order to ensure that a free slot is present to hold
3891          * the indirect block).
3892          */
3893         if (hammer2_indirect_optimize) {
3894                 /*
3895                  * Insert node for least number of keys, this will arrange
3896                  * the first few blocks of a large file or the first few
3897                  * inodes in a directory with fewer indirect blocks when
3898                  * created linearly.
3899                  */
3900                 if (hicount < locount && hicount != 0)
3901                         key |= (hammer2_key_t)1 << keybits;
3902                 else
3903                         key &= ~(hammer2_key_t)1 << keybits;
3904         } else {
3905                 /*
3906                  * Insert node for most number of keys, best for heavily
3907                  * fragmented files.
3908                  */
3909                 if (hicount > locount)
3910                         key |= (hammer2_key_t)1 << keybits;
3911                 else
3912                         key &= ~(hammer2_key_t)1 << keybits;
3913         }
3914         *keyp = key;
3915
3916         return (keybits);
3917 }
3918
3919 /*
3920  * Sets CHAIN_DELETED and CHAIN_FLUSH_DELETE in the chain being deleted and
3921  * set chain->delete_tid.  The chain is not actually marked possibly-free
3922  * in the freemap until the deletion is completely flushed out (because
3923  * a flush which doesn't cover the entire deletion is flushing the deleted
3924  * chain as if it were live).
3925  *
3926  * This function does NOT generate a modification to the parent.  It
3927  * would be nearly impossible to figure out which parent to modify anyway.
3928  * Such modifications are handled top-down by the flush code and are
3929  * properly merged using the flush synchronization point.
3930  *
3931  * The find/get code will properly overload the RBTREE check on top of
3932  * the bref check to detect deleted entries.
3933  *
3934  * This function is NOT recursive.  Any entity already pushed into the
3935  * chain (such as an inode) may still need visibility into its contents,
3936  * as well as the ability to read and modify the contents.  For example,
3937  * for an unlinked file which is still open.
3938  *
3939  * NOTE: This function does NOT set chain->modify_tid, allowing future
3940  *       code to distinguish between live and deleted chains by testing
3941  *       trans->sync_tid vs chain->modify_tid and chain->delete_tid.
3942  *
3943  * NOTE: Deletions normally do not occur in the middle of a duplication
3944  *       chain but we use a trick for hardlink migration that refactors
3945  *       the originating inode without deleting it, so we make no assumptions
3946  *       here.
3947  */
3948 void
3949 hammer2_chain_delete(hammer2_trans_t *trans, hammer2_chain_t *chain, int flags)
3950 {
3951         KKASSERT(ccms_thread_lock_owned(&chain->core->cst));
3952
3953         /*
3954          * Nothing to do if already marked.
3955          */
3956         if (chain->flags & HAMMER2_CHAIN_DELETED)
3957                 return;
3958
3959         /*
3960          * The setting of DELETED causes finds, lookups, and _next iterations
3961          * to no longer recognize the chain.  RB_SCAN()s will still have
3962          * visibility (needed for flush serialization points).
3963          *
3964          * We need the spinlock on the core whos RBTREE contains chain
3965          * to protect against races.
3966          */
3967         spin_lock(&chain->above->cst.spin);
3968         _hammer2_chain_delete_helper(trans, chain->above, chain);
3969         spin_unlock(&chain->above->cst.spin);
3970
3971         hammer2_chain_setsubmod(trans, chain);
3972 }
3973
3974 /*
3975  * Returns the index of the nearest element in the blockref array >= elm.
3976  * Returns (count) if no element could be found.  If delete_filter is non-zero
3977  * the scan filters out any blockrefs which match deleted chains on dbtree.
3978  *
3979  * Sets *key_nextp to the next key for loop purposes but does not modify
3980  * it if the next key would be higher than the current value of *key_nextp.
3981  * Note that *key_nexp can overflow to 0, which should be tested by the
3982  * caller.
3983  *
3984  * (*cache_indexp) is a heuristic and can be any value without effecting
3985  * the result.
3986  *
3987  * The spin lock on the related chain must be held.
3988  */
3989 int
3990 hammer2_base_find(hammer2_chain_t *parent,
3991                   hammer2_blockref_t *base, int count,
3992                   int *cache_indexp, hammer2_key_t *key_nextp,
3993                   hammer2_key_t key_beg, hammer2_key_t key_end,
3994                   int delete_filter)
3995 {
3996         hammer2_chain_core_t *core = parent->core;
3997         hammer2_blockref_t *scan;
3998         hammer2_key_t scan_end;
3999         int i;
4000         int limit;
4001
4002         /*
4003          * Require the live chain's already have their core's counted
4004          * so we can optimize operations.
4005          */
4006         KKASSERT((parent->flags & HAMMER2_CHAIN_DUPLICATED) ||
4007                  core->flags & HAMMER2_CORE_COUNTEDBREFS);
4008
4009         /*
4010          * Degenerate case
4011          */
4012         if (count == 0 || base == NULL)
4013                 return(count);
4014
4015         /*
4016          * Sequential optimization using *cache_indexp.  This is the most
4017          * likely scenario.
4018          *
4019          * We can avoid trailing empty entries on live chains, otherwise
4020          * we might have to check the whole block array.
4021          */
4022         i = *cache_indexp;
4023         cpu_ccfence();
4024         if (parent->flags & HAMMER2_CHAIN_DUPLICATED)
4025                 limit = count;
4026         else
4027                 limit = core->live_zero;
4028         if (i >= limit)
4029                 i = limit - 1;
4030         if (i < 0)
4031                 i = 0;
4032         KKASSERT(i < count);
4033
4034         /*
4035          * Search backwards
4036          */
4037         scan = &base[i];
4038         while (i > 0 && (scan->type == 0 || scan->key > key_beg)) {
4039                 --scan;
4040                 --i;
4041         }
4042         *cache_indexp = i;
4043
4044         /*
4045          * Search forwards, stop when we find a scan element which
4046          * encloses the key or until we know that there are no further
4047          * elements.
4048          */
4049         while (i < count) {
4050                 if (scan->type != 0) {
4051                         scan_end = scan->key +
4052                                    ((hammer2_key_t)1 << scan->keybits) - 1;
4053                         if (scan->key > key_beg || scan_end >= key_beg) {
4054                                 /*
4055                                  * Check to see if the entry is covered by
4056                                  * a deleted chain and ignore the entry if
4057                                  * it is and delete_filter != 0.
4058                                  */
4059                                 if (delete_filter == 0)
4060                                         break;
4061                                 if (hammer2_chain_find_deleted(
4062                                         parent, scan->key, scan_end) == NULL) {
4063                                         break;
4064                                 }
4065                         }
4066                 }
4067                 if (i >= limit)
4068                         return (count);
4069                 ++scan;
4070                 ++i;
4071         }
4072         if (i != count) {
4073                 *cache_indexp = i;
4074                 if (i >= limit) {
4075                         i = count;
4076                 } else {
4077                         scan_end = scan->key +
4078                                    ((hammer2_key_t)1 << scan->keybits);
4079                         if (scan_end && (*key_nextp > scan_end ||
4080                                          *key_nextp == 0)) {
4081                                 *key_nextp = scan_end;
4082                         }
4083                 }
4084         }
4085         return (i);
4086 }
4087
4088 /*
4089  * Do a combined search and return the next match either from the blockref
4090  * array or from the in-memory chain.  Sets *bresp to the returned bref in
4091  * both cases, or sets it to NULL if the search exhausted.  Only returns
4092  * a non-NULL chain if the search matched from the in-memory chain.
4093  *
4094  * When no in-memory chain has been found and a non-NULL bref is returned
4095  * in *bresp.
4096  *
4097  * Must be called with above's spinlock held.  Spinlock remains held
4098  * through the operation.
4099  *
4100  * The returned chain is not locked or referenced.  Use the returned bref
4101  * to determine if the search exhausted or not.  Iterate if the base find
4102  * is chosen but matches a deleted chain.
4103  */
4104 static hammer2_chain_t *
4105 hammer2_combined_find(hammer2_chain_t *parent,
4106                       hammer2_blockref_t *base, int count,
4107                       int *cache_indexp, hammer2_key_t *key_nextp,
4108                       hammer2_key_t key_beg, hammer2_key_t key_end,
4109                       hammer2_blockref_t **bresp)
4110 {
4111         hammer2_blockref_t *bref;
4112         hammer2_chain_t *chain;
4113         int i;
4114
4115         /*
4116          * Lookup in block array and in rbtree.
4117          */
4118         *key_nextp = key_end + 1;
4119         i = hammer2_base_find(parent, base, count, cache_indexp,
4120                               key_nextp, key_beg, key_end, 1);
4121         chain = hammer2_chain_find(parent, key_nextp, key_beg, key_end);
4122
4123         /*
4124          * Neither matched
4125          */
4126         if (i == count && chain == NULL) {
4127                 *bresp = NULL;
4128                 return(NULL);
4129         }
4130
4131         /*
4132          * Only chain matched.
4133          */
4134         if (i == count) {
4135                 bref = &chain->bref;
4136                 goto found;
4137         }
4138
4139         /*
4140          * Only blockref matched.
4141          */
4142         if (chain == NULL) {
4143                 bref = &base[i];
4144                 goto found;
4145         }
4146
4147         /*
4148          * Both in-memory and blockref matched, select the nearer element.
4149          *
4150          * If both are flush with the left-hand side or both are the
4151          * same distance away, select the chain.  In this situation the
4152          * chain must have been loaded from the matching blockmap.
4153          */
4154         if ((chain->bref.key <= key_beg && base[i].key <= key_beg) ||
4155             chain->bref.key == base[i].key) {
4156                 KKASSERT(chain->bref.key == base[i].key);
4157                 if ((chain->flags & HAMMER2_CHAIN_BMAPPED) == 0) {
4158                         kprintf("chain not bmapped %p.%d %08x\n", chain, chain->bref.type, chain->flags);
4159                         kprintf("in chain mod/del %016jx %016jx\n", chain->modify_tid, chain->delete_tid);
4160                         kprintf("and updlo/hi %016jx %016jx\n", chain->update_lo, chain->update_hi);
4161                 }
4162                 KKASSERT(chain->flags & HAMMER2_CHAIN_BMAPPED);
4163                 bref = &chain->bref;
4164                 goto found;
4165         }
4166
4167         /*
4168          * Select the nearer key
4169          */
4170         if (chain->bref.key < base[i].key) {
4171                 bref = &chain->bref;
4172         } else {
4173                 bref = &base[i];
4174                 chain = NULL;
4175         }
4176
4177         /*
4178          * If the bref is out of bounds we've exhausted our search.
4179          */
4180 found:
4181         if (bref->key > key_end) {
4182                 *bresp = NULL;
4183                 chain = NULL;
4184         } else {
4185                 *bresp = bref;
4186         }
4187         return(chain);
4188 }
4189
4190 /*
4191  * Locate the specified block array element and delete it.  The element
4192  * must exist.
4193  *
4194  * The spin lock on the related chain must be held.
4195  *
4196  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4197  *       need to be adjusted when we commit the media change.
4198  */
4199 void
4200 hammer2_base_delete(hammer2_trans_t *trans, hammer2_chain_t *parent,
4201                     hammer2_blockref_t *base, int count,
4202                     int *cache_indexp, hammer2_chain_t *child)
4203 {
4204         hammer2_blockref_t *elm = &child->bref;
4205         hammer2_chain_core_t *core = parent->core;
4206         hammer2_key_t key_next;
4207         int i;
4208
4209         /*
4210          * Delete element.  Expect the element to exist.
4211          *
4212          * XXX see caller, flush code not yet sophisticated enough to prevent
4213          *     re-flushed in some cases.
4214          */
4215         key_next = 0; /* max range */
4216         i = hammer2_base_find(parent, base, count, cache_indexp,
4217                               &key_next, elm->key, elm->key, 0);
4218         if (i == count || base[i].type == 0 ||
4219             base[i].key != elm->key || base[i].keybits != elm->keybits) {
4220                 spin_unlock(&core->cst.spin);
4221                 panic("delete base %p element not found at %d/%d elm %p\n"
4222                       "child ino_reason=%08x\n",
4223                       base, i, count, elm,
4224                       child->inode_reason);
4225                 return;
4226         }
4227         bzero(&base[i], sizeof(*base));
4228         base[i].mirror_tid = (intptr_t)parent;          /* MEDIA DEBUG */
4229         base[i].modify_tid = (intptr_t)child;           /* MEDIA DEBUG */
4230         base[i].check.debug.sync_tid = trans->sync_tid; /* MEDIA DEBUG */
4231         ++parent->nremoves;                             /* DEBUG */
4232
4233         /*
4234          * We can only optimize core->live_zero for live chains.
4235          */
4236         if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4237                 if (core->live_zero == i + 1) {
4238                         while (--i >= 0 && base[i].type == 0)
4239                                 ;
4240                         core->live_zero = i + 1;
4241                 }
4242         }
4243 }
4244
4245 /*
4246  * Insert the specified element.  The block array must not already have the
4247  * element and must have space available for the insertion.
4248  *
4249  * The spin lock on the related chain must be held.
4250  *
4251  * NOTE: live_count was adjusted when the chain was deleted, so it does not
4252  *       need to be adjusted when we commit the media change.
4253  */
4254 void
4255 hammer2_base_insert(hammer2_trans_t *trans __unused, hammer2_chain_t *parent,
4256                     hammer2_blockref_t *base, int count,
4257                     int *cache_indexp, hammer2_chain_t *child)
4258 {
4259         hammer2_blockref_t *elm = &child->bref;
4260         hammer2_chain_core_t *core = parent->core;
4261         hammer2_key_t key_next;
4262         hammer2_key_t xkey;
4263         int i;
4264         int j;
4265         int k;
4266         int l;
4267         int u = 1;
4268
4269         /*
4270          * Insert new element.  Expect the element to not already exist
4271          * unless we are replacing it.
4272          *
4273          * XXX see caller, flush code not yet sophisticated enough to prevent
4274          *     re-flushed in some cases.
4275          */
4276         key_next = 0; /* max range */
4277         i = hammer2_base_find(parent, base, count, cache_indexp,
4278                               &key_next, elm->key, elm->key, 0);
4279
4280         /*
4281          * Shortcut fill optimization, typical ordered insertion(s) may not
4282          * require a search.
4283          */
4284         KKASSERT(i >= 0 && i <= count);
4285
4286         /*
4287          * We can only optimize core->live_zero for live chains.
4288          */
4289         if (i == count && core->live_zero < count) {
4290                 if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4291                         i = core->live_zero++;
4292                         base[i] = *elm;
4293         ++parent->ninserts;     /* DEBUG */
4294                         return;
4295                 }
4296         }
4297
4298         xkey = elm->key + ((hammer2_key_t)1 << elm->keybits) - 1;
4299         if (i != count && (base[i].key < elm->key || xkey >= base[i].key)) {
4300                 if (child->flags & HAMMER2_CHAIN_FLUSH_TEMPORARY) {
4301                         kprintf("child %p special replace\n", child);
4302                         base[i] = *elm;
4303                         return;
4304                 } else {
4305                         spin_unlock(&core->cst.spin);
4306                         panic("insert base %p overlapping "
4307                               "elements at %d elm %p\n",
4308                               base, i, elm);
4309                 }
4310         }
4311
4312         /*
4313          * Try to find an empty slot before or after.
4314          */
4315         j = i;
4316         k = i;
4317         while (j > 0 || k < count) {
4318                 --j;
4319                 if (j >= 0 && base[j].type == 0) {
4320                         if (j == i - 1) {
4321                                 base[j] = *elm;
4322                         } else {
4323                                 bcopy(&base[j+1], &base[j],
4324                                       (i - j - 1) * sizeof(*base));
4325                                 base[i - 1] = *elm;
4326                         }
4327         ++parent->ninserts;     /* DEBUG */
4328                         goto validate;
4329                 }
4330                 ++k;
4331                 if (k < count && base[k].type == 0) {
4332                         bcopy(&base[i], &base[i+1],
4333                               (k - i) * sizeof(hammer2_blockref_t));
4334                         base[i] = *elm;
4335
4336                         /*
4337                          * We can only update core->live_zero for live
4338                          * chains.
4339                          */
4340                         if ((parent->flags & HAMMER2_CHAIN_DUPLICATED) == 0) {
4341                                 if (core->live_zero <= k)
4342                                         core->live_zero = k + 1;
4343                         }
4344                         u = 2;
4345         ++parent->ninserts;     /* DEBUG */
4346                         goto validate;
4347                 }
4348         }
4349         panic("hammer2_base_insert: no room!");
4350
4351         /*
4352          * Debugging
4353          */
4354 validate:
4355         key_next = 0;
4356         for (l = 0; l < count; ++l) {
4357                 if (base[l].type) {
4358                         key_next = base[l].key +
4359                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4360                         break;
4361                 }
4362         }
4363         while (++l < count) {
4364                 if (base[l].type) {
4365                         if (base[l].key <= key_next)
4366                                 panic("base_insert %d %d,%d,%d fail %p:%d", u, i, j, k, base, l);
4367                         key_next = base[l].key +
4368                                    ((hammer2_key_t)1 << base[l].keybits) - 1;
4369
4370                 }
4371         }
4372
4373 }
4374
4375 #if 0
4376
4377 /*
4378  * Sort the blockref array for the chain.  Used by the flush code to
4379  * sort the blockref[] array.
4380  *
4381  * The chain must be exclusively locked AND spin-locked.
4382  */
4383 typedef hammer2_blockref_t *hammer2_blockref_p;
4384
4385 static
4386 int
4387 hammer2_base_sort_callback(const void *v1, const void *v2)
4388 {
4389         hammer2_blockref_p bref1 = *(const hammer2_blockref_p *)v1;
4390         hammer2_blockref_p bref2 = *(const hammer2_blockref_p *)v2;
4391
4392         /*
4393          * Make sure empty elements are placed at the end of the array
4394          */
4395         if (bref1->type == 0) {
4396                 if (bref2->type == 0)
4397                         return(0);
4398                 return(1);
4399         } else if (bref2->type == 0) {
4400                 return(-1);
4401         }
4402
4403         /*
4404          * Sort by key
4405          */
4406         if (bref1->key < bref2->key)
4407                 return(-1);
4408         if (bref1->key > bref2->key)
4409                 return(1);
4410         return(0);
4411 }
4412
4413 void
4414 hammer2_base_sort(hammer2_chain_t *chain)
4415 {
4416         hammer2_blockref_t *base;
4417         int count;
4418
4419         switch(chain->bref.type) {
4420         case HAMMER2_BREF_TYPE_INODE:
4421                 /*
4422                  * Special shortcut for embedded data returns the inode
4423                  * itself.  Callers must detect this condition and access
4424                  * the embedded data (the strategy code does this for us).
4425                  *
4426                  * This is only applicable to regular files and softlinks.
4427                  */
4428                 if (chain->data->ipdata.op_flags & HAMMER2_OPFLAG_DIRECTDATA)
4429                         return;
4430                 base = &chain->data->ipdata.u.blockset.blockref[0];
4431                 count = HAMMER2_SET_COUNT;
4432                 break;
4433         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4434         case HAMMER2_BREF_TYPE_INDIRECT:
4435                 /*
4436                  * Optimize indirect blocks in the INITIAL state to avoid
4437                  * I/O.
4438                  */
4439                 KKASSERT((chain->flags & HAMMER2_CHAIN_INITIAL) == 0);
4440                 base = &chain->data->npdata[0];
4441                 count = chain->bytes / sizeof(hammer2_blockref_t);
4442                 break;
4443         case HAMMER2_BREF_TYPE_VOLUME:
4444                 base = &chain->hmp->voldata.sroot_blockset.blockref[0];
4445                 count = HAMMER2_SET_COUNT;
4446                 break;
4447         case HAMMER2_BREF_TYPE_FREEMAP:
4448                 base = &chain->hmp->voldata.freemap_blockset.blockref[0];
4449                 count = HAMMER2_SET_COUNT;
4450                 break;
4451         default:
4452                 panic("hammer2_chain_lookup: unrecognized blockref type: %d",
4453                       chain->bref.type);
4454                 base = NULL;    /* safety */
4455                 count = 0;      /* safety */
4456         }
4457         kqsort(base, count, sizeof(*base), hammer2_base_sort_callback);
4458 }
4459
4460 #endif
4461
4462 /*
4463  * Chain memory management
4464  */
4465 void
4466 hammer2_chain_wait(hammer2_chain_t *chain)
4467 {
4468         tsleep(chain, 0, "chnflw", 1);
4469 }
4470
4471 /*
4472  * Manage excessive memory resource use for chain and related
4473  * structures.
4474  */
4475 void
4476 hammer2_chain_memory_wait(hammer2_pfsmount_t *pmp)
4477 {
4478         long waiting;
4479         long count;
4480         long limit;
4481 #if 0
4482         static int zzticks;
4483 #endif
4484
4485         /*
4486          * Atomic check condition and wait.  Also do an early speedup of
4487          * the syncer to try to avoid hitting the wait.
4488          */
4489         for (;;) {
4490                 waiting = pmp->inmem_dirty_chains;
4491                 cpu_ccfence();
4492                 count = waiting & HAMMER2_DIRTYCHAIN_MASK;
4493
4494                 limit = pmp->mp->mnt_nvnodelistsize / 10;
4495                 if (limit < hammer2_limit_dirty_chains)
4496                         limit = hammer2_limit_dirty_chains;
4497                 if (limit < 1000)
4498                         limit = 1000;
4499
4500 #if 0
4501                 if ((int)(ticks - zzticks) > hz) {
4502                         zzticks = ticks;
4503                         kprintf("count %ld %ld\n", count, limit);
4504                 }
4505 #endif
4506
4507                 /*
4508                  * Block if there are too many dirty chains present, wait
4509                  * for the flush to clean some out.
4510                  */
4511                 if (count > limit) {
4512                         tsleep_interlock(&pmp->inmem_dirty_chains, 0);
4513                         if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4514                                                waiting,
4515                                        waiting | HAMMER2_DIRTYCHAIN_WAITING)) {
4516                                 speedup_syncer(pmp->mp);
4517                                 tsleep(&pmp->inmem_dirty_chains, PINTERLOCKED,
4518                                        "chnmem", hz);
4519                         }
4520                         continue;       /* loop on success or fail */
4521                 }
4522
4523                 /*
4524                  * Try to start an early flush before we are forced to block.
4525                  */
4526                 if (count > limit * 7 / 10)
4527                         speedup_syncer(pmp->mp);
4528                 break;
4529         }
4530 }
4531
4532 void
4533 hammer2_chain_memory_inc(hammer2_pfsmount_t *pmp)
4534 {
4535         if (pmp)
4536                 atomic_add_long(&pmp->inmem_dirty_chains, 1);
4537 }
4538
4539 void
4540 hammer2_chain_memory_wakeup(hammer2_pfsmount_t *pmp)
4541 {
4542         long waiting;
4543
4544         if (pmp == NULL)
4545                 return;
4546
4547         for (;;) {
4548                 waiting = pmp->inmem_dirty_chains;
4549                 cpu_ccfence();
4550                 if (atomic_cmpset_long(&pmp->inmem_dirty_chains,
4551                                        waiting,
4552                                        (waiting - 1) &
4553                                         ~HAMMER2_DIRTYCHAIN_WAITING)) {
4554                         break;
4555                 }
4556         }
4557
4558         if (waiting & HAMMER2_DIRTYCHAIN_WAITING)
4559                 wakeup(&pmp->inmem_dirty_chains);
4560 }
4561
4562 static
4563 void
4564 adjreadcounter(hammer2_blockref_t *bref, size_t bytes)
4565 {
4566         long *counterp;
4567
4568         switch(bref->type) {
4569         case HAMMER2_BREF_TYPE_DATA:
4570                 counterp = &hammer2_iod_file_read;
4571                 break;
4572         case HAMMER2_BREF_TYPE_INODE:
4573                 counterp = &hammer2_iod_meta_read;
4574                 break;
4575         case HAMMER2_BREF_TYPE_INDIRECT:
4576                 counterp = &hammer2_iod_indr_read;
4577                 break;
4578         case HAMMER2_BREF_TYPE_FREEMAP_NODE:
4579         case HAMMER2_BREF_TYPE_FREEMAP_LEAF:
4580                 counterp = &hammer2_iod_fmap_read;
4581                 break;
4582         default:
4583                 counterp = &hammer2_iod_volu_read;
4584                 break;
4585         }
4586         *counterp += bytes;
4587 }