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