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