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