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