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