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