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