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