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