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