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