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