hammer2 - Cleanup
[dragonfly.git] / sys / vfs / hammer2 / hammer2_inode.c
1 /*
2  * Copyright (c) 2011-2018 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 #include <sys/cdefs.h>
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/types.h>
39 #include <sys/lock.h>
40 #include <sys/uuid.h>
41
42 #include "hammer2.h"
43
44 #define INODE_DEBUG     0
45
46 RB_GENERATE2(hammer2_inode_tree, hammer2_inode, rbnode, hammer2_inode_cmp,
47              hammer2_tid_t, meta.inum);
48
49 int
50 hammer2_inode_cmp(hammer2_inode_t *ip1, hammer2_inode_t *ip2)
51 {
52         if (ip1->meta.inum < ip2->meta.inum)
53                 return(-1);
54         if (ip1->meta.inum > ip2->meta.inum)
55                 return(1);
56         return(0);
57 }
58
59 static __inline
60 void
61 hammer2_knote(struct vnode *vp, int flags)
62 {
63         if (flags)
64                 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
65 }
66
67 /*
68  * Caller holds pmp->list_spin and the inode should be locked.  Merge ip
69  * with the specified depend.
70  *
71  * If the ip is on SYNCQ it stays there and (void *)-1 is returned, indicating
72  * that successive calls must ensure the ip is on a pass2 depend (or they are
73  * all SYNCQ).  If the passed-in depend is not NULL and not (void *)-1 then
74  * we can set pass2 on it and return.
75  *
76  * If the ip is not on SYNCQ it is merged with the passed-in depend, creating
77  * a self-depend if necessary, and depend->pass2 is set according
78  * to the PASS2 flag.  SIDEQ is set.
79  */
80 static __noinline
81 hammer2_depend_t *
82 hammer2_inode_setdepend_locked(hammer2_inode_t *ip, hammer2_depend_t *depend)
83 {
84         hammer2_pfs_t *pmp = ip->pmp;
85         hammer2_depend_t *dtmp;
86         hammer2_inode_t *iptmp;
87
88         /*
89          * If ip is SYNCQ its entry is used for the syncq list and it will
90          * no longer be associated with a dependency.  Merging this status
91          * with a passed-in depend implies PASS2.
92          */
93         if (ip->flags & HAMMER2_INODE_SYNCQ) {
94                 if (depend == (void *)-1 ||
95                     depend == NULL) {
96                         return ((void *)-1);
97                 }
98                 depend->pass2 = 1;
99                 hammer2_trans_setflags(pmp, HAMMER2_TRANS_RESCAN);
100
101                 return depend;
102         }
103
104         /*
105          * If ip is already SIDEQ, merge ip->depend into the passed-in depend.
106          * If it is not, associate the ip with the passed-in depend, creating
107          * a single-entry dependency using depend_static if necessary.
108          *
109          * NOTE: The use of ip->depend_static always requires that the
110          *       specific ip containing the structure is part of that
111          *       particular depend_static's dependency group.
112          */
113         if (ip->flags & HAMMER2_INODE_SIDEQ) {
114                 /*
115                  * Merge ip->depend with the passed-in depend.  If the
116                  * passed-in depend is not a special case, all ips associated
117                  * with ip->depend (including the original ip) must be moved
118                  * to the passed-in depend.
119                  */
120                 if (depend == NULL) {
121                         depend = ip->depend;
122                 } else if (depend == (void *)-1) {
123                         depend = ip->depend;
124                         depend->pass2 = 1;
125                 } else if (depend != ip->depend) {
126 #ifdef INVARIANTS
127                         int sanitychk = 0;
128 #endif
129                         dtmp = ip->depend;
130                         while ((iptmp = TAILQ_FIRST(&dtmp->sideq)) != NULL) {
131 #ifdef INVARIANTS
132                                 if (iptmp == ip)
133                                         sanitychk = 1;
134 #endif
135                                 TAILQ_REMOVE(&dtmp->sideq, iptmp, entry);
136                                 TAILQ_INSERT_TAIL(&depend->sideq, iptmp, entry);
137                                 iptmp->depend = depend;
138                         }
139                         KKASSERT(sanitychk == 1);
140                         depend->count += dtmp->count;
141                         depend->pass2 |= dtmp->pass2;
142                         TAILQ_REMOVE(&pmp->depq, dtmp, entry);
143                         dtmp->count = 0;
144                         dtmp->pass2 = 0;
145                 }
146         } else {
147                 /*
148                  * Add ip to the sideq, creating a self-dependency if
149                  * necessary.
150                  */
151                 hammer2_inode_ref(ip);
152                 atomic_set_int(&ip->flags, HAMMER2_INODE_SIDEQ);
153                 if (depend == NULL) {
154                         depend = &ip->depend_static;
155                         TAILQ_INSERT_TAIL(&pmp->depq, depend, entry);
156                 } else if (depend == (void *)-1) {
157                         depend = &ip->depend_static;
158                         depend->pass2 = 1;
159                         TAILQ_INSERT_TAIL(&pmp->depq, depend, entry);
160                 } /* else add ip to passed-in depend */
161                 TAILQ_INSERT_TAIL(&depend->sideq, ip, entry);
162                 ip->depend = depend;
163                 ++depend->count;
164                 ++pmp->sideq_count;
165         }
166
167         if (ip->flags & HAMMER2_INODE_SYNCQ_PASS2)
168                 depend->pass2 = 1;
169         if (depend->pass2)
170                 hammer2_trans_setflags(pmp, HAMMER2_TRANS_RESCAN);
171
172         return depend;
173 }
174
175 /*
176  * Put a solo inode on the SIDEQ (meaning that its dirty).  This can also
177  * occur from inode_lock4() and inode_depend().
178  *
179  * Caller must pass-in a locked inode.
180  */
181 void
182 hammer2_inode_delayed_sideq(hammer2_inode_t *ip)
183 {
184         hammer2_pfs_t *pmp = ip->pmp;
185
186         /*
187          * Optimize case to avoid pmp spinlock.
188          */
189         if ((ip->flags & (HAMMER2_INODE_SYNCQ | HAMMER2_INODE_SIDEQ)) == 0) {
190                 hammer2_spin_ex(&pmp->list_spin);
191                 hammer2_inode_setdepend_locked(ip, NULL);
192                 hammer2_spin_unex(&pmp->list_spin);
193         }
194 }
195
196 /*
197  * Lock an inode, with SYNCQ semantics.
198  *
199  * HAMMER2 offers shared and exclusive locks on inodes.  Pass a mask of
200  * flags for options:
201  *
202  *      - pass HAMMER2_RESOLVE_SHARED if a shared lock is desired.  The
203  *        inode locking function will automatically set the RDONLY flag.
204  *        shared locks are not subject to SYNCQ semantics, exclusive locks
205  *        are.
206  *
207  *      - pass HAMMER2_RESOLVE_ALWAYS if you need the inode's meta-data.
208  *        Most front-end inode locks do.
209  *
210  *      - pass HAMMER2_RESOLVE_NEVER if you do not want to require that
211  *        the inode data be resolved.  This is used by the syncthr because
212  *        it can run on an unresolved/out-of-sync cluster, and also by the
213  *        vnode reclamation code to avoid unnecessary I/O (particularly when
214  *        disposing of hundreds of thousands of cached vnodes).
215  *
216  * This function, along with lock4, has SYNCQ semantics.  If the inode being
217  * locked is on the SYNCQ, that is it has been staged by the syncer, we must
218  * block until the operation is complete (even if we can lock the inode).  In
219  * order to reduce the stall time, we re-order the inode to the front of the
220  * pmp->syncq prior to blocking.  This reordering VERY significantly improves
221  * performance.
222  *
223  * The inode locking function locks the inode itself, resolves any stale
224  * chains in the inode's cluster, and allocates a fresh copy of the
225  * cluster with 1 ref and all the underlying chains locked.
226  *
227  * ip->cluster will be stable while the inode is locked.
228  *
229  * NOTE: We don't combine the inode/chain lock because putting away an
230  *       inode would otherwise confuse multiple lock holders of the inode.
231  */
232 void
233 hammer2_inode_lock(hammer2_inode_t *ip, int how)
234 {
235         hammer2_pfs_t *pmp;
236
237         hammer2_inode_ref(ip);
238         pmp = ip->pmp;
239
240         /* 
241          * Inode structure mutex - Shared lock
242          */
243         if (how & HAMMER2_RESOLVE_SHARED) {
244                 hammer2_mtx_sh(&ip->lock);
245                 return;
246         }
247
248         /*
249          * Inode structure mutex - Exclusive lock
250          *
251          * An exclusive lock (if not recursive) must wait for inodes on
252          * SYNCQ to flush first, to ensure that meta-data dependencies such
253          * as the nlink count and related directory entries are not split
254          * across flushes.
255          *
256          * If the vnode is locked by the current thread it must be unlocked
257          * across the tsleep() to avoid a deadlock.
258          */
259         hammer2_mtx_ex(&ip->lock);
260         if (hammer2_mtx_refs(&ip->lock) > 1)
261                 return;
262         while ((ip->flags & HAMMER2_INODE_SYNCQ) && pmp) {
263                 hammer2_spin_ex(&pmp->list_spin);
264                 if (ip->flags & HAMMER2_INODE_SYNCQ) {
265                         tsleep_interlock(&ip->flags, 0);
266                         atomic_set_int(&ip->flags, HAMMER2_INODE_SYNCQ_WAKEUP);
267                         TAILQ_REMOVE(&pmp->syncq, ip, entry);
268                         TAILQ_INSERT_HEAD(&pmp->syncq, ip, entry);
269                         hammer2_spin_unex(&pmp->list_spin);
270                         hammer2_mtx_unlock(&ip->lock);
271                         tsleep(&ip->flags, PINTERLOCKED, "h2sync", 0);
272                         hammer2_mtx_ex(&ip->lock);
273                         continue;
274                 }
275                 hammer2_spin_unex(&pmp->list_spin);
276                 break;
277         }
278 }
279
280 /*
281  * Exclusively lock up to four inodes, in order, with SYNCQ semantics.
282  * ip1 and ip2 must not be NULL.  ip3 and ip4 may be NULL, but if ip3 is
283  * NULL then ip4 must also be NULL.
284  *
285  * This creates a dependency between up to four inodes.
286  */
287 void
288 hammer2_inode_lock4(hammer2_inode_t *ip1, hammer2_inode_t *ip2,
289                     hammer2_inode_t *ip3, hammer2_inode_t *ip4)
290 {
291         hammer2_inode_t *ips[4];
292         hammer2_inode_t *iptmp;
293         hammer2_inode_t *ipslp;
294         hammer2_depend_t *depend;
295         hammer2_pfs_t *pmp;
296         size_t count;
297         size_t i;
298
299         pmp = ip1->pmp;                 /* may be NULL */
300         KKASSERT(pmp == ip2->pmp);
301
302         ips[0] = ip1;
303         ips[1] = ip2;
304         if (ip3 == NULL) {
305                 count = 2;
306         } else if (ip4 == NULL) {
307                 count = 3;
308                 ips[2] = ip3;
309                 KKASSERT(pmp == ip3->pmp);
310         } else {
311                 count = 4;
312                 ips[2] = ip3;
313                 ips[3] = ip4;
314                 KKASSERT(pmp == ip3->pmp);
315                 KKASSERT(pmp == ip4->pmp);
316         }
317
318         for (i = 0; i < count; ++i)
319                 hammer2_inode_ref(ips[i]);
320
321 restart:
322         /*
323          * Lock the inodes in order
324          */
325         for (i = 0; i < count; ++i) {
326                 hammer2_mtx_ex(&ips[i]->lock);
327         }
328
329         /*
330          * Associate dependencies, record the first inode found on SYNCQ
331          * (operation is allowed to proceed for inodes on PASS2) for our
332          * sleep operation, this inode is theoretically the last one sync'd
333          * in the sequence.
334          *
335          * All inodes found on SYNCQ are moved to the head of the syncq
336          * to reduce stalls.
337          */
338         hammer2_spin_ex(&pmp->list_spin);
339         depend = NULL;
340         ipslp = NULL;
341         for (i = 0; i < count; ++i) {
342                 iptmp = ips[i];
343                 depend = hammer2_inode_setdepend_locked(iptmp, depend);
344                 if (iptmp->flags & HAMMER2_INODE_SYNCQ) {
345                         TAILQ_REMOVE(&pmp->syncq, iptmp, entry);
346                         TAILQ_INSERT_HEAD(&pmp->syncq, iptmp, entry);
347                         if (ipslp == NULL)
348                                 ipslp = iptmp;
349                 }
350         }
351         hammer2_spin_unex(&pmp->list_spin);
352
353         /*
354          * Block and retry if any of the inodes are on SYNCQ.  It is
355          * important that we allow the operation to proceed in the
356          * PASS2 case, to avoid deadlocking against the vnode.
357          */
358         if (ipslp) {
359                 for (i = 0; i < count; ++i)
360                         hammer2_mtx_unlock(&ips[i]->lock);
361                 tsleep(&ipslp->flags, 0, "h2sync", 2);
362                 goto restart;
363         }
364 }
365
366 /*
367  * Release an inode lock.  If another thread is blocked on SYNCQ_WAKEUP
368  * we wake them up.
369  */
370 void
371 hammer2_inode_unlock(hammer2_inode_t *ip)
372 {
373         if (ip->flags & HAMMER2_INODE_SYNCQ_WAKEUP) {
374                 atomic_clear_int(&ip->flags, HAMMER2_INODE_SYNCQ_WAKEUP);
375                 hammer2_mtx_unlock(&ip->lock);
376                 wakeup(&ip->flags);
377         } else {
378                 hammer2_mtx_unlock(&ip->lock);
379         }
380         hammer2_inode_drop(ip);
381 }
382
383 /*
384  * If either ip1 or ip2 have been tapped by the syncer, make sure that both
385  * are.  This ensure that dependencies (e.g. dirent-v-inode) are synced
386  * together.  For dirent-v-inode depends, pass the dirent as ip1.
387  *
388  * If neither ip1 or ip2 have been tapped by the syncer, merge them into a
389  * single dependency.  Dependencies are entered into pmp->depq.  This
390  * effectively flags the inodes SIDEQ.
391  *
392  * Both ip1 and ip2 must be locked by the caller.  This also ensures
393  * that we can't race the end of the syncer's queue run.
394  */
395 void
396 hammer2_inode_depend(hammer2_inode_t *ip1, hammer2_inode_t *ip2)
397 {
398         hammer2_pfs_t *pmp;
399         hammer2_depend_t *depend;
400
401         pmp = ip1->pmp;
402         hammer2_spin_ex(&pmp->list_spin);
403         depend = hammer2_inode_setdepend_locked(ip1, NULL);
404         depend = hammer2_inode_setdepend_locked(ip2, depend);
405         hammer2_spin_unex(&pmp->list_spin);
406 }
407
408 /*
409  * Select a chain out of an inode's cluster and lock it.
410  *
411  * The inode does not have to be locked.
412  */
413 hammer2_chain_t *
414 hammer2_inode_chain(hammer2_inode_t *ip, int clindex, int how)
415 {
416         hammer2_chain_t *chain;
417         hammer2_cluster_t *cluster;
418
419         hammer2_spin_sh(&ip->cluster_spin);
420         cluster = &ip->cluster;
421         if (clindex >= cluster->nchains)
422                 chain = NULL;
423         else
424                 chain = cluster->array[clindex].chain;
425         if (chain) {
426                 hammer2_chain_ref(chain);
427                 hammer2_spin_unsh(&ip->cluster_spin);
428                 hammer2_chain_lock(chain, how);
429         } else {
430                 hammer2_spin_unsh(&ip->cluster_spin);
431         }
432         return chain;
433 }
434
435 hammer2_chain_t *
436 hammer2_inode_chain_and_parent(hammer2_inode_t *ip, int clindex,
437                                hammer2_chain_t **parentp, int how)
438 {
439         hammer2_chain_t *chain;
440         hammer2_chain_t *parent;
441
442         for (;;) {
443                 hammer2_spin_sh(&ip->cluster_spin);
444                 if (clindex >= ip->cluster.nchains)
445                         chain = NULL;
446                 else
447                         chain = ip->cluster.array[clindex].chain;
448                 if (chain) {
449                         hammer2_chain_ref(chain);
450                         hammer2_spin_unsh(&ip->cluster_spin);
451                         hammer2_chain_lock(chain, how);
452                 } else {
453                         hammer2_spin_unsh(&ip->cluster_spin);
454                 }
455
456                 /*
457                  * Get parent, lock order must be (parent, chain).
458                  */
459                 parent = chain->parent;
460                 if (parent) {
461                         hammer2_chain_ref(parent);
462                         hammer2_chain_unlock(chain);
463                         hammer2_chain_lock(parent, how);
464                         hammer2_chain_lock(chain, how);
465                 }
466                 if (ip->cluster.array[clindex].chain == chain &&
467                     chain->parent == parent) {
468                         break;
469                 }
470
471                 /*
472                  * Retry
473                  */
474                 hammer2_chain_unlock(chain);
475                 hammer2_chain_drop(chain);
476                 if (parent) {
477                         hammer2_chain_unlock(parent);
478                         hammer2_chain_drop(parent);
479                 }
480         }
481         *parentp = parent;
482
483         return chain;
484 }
485
486 /*
487  * Temporarily release a lock held shared or exclusive.  Caller must
488  * hold the lock shared or exclusive on call and lock will be released
489  * on return.
490  *
491  * Restore a lock that was temporarily released.
492  */
493 hammer2_mtx_state_t
494 hammer2_inode_lock_temp_release(hammer2_inode_t *ip)
495 {
496         return hammer2_mtx_temp_release(&ip->lock);
497 }
498
499 void
500 hammer2_inode_lock_temp_restore(hammer2_inode_t *ip, hammer2_mtx_state_t ostate)
501 {
502         hammer2_mtx_temp_restore(&ip->lock, ostate);
503 }
504
505 /*
506  * Upgrade a shared inode lock to exclusive and return.  If the inode lock
507  * is already held exclusively this is a NOP.
508  *
509  * The caller MUST hold the inode lock either shared or exclusive on call
510  * and will own the lock exclusively on return.
511  *
512  * Returns non-zero if the lock was already exclusive prior to the upgrade.
513  */
514 int
515 hammer2_inode_lock_upgrade(hammer2_inode_t *ip)
516 {
517         int wasexclusive;
518
519         if (mtx_islocked_ex(&ip->lock)) {
520                 wasexclusive = 1;
521         } else {
522                 hammer2_mtx_unlock(&ip->lock);
523                 hammer2_mtx_ex(&ip->lock);
524                 wasexclusive = 0;
525         }
526         return wasexclusive;
527 }
528
529 /*
530  * Downgrade an inode lock from exclusive to shared only if the inode
531  * lock was previously shared.  If the inode lock was previously exclusive,
532  * this is a NOP.
533  */
534 void
535 hammer2_inode_lock_downgrade(hammer2_inode_t *ip, int wasexclusive)
536 {
537         if (wasexclusive == 0)
538                 hammer2_mtx_downgrade(&ip->lock);
539 }
540
541 /*
542  * Lookup an inode by inode number
543  */
544 hammer2_inode_t *
545 hammer2_inode_lookup(hammer2_pfs_t *pmp, hammer2_tid_t inum)
546 {
547         hammer2_inode_t *ip;
548
549         KKASSERT(pmp);
550         if (pmp->spmp_hmp) {
551                 ip = NULL;
552         } else {
553                 hammer2_spin_ex(&pmp->inum_spin);
554                 ip = RB_LOOKUP(hammer2_inode_tree, &pmp->inum_tree, inum);
555                 if (ip)
556                         hammer2_inode_ref(ip);
557                 hammer2_spin_unex(&pmp->inum_spin);
558         }
559         return(ip);
560 }
561
562 /*
563  * Adding a ref to an inode is only legal if the inode already has at least
564  * one ref.
565  *
566  * (can be called with spinlock held)
567  */
568 void
569 hammer2_inode_ref(hammer2_inode_t *ip)
570 {
571         atomic_add_int(&ip->refs, 1);
572         if (hammer2_debug & 0x80000) {
573                 kprintf("INODE+1 %p (%d->%d)\n", ip, ip->refs - 1, ip->refs);
574                 print_backtrace(8);
575         }
576 }
577
578 /*
579  * Drop an inode reference, freeing the inode when the last reference goes
580  * away.
581  */
582 void
583 hammer2_inode_drop(hammer2_inode_t *ip)
584 {
585         hammer2_pfs_t *pmp;
586         u_int refs;
587
588         while (ip) {
589                 if (hammer2_debug & 0x80000) {
590                         kprintf("INODE-1 %p (%d->%d)\n",
591                                 ip, ip->refs, ip->refs - 1);
592                         print_backtrace(8);
593                 }
594                 refs = ip->refs;
595                 cpu_ccfence();
596                 if (refs == 1) {
597                         /*
598                          * Transition to zero, must interlock with
599                          * the inode inumber lookup tree (if applicable).
600                          * It should not be possible for anyone to race
601                          * the transition to 0.
602                          */
603                         pmp = ip->pmp;
604                         KKASSERT(pmp);
605                         hammer2_spin_ex(&pmp->inum_spin);
606
607                         if (atomic_cmpset_int(&ip->refs, 1, 0)) {
608                                 KKASSERT(hammer2_mtx_refs(&ip->lock) == 0);
609                                 if (ip->flags & HAMMER2_INODE_ONRBTREE) {
610                                         atomic_clear_int(&ip->flags,
611                                                      HAMMER2_INODE_ONRBTREE);
612                                         RB_REMOVE(hammer2_inode_tree,
613                                                   &pmp->inum_tree, ip);
614                                         --pmp->inum_count;
615                                 }
616                                 hammer2_spin_unex(&pmp->inum_spin);
617
618                                 ip->pmp = NULL;
619
620                                 /*
621                                  * Cleaning out ip->cluster isn't entirely
622                                  * trivial.
623                                  */
624                                 hammer2_inode_repoint(ip, NULL, NULL);
625
626                                 kfree(ip, pmp->minode);
627                                 atomic_add_long(&pmp->inmem_inodes, -1);
628                                 ip = NULL;      /* will terminate loop */
629                         } else {
630                                 hammer2_spin_unex(&ip->pmp->inum_spin);
631                         }
632                 } else {
633                         /*
634                          * Non zero transition
635                          */
636                         if (atomic_cmpset_int(&ip->refs, refs, refs - 1))
637                                 break;
638                 }
639         }
640 }
641
642 /*
643  * Get the vnode associated with the given inode, allocating the vnode if
644  * necessary.  The vnode will be returned exclusively locked.
645  *
646  * *errorp is set to a UNIX error, not a HAMMER2 error.
647  *
648  * The caller must lock the inode (shared or exclusive).
649  *
650  * Great care must be taken to avoid deadlocks and vnode acquisition/reclaim
651  * races.
652  */
653 struct vnode *
654 hammer2_igetv(hammer2_inode_t *ip, int *errorp)
655 {
656         hammer2_pfs_t *pmp;
657         struct vnode *vp;
658
659         pmp = ip->pmp;
660         KKASSERT(pmp != NULL);
661         *errorp = 0;
662
663         for (;;) {
664                 /*
665                  * Attempt to reuse an existing vnode assignment.  It is
666                  * possible to race a reclaim so the vget() may fail.  The
667                  * inode must be unlocked during the vget() to avoid a
668                  * deadlock against a reclaim.
669                  */
670                 int wasexclusive;
671
672                 vp = ip->vp;
673                 if (vp) {
674                         /*
675                          * Inode must be unlocked during the vget() to avoid
676                          * possible deadlocks, but leave the ip ref intact.
677                          *
678                          * vnode is held to prevent destruction during the
679                          * vget().  The vget() can still fail if we lost
680                          * a reclaim race on the vnode.
681                          */
682                         hammer2_mtx_state_t ostate;
683
684                         vhold(vp);
685                         ostate = hammer2_inode_lock_temp_release(ip);
686                         if (vget(vp, LK_EXCLUSIVE)) {
687                                 vdrop(vp);
688                                 hammer2_inode_lock_temp_restore(ip, ostate);
689                                 continue;
690                         }
691                         hammer2_inode_lock_temp_restore(ip, ostate);
692                         vdrop(vp);
693                         /* vp still locked and ref from vget */
694                         if (ip->vp != vp) {
695                                 kprintf("hammer2: igetv race %p/%p\n",
696                                         ip->vp, vp);
697                                 vput(vp);
698                                 continue;
699                         }
700                         *errorp = 0;
701                         break;
702                 }
703
704                 /*
705                  * No vnode exists, allocate a new vnode.  Beware of
706                  * allocation races.  This function will return an
707                  * exclusively locked and referenced vnode.
708                  */
709                 *errorp = getnewvnode(VT_HAMMER2, pmp->mp, &vp, 0, 0);
710                 if (*errorp) {
711                         kprintf("hammer2: igetv getnewvnode failed %d\n",
712                                 *errorp);
713                         vp = NULL;
714                         break;
715                 }
716
717                 /*
718                  * Lock the inode and check for an allocation race.
719                  */
720                 wasexclusive = hammer2_inode_lock_upgrade(ip);
721                 if (ip->vp != NULL) {
722                         vp->v_type = VBAD;
723                         vx_put(vp);
724                         hammer2_inode_lock_downgrade(ip, wasexclusive);
725                         continue;
726                 }
727
728                 switch (ip->meta.type) {
729                 case HAMMER2_OBJTYPE_DIRECTORY:
730                         vp->v_type = VDIR;
731                         break;
732                 case HAMMER2_OBJTYPE_REGFILE:
733                         /*
734                          * Regular file must use buffer cache I/O
735                          * (VKVABIO cpu sync semantics supported)
736                          */
737                         vp->v_type = VREG;
738                         vsetflags(vp, VKVABIO);
739                         vinitvmio(vp, ip->meta.size,
740                                   HAMMER2_LBUFSIZE,
741                                   (int)ip->meta.size & HAMMER2_LBUFMASK);
742                         break;
743                 case HAMMER2_OBJTYPE_SOFTLINK:
744                         /*
745                          * XXX for now we are using the generic file_read
746                          * and file_write code so we need a buffer cache
747                          * association.
748                          *
749                          * (VKVABIO cpu sync semantics supported)
750                          */
751                         vp->v_type = VLNK;
752                         vsetflags(vp, VKVABIO);
753                         vinitvmio(vp, ip->meta.size,
754                                   HAMMER2_LBUFSIZE,
755                                   (int)ip->meta.size & HAMMER2_LBUFMASK);
756                         break;
757                 case HAMMER2_OBJTYPE_CDEV:
758                         vp->v_type = VCHR;
759                         /* fall through */
760                 case HAMMER2_OBJTYPE_BDEV:
761                         vp->v_ops = &pmp->mp->mnt_vn_spec_ops;
762                         if (ip->meta.type != HAMMER2_OBJTYPE_CDEV)
763                                 vp->v_type = VBLK;
764                         addaliasu(vp,
765                                   ip->meta.rmajor,
766                                   ip->meta.rminor);
767                         break;
768                 case HAMMER2_OBJTYPE_FIFO:
769                         vp->v_type = VFIFO;
770                         vp->v_ops = &pmp->mp->mnt_vn_fifo_ops;
771                         break;
772                 case HAMMER2_OBJTYPE_SOCKET:
773                         vp->v_type = VSOCK;
774                         break;
775                 default:
776                         panic("hammer2: unhandled objtype %d",
777                               ip->meta.type);
778                         break;
779                 }
780
781                 if (ip == pmp->iroot)
782                         vsetflags(vp, VROOT);
783
784                 vp->v_data = ip;
785                 ip->vp = vp;
786                 hammer2_inode_ref(ip);          /* vp association */
787                 hammer2_inode_lock_downgrade(ip, wasexclusive);
788                 break;
789         }
790
791         /*
792          * Return non-NULL vp and *errorp == 0, or NULL vp and *errorp != 0.
793          */
794         if (hammer2_debug & 0x0002) {
795                 kprintf("igetv vp %p refs 0x%08x aux 0x%08x\n",
796                         vp, vp->v_refcnt, vp->v_auxrefs);
797         }
798         return (vp);
799 }
800
801 /*
802  * Returns the inode associated with the passed-in cluster, allocating a new
803  * hammer2_inode structure if necessary, then synchronizing it to the passed
804  * xop cluster.  When synchronizing, if idx >= 0, only cluster index (idx)
805  * is synchronized.  Otherwise the whole cluster is synchronized.  inum will
806  * be extracted from the passed-in xop and the inum argument will be ignored.
807  *
808  * If xop is passed as NULL then a new hammer2_inode is allocated with the
809  * specified inum, and returned.   For normal inodes, the inode will be
810  * indexed in memory and if it already exists the existing ip will be
811  * returned instead of allocating a new one.  The superroot and PFS inodes
812  * are not indexed in memory.
813  *
814  * The passed-in cluster must be locked and will remain locked on return.
815  * The returned inode will be locked and the caller may dispose of both
816  * via hammer2_inode_unlock() + hammer2_inode_drop().  However, if the caller
817  * needs to resolve a hardlink it must ref/unlock/relock/drop the inode.
818  *
819  * The hammer2_inode structure regulates the interface between the high level
820  * kernel VNOPS API and the filesystem backend (the chains).
821  *
822  * On return the inode is locked with the supplied cluster.
823  */
824 hammer2_inode_t *
825 hammer2_inode_get(hammer2_pfs_t *pmp, hammer2_xop_head_t *xop,
826                   hammer2_tid_t inum, int idx)
827 {
828         hammer2_inode_t *nip;
829         const hammer2_inode_data_t *iptmp;
830         const hammer2_inode_data_t *nipdata;
831
832         KKASSERT(xop == NULL ||
833                  hammer2_cluster_type(&xop->cluster) ==
834                  HAMMER2_BREF_TYPE_INODE);
835         KKASSERT(pmp);
836
837         /*
838          * Interlocked lookup/ref of the inode.  This code is only needed
839          * when looking up inodes with nlinks != 0 (TODO: optimize out
840          * otherwise and test for duplicates).
841          *
842          * Cluster can be NULL during the initial pfs allocation.
843          */
844         if (xop) {
845                 iptmp = &hammer2_xop_gdata(xop)->ipdata;
846                 inum = iptmp->meta.inum;
847                 hammer2_xop_pdata(xop);
848         }
849 again:
850         nip = hammer2_inode_lookup(pmp, inum);
851         if (nip) {
852                 /*
853                  * Handle SMP race (not applicable to the super-root spmp
854                  * which can't index inodes due to duplicative inode numbers).
855                  */
856                 hammer2_mtx_ex(&nip->lock);
857                 if (pmp->spmp_hmp == NULL &&
858                     (nip->flags & HAMMER2_INODE_ONRBTREE) == 0) {
859                         hammer2_mtx_unlock(&nip->lock);
860                         hammer2_inode_drop(nip);
861                         goto again;
862                 }
863                 if (xop) {
864                         if (idx >= 0)
865                                 hammer2_inode_repoint_one(nip, &xop->cluster,
866                                                           idx);
867                         else
868                                 hammer2_inode_repoint(nip, NULL, &xop->cluster);
869                 }
870                 return nip;
871         }
872
873         /*
874          * We couldn't find the inode number, create a new inode and try to
875          * insert it, handle insertion races.
876          */
877         nip = kmalloc(sizeof(*nip), pmp->minode, M_WAITOK | M_ZERO);
878         spin_init(&nip->cluster_spin, "h2clspin");
879         atomic_add_long(&pmp->inmem_inodes, 1);
880         if (pmp->spmp_hmp)
881                 nip->flags = HAMMER2_INODE_SROOT;
882
883         /*
884          * Initialize nip's cluster.  A cluster is provided for normal
885          * inodes but typically not for the super-root or PFS inodes.
886          */
887         nip->cluster.refs = 1;
888         nip->cluster.pmp = pmp;
889         nip->cluster.flags |= HAMMER2_CLUSTER_INODE;
890         if (xop) {
891                 nipdata = &hammer2_xop_gdata(xop)->ipdata;
892                 nip->meta = nipdata->meta;
893                 hammer2_xop_pdata(xop);
894                 atomic_set_int(&nip->flags, HAMMER2_INODE_METAGOOD);
895                 hammer2_inode_repoint(nip, NULL, &xop->cluster);
896         } else {
897                 nip->meta.inum = inum;          /* PFS inum is always 1 XXX */
898                 /* mtime will be updated when a cluster is available */
899                 atomic_set_int(&nip->flags, HAMMER2_INODE_METAGOOD);    /*XXX*/
900         }
901
902         nip->pmp = pmp;
903
904         /*
905          * ref and lock on nip gives it state compatible to after a
906          * hammer2_inode_lock() call.
907          */
908         nip->refs = 1;
909         hammer2_mtx_init(&nip->lock, "h2inode");
910         hammer2_mtx_init(&nip->truncate_lock, "h2trunc");
911         hammer2_mtx_ex(&nip->lock);
912         TAILQ_INIT(&nip->depend_static.sideq);
913         /* combination of thread lock and chain lock == inode lock */
914
915         /*
916          * Attempt to add the inode.  If it fails we raced another inode
917          * get.  Undo all the work and try again.
918          */
919         if (pmp->spmp_hmp == NULL) {
920                 hammer2_spin_ex(&pmp->inum_spin);
921                 if (RB_INSERT(hammer2_inode_tree, &pmp->inum_tree, nip)) {
922                         hammer2_spin_unex(&pmp->inum_spin);
923                         hammer2_mtx_unlock(&nip->lock);
924                         hammer2_inode_drop(nip);
925                         goto again;
926                 }
927                 atomic_set_int(&nip->flags, HAMMER2_INODE_ONRBTREE);
928                 ++pmp->inum_count;
929                 hammer2_spin_unex(&pmp->inum_spin);
930         }
931         return (nip);
932 }
933
934 /*
935  * Create a PFS inode under the superroot.  This function will create the
936  * inode, its media chains, and also insert it into the media.
937  *
938  * Caller must be in a flush transaction because we are inserting the inode
939  * onto the media.
940  */
941 hammer2_inode_t *
942 hammer2_inode_create_pfs(hammer2_pfs_t *spmp,
943                      const uint8_t *name, size_t name_len,
944                      int *errorp)
945 {
946         hammer2_xop_create_t *xop;
947         hammer2_inode_t *pip;
948         hammer2_inode_t *nip;
949         int error;
950         uuid_t pip_uid;
951         uuid_t pip_gid;
952         uint32_t pip_mode;
953         uint8_t pip_comp_algo;
954         uint8_t pip_check_algo;
955         hammer2_tid_t pip_inum;
956         hammer2_key_t lhc;
957
958         pip = spmp->iroot;
959         nip = NULL;
960
961         lhc = hammer2_dirhash(name, name_len);
962         *errorp = 0;
963
964         /*
965          * Locate the inode or indirect block to create the new
966          * entry in.  At the same time check for key collisions
967          * and iterate until we don't get one.
968          *
969          * Lock the directory exclusively for now to guarantee that
970          * we can find an unused lhc for the name.  Due to collisions,
971          * two different creates can end up with the same lhc so we
972          * cannot depend on the OS to prevent the collision.
973          */
974         hammer2_inode_lock(pip, 0);
975
976         pip_uid = pip->meta.uid;
977         pip_gid = pip->meta.gid;
978         pip_mode = pip->meta.mode;
979         pip_comp_algo = pip->meta.comp_algo;
980         pip_check_algo = pip->meta.check_algo;
981         pip_inum = (pip == pip->pmp->iroot) ? 1 : pip->meta.inum;
982
983         /*
984          * Locate an unused key in the collision space.
985          */
986         {
987                 hammer2_xop_scanlhc_t *sxop;
988                 hammer2_key_t lhcbase;
989
990                 lhcbase = lhc;
991                 sxop = hammer2_xop_alloc(pip, HAMMER2_XOP_MODIFYING);
992                 sxop->lhc = lhc;
993                 hammer2_xop_start(&sxop->head, &hammer2_scanlhc_desc);
994                 while ((error = hammer2_xop_collect(&sxop->head, 0)) == 0) {
995                         if (lhc != sxop->head.cluster.focus->bref.key)
996                                 break;
997                         ++lhc;
998                 }
999                 hammer2_xop_retire(&sxop->head, HAMMER2_XOPMASK_VOP);
1000
1001                 if (error) {
1002                         if (error != HAMMER2_ERROR_ENOENT)
1003                                 goto done2;
1004                         ++lhc;
1005                         error = 0;
1006                 }
1007                 if ((lhcbase ^ lhc) & ~HAMMER2_DIRHASH_LOMASK) {
1008                         error = HAMMER2_ERROR_ENOSPC;
1009                         goto done2;
1010                 }
1011         }
1012
1013         /*
1014          * Create the inode with the lhc as the key.
1015          */
1016         xop = hammer2_xop_alloc(pip, HAMMER2_XOP_MODIFYING);
1017         xop->lhc = lhc;
1018         xop->flags = HAMMER2_INSERT_PFSROOT;
1019         bzero(&xop->meta, sizeof(xop->meta));
1020
1021         xop->meta.type = HAMMER2_OBJTYPE_DIRECTORY;
1022         xop->meta.inum = 1;
1023         xop->meta.iparent = pip_inum;
1024
1025         /* Inherit parent's inode compression mode. */
1026         xop->meta.comp_algo = pip_comp_algo;
1027         xop->meta.check_algo = pip_check_algo;
1028         xop->meta.version = HAMMER2_INODE_VERSION_ONE;
1029         hammer2_update_time(&xop->meta.ctime);
1030         xop->meta.mtime = xop->meta.ctime;
1031         xop->meta.mode = 0755;
1032         xop->meta.nlinks = 1;
1033
1034         /*
1035          * Regular files and softlinks allow a small amount of data to be
1036          * directly embedded in the inode.  This flag will be cleared if
1037          * the size is extended past the embedded limit.
1038          */
1039         if (xop->meta.type == HAMMER2_OBJTYPE_REGFILE ||
1040             xop->meta.type == HAMMER2_OBJTYPE_SOFTLINK) {
1041                 xop->meta.op_flags |= HAMMER2_OPFLAG_DIRECTDATA;
1042         }
1043         hammer2_xop_setname(&xop->head, name, name_len);
1044         xop->meta.name_len = name_len;
1045         xop->meta.name_key = lhc;
1046         KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
1047
1048         hammer2_xop_start(&xop->head, &hammer2_inode_create_desc);
1049
1050         error = hammer2_xop_collect(&xop->head, 0);
1051 #if INODE_DEBUG
1052         kprintf("CREATE INODE %*.*s\n",
1053                 (int)name_len, (int)name_len, name);
1054 #endif
1055
1056         if (error) {
1057                 *errorp = error;
1058                 goto done;
1059         }
1060
1061         /*
1062          * Set up the new inode if not a hardlink pointer.
1063          *
1064          * NOTE: *_get() integrates chain's lock into the inode lock.
1065          *
1066          * NOTE: Only one new inode can currently be created per
1067          *       transaction.  If the need arises we can adjust
1068          *       hammer2_trans_init() to allow more.
1069          *
1070          * NOTE: nipdata will have chain's blockset data.
1071          */
1072         nip = hammer2_inode_get(pip->pmp, &xop->head, -1, -1);
1073         nip->comp_heuristic = 0;
1074 done:
1075         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1076 done2:
1077         hammer2_inode_unlock(pip);
1078
1079         return (nip);
1080 }
1081
1082 /*
1083  * Create a new, normal inode.  This function will create the inode,
1084  * the media chains, but will not insert the chains onto the media topology
1085  * (doing so would require a flush transaction and cause long stalls).
1086  *
1087  * Caller must be in a normal transaction.
1088  */
1089 hammer2_inode_t *
1090 hammer2_inode_create_normal(hammer2_inode_t *pip,
1091                             struct vattr *vap, struct ucred *cred,
1092                             hammer2_key_t inum, int *errorp)
1093 {
1094         hammer2_xop_create_t *xop;
1095         hammer2_inode_t *dip;
1096         hammer2_inode_t *nip;
1097         int error;
1098         uid_t xuid;
1099         uuid_t pip_uid;
1100         uuid_t pip_gid;
1101         uint32_t pip_mode;
1102         uint8_t pip_comp_algo;
1103         uint8_t pip_check_algo;
1104         hammer2_tid_t pip_inum;
1105         uint8_t type;
1106
1107         dip = pip->pmp->iroot;
1108         KKASSERT(dip != NULL);
1109
1110         *errorp = 0;
1111
1112         /*hammer2_inode_lock(dip, 0);*/
1113
1114         pip_uid = pip->meta.uid;
1115         pip_gid = pip->meta.gid;
1116         pip_mode = pip->meta.mode;
1117         pip_comp_algo = pip->meta.comp_algo;
1118         pip_check_algo = pip->meta.check_algo;
1119         pip_inum = (pip == pip->pmp->iroot) ? 1 : pip->meta.inum;
1120
1121         /*
1122          * Create the in-memory hammer2_inode structure for the specified
1123          * inode.
1124          */
1125         nip = hammer2_inode_get(dip->pmp, NULL, inum, -1);
1126         nip->comp_heuristic = 0;
1127         KKASSERT((nip->flags & HAMMER2_INODE_CREATING) == 0 &&
1128                  nip->cluster.nchains == 0);
1129         atomic_set_int(&nip->flags, HAMMER2_INODE_CREATING);
1130
1131         /*
1132          * Setup the inode meta-data
1133          */
1134         nip->meta.type = hammer2_get_obj_type(vap->va_type);
1135
1136         switch (nip->meta.type) {
1137         case HAMMER2_OBJTYPE_CDEV:
1138         case HAMMER2_OBJTYPE_BDEV:
1139                 nip->meta.rmajor = vap->va_rmajor;
1140                 nip->meta.rminor = vap->va_rminor;
1141                 break;
1142         default:
1143                 break;
1144         }
1145         type = nip->meta.type;
1146
1147         KKASSERT(nip->meta.inum == inum);
1148         nip->meta.iparent = pip_inum;
1149         
1150         /* Inherit parent's inode compression mode. */
1151         nip->meta.comp_algo = pip_comp_algo;
1152         nip->meta.check_algo = pip_check_algo;
1153         nip->meta.version = HAMMER2_INODE_VERSION_ONE;
1154         hammer2_update_time(&nip->meta.ctime);
1155         nip->meta.mtime = nip->meta.ctime;
1156         nip->meta.mode = vap->va_mode;
1157         nip->meta.nlinks = 1;
1158
1159         xuid = hammer2_to_unix_xid(&pip_uid);
1160         xuid = vop_helper_create_uid(dip->pmp->mp, pip_mode,
1161                                      xuid, cred,
1162                                      &vap->va_mode);
1163         if (vap->va_vaflags & VA_UID_UUID_VALID)
1164                 nip->meta.uid = vap->va_uid_uuid;
1165         else if (vap->va_uid != (uid_t)VNOVAL)
1166                 hammer2_guid_to_uuid(&nip->meta.uid, vap->va_uid);
1167         else
1168                 hammer2_guid_to_uuid(&nip->meta.uid, xuid);
1169
1170         if (vap->va_vaflags & VA_GID_UUID_VALID)
1171                 nip->meta.gid = vap->va_gid_uuid;
1172         else if (vap->va_gid != (gid_t)VNOVAL)
1173                 hammer2_guid_to_uuid(&nip->meta.gid, vap->va_gid);
1174         else
1175                 nip->meta.gid = pip_gid;
1176
1177         /*
1178          * Regular files and softlinks allow a small amount of data to be
1179          * directly embedded in the inode.  This flag will be cleared if
1180          * the size is extended past the embedded limit.
1181          */
1182         if (nip->meta.type == HAMMER2_OBJTYPE_REGFILE ||
1183             nip->meta.type == HAMMER2_OBJTYPE_SOFTLINK) {
1184                 nip->meta.op_flags |= HAMMER2_OPFLAG_DIRECTDATA;
1185         }
1186
1187         /*
1188          * Create the inode using (inum) as the key.  Pass pip for
1189          * method inheritance.
1190          */
1191         xop = hammer2_xop_alloc(pip, HAMMER2_XOP_MODIFYING);
1192         xop->lhc = inum;
1193         xop->flags = 0;
1194         xop->meta = nip->meta;
1195         KKASSERT(vap);
1196
1197         xop->meta.name_len = hammer2_xop_setname_inum(&xop->head, inum);
1198         xop->meta.name_key = inum;
1199         nip->meta.name_len = xop->meta.name_len;
1200         nip->meta.name_key = xop->meta.name_key;
1201         hammer2_inode_modify(nip);
1202
1203         /*
1204          * Create the inode media chains but leave them detached.  We are
1205          * not in a flush transaction so we can't mess with media topology
1206          * above normal inodes (i.e. the index of the inodes themselves).
1207          *
1208          * We've already set the INODE_CREATING flag.  The inode's media
1209          * chains will be inserted onto the media topology on the next
1210          * filesystem sync.
1211          */
1212         hammer2_xop_start(&xop->head, &hammer2_inode_create_det_desc);
1213
1214         error = hammer2_xop_collect(&xop->head, 0);
1215 #if INODE_DEBUG
1216         kprintf("create inode type %d error %d\n", nip->meta.type, error);
1217 #endif
1218
1219         if (error) {
1220                 *errorp = error;
1221                 goto done;
1222         }
1223
1224         /*
1225          * Associate the media chains created by the backend with the
1226          * frontend inode.
1227          */
1228         hammer2_inode_repoint(nip, NULL, &xop->head.cluster);
1229 done:
1230         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1231         /*hammer2_inode_unlock(dip);*/
1232
1233         return (nip);
1234 }
1235
1236 /*
1237  * Create a directory entry under dip with the specified name, inode number,
1238  * and OBJTYPE (type).
1239  *
1240  * This returns a UNIX errno code, not a HAMMER2_ERROR_* code.
1241  *
1242  * Caller must hold dip locked.
1243  */
1244 int
1245 hammer2_dirent_create(hammer2_inode_t *dip, const char *name, size_t name_len,
1246                       hammer2_key_t inum, uint8_t type)
1247 {
1248         hammer2_xop_mkdirent_t *xop;
1249         hammer2_key_t lhc;
1250         int error;
1251
1252         lhc = 0;
1253         error = 0;
1254
1255         KKASSERT(name != NULL);
1256         lhc = hammer2_dirhash(name, name_len);
1257
1258         /*
1259          * Locate the inode or indirect block to create the new
1260          * entry in.  At the same time check for key collisions
1261          * and iterate until we don't get one.
1262          *
1263          * Lock the directory exclusively for now to guarantee that
1264          * we can find an unused lhc for the name.  Due to collisions,
1265          * two different creates can end up with the same lhc so we
1266          * cannot depend on the OS to prevent the collision.
1267          */
1268         hammer2_inode_modify(dip);
1269
1270         /*
1271          * If name specified, locate an unused key in the collision space.
1272          * Otherwise use the passed-in lhc directly.
1273          */
1274         {
1275                 hammer2_xop_scanlhc_t *sxop;
1276                 hammer2_key_t lhcbase;
1277
1278                 lhcbase = lhc;
1279                 sxop = hammer2_xop_alloc(dip, HAMMER2_XOP_MODIFYING);
1280                 sxop->lhc = lhc;
1281                 hammer2_xop_start(&sxop->head, &hammer2_scanlhc_desc);
1282                 while ((error = hammer2_xop_collect(&sxop->head, 0)) == 0) {
1283                         if (lhc != sxop->head.cluster.focus->bref.key)
1284                                 break;
1285                         ++lhc;
1286                 }
1287                 hammer2_xop_retire(&sxop->head, HAMMER2_XOPMASK_VOP);
1288
1289                 if (error) {
1290                         if (error != HAMMER2_ERROR_ENOENT)
1291                                 goto done2;
1292                         ++lhc;
1293                         error = 0;
1294                 }
1295                 if ((lhcbase ^ lhc) & ~HAMMER2_DIRHASH_LOMASK) {
1296                         error = HAMMER2_ERROR_ENOSPC;
1297                         goto done2;
1298                 }
1299         }
1300
1301         /*
1302          * Create the directory entry with the lhc as the key.
1303          */
1304         xop = hammer2_xop_alloc(dip, HAMMER2_XOP_MODIFYING);
1305         xop->lhc = lhc;
1306         bzero(&xop->dirent, sizeof(xop->dirent));
1307         xop->dirent.inum = inum;
1308         xop->dirent.type = type;
1309         xop->dirent.namlen = name_len;
1310
1311         KKASSERT(name_len < HAMMER2_INODE_MAXNAME);
1312         hammer2_xop_setname(&xop->head, name, name_len);
1313
1314         hammer2_xop_start(&xop->head, &hammer2_inode_mkdirent_desc);
1315
1316         error = hammer2_xop_collect(&xop->head, 0);
1317
1318         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1319 done2:
1320         error = hammer2_error_to_errno(error);
1321
1322         return error;
1323 }
1324
1325 /*
1326  * Repoint ip->cluster's chains to cluster's chains and fixup the default
1327  * focus.  All items, valid or invalid, are repointed.  hammer2_xop_start()
1328  * filters out invalid or non-matching elements.
1329  *
1330  * Caller must hold the inode and cluster exclusive locked, if not NULL,
1331  * must also be locked.
1332  *
1333  * Cluster may be NULL to clean out any chains in ip->cluster.
1334  */
1335 void
1336 hammer2_inode_repoint(hammer2_inode_t *ip, hammer2_inode_t *pip,
1337                       hammer2_cluster_t *cluster)
1338 {
1339         hammer2_chain_t *dropch[HAMMER2_MAXCLUSTER];
1340         hammer2_chain_t *ochain;
1341         hammer2_chain_t *nchain;
1342         int i;
1343
1344         bzero(dropch, sizeof(dropch));
1345
1346         /*
1347          * Replace chains in ip->cluster with chains from cluster and
1348          * adjust the focus if necessary.
1349          *
1350          * NOTE: nchain and/or ochain can be NULL due to gaps
1351          *       in the cluster arrays.
1352          */
1353         hammer2_spin_ex(&ip->cluster_spin);
1354         for (i = 0; cluster && i < cluster->nchains; ++i) {
1355                 /*
1356                  * Do not replace elements which are the same.  Also handle
1357                  * element count discrepancies.
1358                  */
1359                 nchain = cluster->array[i].chain;
1360                 if (i < ip->cluster.nchains) {
1361                         ochain = ip->cluster.array[i].chain;
1362                         if (ochain == nchain)
1363                                 continue;
1364                 } else {
1365                         ochain = NULL;
1366                 }
1367
1368                 /*
1369                  * Make adjustments
1370                  */
1371                 ip->cluster.array[i].chain = nchain;
1372                 ip->cluster.array[i].flags &= ~HAMMER2_CITEM_INVALID;
1373                 ip->cluster.array[i].flags |= cluster->array[i].flags &
1374                                               HAMMER2_CITEM_INVALID;
1375                 if (nchain)
1376                         hammer2_chain_ref(nchain);
1377                 dropch[i] = ochain;
1378         }
1379
1380         /*
1381          * Release any left-over chains in ip->cluster.
1382          */
1383         while (i < ip->cluster.nchains) {
1384                 nchain = ip->cluster.array[i].chain;
1385                 if (nchain) {
1386                         ip->cluster.array[i].chain = NULL;
1387                         ip->cluster.array[i].flags |= HAMMER2_CITEM_INVALID;
1388                 }
1389                 dropch[i] = nchain;
1390                 ++i;
1391         }
1392
1393         /*
1394          * Fixup fields.  Note that the inode-embedded cluster is never
1395          * directly locked.
1396          */
1397         if (cluster) {
1398                 ip->cluster.nchains = cluster->nchains;
1399                 ip->cluster.focus = cluster->focus;
1400                 ip->cluster.flags = cluster->flags & ~HAMMER2_CLUSTER_LOCKED;
1401         } else {
1402                 ip->cluster.nchains = 0;
1403                 ip->cluster.focus = NULL;
1404                 ip->cluster.flags &= ~HAMMER2_CLUSTER_ZFLAGS;
1405         }
1406
1407         hammer2_spin_unex(&ip->cluster_spin);
1408
1409         /*
1410          * Cleanup outside of spinlock
1411          */
1412         while (--i >= 0) {
1413                 if (dropch[i])
1414                         hammer2_chain_drop(dropch[i]);
1415         }
1416 }
1417
1418 /*
1419  * Repoint a single element from the cluster to the ip.  Used by the
1420  * synchronization threads to piecemeal update inodes.  Does not change
1421  * focus and requires inode to be re-locked to clean-up flags (XXX).
1422  */
1423 void
1424 hammer2_inode_repoint_one(hammer2_inode_t *ip, hammer2_cluster_t *cluster,
1425                           int idx)
1426 {
1427         hammer2_chain_t *ochain;
1428         hammer2_chain_t *nchain;
1429         int i;
1430
1431         hammer2_spin_ex(&ip->cluster_spin);
1432         KKASSERT(idx < cluster->nchains);
1433         if (idx < ip->cluster.nchains) {
1434                 ochain = ip->cluster.array[idx].chain;
1435                 nchain = cluster->array[idx].chain;
1436         } else {
1437                 ochain = NULL;
1438                 nchain = cluster->array[idx].chain;
1439                 for (i = ip->cluster.nchains; i <= idx; ++i) {
1440                         bzero(&ip->cluster.array[i],
1441                               sizeof(ip->cluster.array[i]));
1442                         ip->cluster.array[i].flags |= HAMMER2_CITEM_INVALID;
1443                 }
1444                 ip->cluster.nchains = idx + 1;
1445         }
1446         if (ochain != nchain) {
1447                 /*
1448                  * Make adjustments.
1449                  */
1450                 ip->cluster.array[idx].chain = nchain;
1451                 ip->cluster.array[idx].flags &= ~HAMMER2_CITEM_INVALID;
1452                 ip->cluster.array[idx].flags |= cluster->array[idx].flags &
1453                                                 HAMMER2_CITEM_INVALID;
1454         }
1455         hammer2_spin_unex(&ip->cluster_spin);
1456         if (ochain != nchain) {
1457                 if (nchain)
1458                         hammer2_chain_ref(nchain);
1459                 if (ochain)
1460                         hammer2_chain_drop(ochain);
1461         }
1462 }
1463
1464 /*
1465  * Called with a locked inode to finish unlinking an inode after xop_unlink
1466  * had been run.  This function is responsible for decrementing nlinks.
1467  *
1468  * We don't bother decrementing nlinks if the file is not open and this was
1469  * the last link.
1470  *
1471  * If the inode is a hardlink target it's chain has not yet been deleted,
1472  * otherwise it's chain has been deleted.
1473  *
1474  * If isopen then any prior deletion was not permanent and the inode is
1475  * left intact with nlinks == 0;
1476  */
1477 int
1478 hammer2_inode_unlink_finisher(hammer2_inode_t *ip, int isopen)
1479 {
1480         hammer2_pfs_t *pmp;
1481         int error;
1482
1483         pmp = ip->pmp;
1484
1485         /*
1486          * Decrement nlinks.  If this is the last link and the file is
1487          * not open we can just delete the inode and not bother dropping
1488          * nlinks to 0 (avoiding unnecessary block updates).
1489          */
1490         if (ip->meta.nlinks == 1) {
1491                 atomic_set_int(&ip->flags, HAMMER2_INODE_ISUNLINKED);
1492                 if (isopen == 0)
1493                         goto killit;
1494         }
1495
1496         hammer2_inode_modify(ip);
1497         --ip->meta.nlinks;
1498         if ((int64_t)ip->meta.nlinks < 0)
1499                 ip->meta.nlinks = 0;    /* safety */
1500
1501         /*
1502          * If nlinks is not zero we are done.  However, this should only be
1503          * possible with a hardlink target.  If the inode is an embedded
1504          * hardlink nlinks should have dropped to zero, warn and proceed
1505          * with the next step.
1506          */
1507         if (ip->meta.nlinks) {
1508                 if ((ip->meta.name_key & HAMMER2_DIRHASH_VISIBLE) == 0)
1509                         return 0;
1510                 kprintf("hammer2_inode_unlink: nlinks was not 0 (%jd)\n",
1511                         (intmax_t)ip->meta.nlinks);
1512                 return 0;
1513         }
1514
1515         if (ip->vp)
1516                 hammer2_knote(ip->vp, NOTE_DELETE);
1517
1518         /*
1519          * nlinks is now an implied zero, delete the inode if not open.
1520          * We avoid unnecessary media updates by not bothering to actually
1521          * decrement nlinks for the 1->0 transition
1522          *
1523          * Put the inode on the sideq to ensure that any disconnected chains
1524          * get properly flushed (so they can be freed).  Defer the deletion
1525          * to the sync code, doing it now will desynchronize the inode from
1526          * related directory entries (which is bad).
1527          *
1528          * NOTE: killit can be reached without modifying the inode, so
1529          *       make sure that it is on the SIDEQ.
1530          */
1531         if (isopen == 0) {
1532 #if 0
1533                 hammer2_xop_destroy_t *xop;
1534 #endif
1535
1536 killit:
1537                 atomic_set_int(&ip->flags, HAMMER2_INODE_DELETING);
1538                 hammer2_inode_delayed_sideq(ip);
1539 #if 0
1540                 xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
1541                 hammer2_xop_start(&xop->head, &hammer2_inode_destroy_desc);
1542                 error = hammer2_xop_collect(&xop->head, 0);
1543                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1544 #endif
1545         }
1546         error = 0;      /* XXX */
1547
1548         return error;
1549 }
1550
1551 /*
1552  * Mark an inode as being modified, meaning that the caller will modify
1553  * ip->meta.
1554  *
1555  * If a vnode is present we set the vnode dirty and the nominal filesystem
1556  * sync will also handle synchronizing the inode meta-data.  If no vnode
1557  * is present we must ensure that the inode is on pmp->sideq.
1558  *
1559  * NOTE: We must always queue the inode to the sideq.  This allows H2 to
1560  *       shortcut vsyncscan() and flush inodes and their related vnodes
1561  *       in a two stages.  H2 still calls vfsync() for each vnode.
1562  *
1563  * NOTE: No mtid (modify_tid) is passed into this routine.  The caller is
1564  *       only modifying the in-memory inode.  A modify_tid is synchronized
1565  *       later when the inode gets flushed.
1566  *
1567  * NOTE: As an exception to the general rule, the inode MAY be locked
1568  *       shared for this particular call.
1569  */
1570 void
1571 hammer2_inode_modify(hammer2_inode_t *ip)
1572 {
1573         atomic_set_int(&ip->flags, HAMMER2_INODE_MODIFIED);
1574         if (ip->vp)
1575                 vsetisdirty(ip->vp);
1576         if (ip->pmp && (ip->flags & HAMMER2_INODE_NOSIDEQ) == 0)
1577                 hammer2_inode_delayed_sideq(ip);
1578 }
1579
1580 /*
1581  * Synchronize the inode's frontend state with the chain state prior
1582  * to any explicit flush of the inode or any strategy write call.  This
1583  * does not flush the inode's chain or its sub-topology to media (higher
1584  * level layers are responsible for doing that).
1585  *
1586  * Called with a locked inode inside a normal transaction.
1587  *
1588  * inode must be locked.
1589  */
1590 int
1591 hammer2_inode_chain_sync(hammer2_inode_t *ip)
1592 {
1593         int error;
1594
1595         error = 0;
1596         if (ip->flags & (HAMMER2_INODE_RESIZED | HAMMER2_INODE_MODIFIED)) {
1597                 hammer2_xop_fsync_t *xop;
1598
1599                 xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
1600                 xop->clear_directdata = 0;
1601                 if (ip->flags & HAMMER2_INODE_RESIZED) {
1602                         if ((ip->meta.op_flags & HAMMER2_OPFLAG_DIRECTDATA) &&
1603                             ip->meta.size > HAMMER2_EMBEDDED_BYTES) {
1604                                 ip->meta.op_flags &= ~HAMMER2_OPFLAG_DIRECTDATA;
1605                                 xop->clear_directdata = 1;
1606                         }
1607                         xop->osize = ip->osize;
1608                 } else {
1609                         xop->osize = ip->meta.size;     /* safety */
1610                 }
1611                 xop->ipflags = ip->flags;
1612                 xop->meta = ip->meta;
1613
1614                 atomic_clear_int(&ip->flags, HAMMER2_INODE_RESIZED |
1615                                              HAMMER2_INODE_MODIFIED);
1616                 hammer2_xop_start(&xop->head, &hammer2_inode_chain_sync_desc);
1617                 error = hammer2_xop_collect(&xop->head, 0);
1618                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1619                 if (error == HAMMER2_ERROR_ENOENT)
1620                         error = 0;
1621                 if (error) {
1622                         kprintf("hammer2: unable to fsync inode %p\n", ip);
1623                         /*
1624                         atomic_set_int(&ip->flags,
1625                                        xop->ipflags & (HAMMER2_INODE_RESIZED |
1626                                                        HAMMER2_INODE_MODIFIED));
1627                         */
1628                         /* XXX return error somehow? */
1629                 }
1630         }
1631         return error;
1632 }
1633
1634 /*
1635  * When an inode is flagged INODE_CREATING its chains have not actually
1636  * been inserting into the on-media tree yet.
1637  */
1638 int
1639 hammer2_inode_chain_ins(hammer2_inode_t *ip)
1640 {
1641         int error;
1642
1643         error = 0;
1644         if (ip->flags & HAMMER2_INODE_CREATING) {
1645                 hammer2_xop_create_t *xop;
1646
1647                 atomic_clear_int(&ip->flags, HAMMER2_INODE_CREATING);
1648                 xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
1649                 xop->lhc = ip->meta.inum;
1650                 xop->flags = 0;
1651                 hammer2_xop_start(&xop->head, &hammer2_inode_create_ins_desc);
1652                 error = hammer2_xop_collect(&xop->head, 0);
1653                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1654                 if (error == HAMMER2_ERROR_ENOENT)
1655                         error = 0;
1656                 if (error) {
1657                         kprintf("hammer2: backend unable to "
1658                                 "insert inode %p %ld\n", ip, ip->meta.inum);
1659                         /* XXX return error somehow? */
1660                 }
1661         }
1662         return error;
1663 }
1664
1665 /*
1666  * When an inode is flagged INODE_DELETING it has been deleted (no directory
1667  * entry or open refs are left, though as an optimization H2 might leave
1668  * nlinks == 1 to avoid unnecessary block updates).  The backend flush then
1669  * needs to actually remove it from the topology.
1670  *
1671  * NOTE: backend flush must still sync and flush the deleted inode to clean
1672  *       out related chains.
1673  */
1674 int
1675 hammer2_inode_chain_des(hammer2_inode_t *ip)
1676 {
1677         int error;
1678
1679         error = 0;
1680         if (ip->flags & HAMMER2_INODE_DELETING) {
1681                 hammer2_xop_destroy_t *xop;
1682
1683                 atomic_clear_int(&ip->flags, HAMMER2_INODE_DELETING);
1684                 xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING);
1685                 hammer2_xop_start(&xop->head, &hammer2_inode_destroy_desc);
1686                 error = hammer2_xop_collect(&xop->head, 0);
1687                 hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1688
1689                 if (error == HAMMER2_ERROR_ENOENT)
1690                         error = 0;
1691                 if (error) {
1692                         kprintf("hammer2: backend unable to "
1693                                 "insert inode %p %ld\n", ip, ip->meta.inum);
1694                         /* XXX return error somehow? */
1695                 }
1696         }
1697         return error;
1698 }
1699
1700 /*
1701  * Flushes the inode's chain and its sub-topology to media.  Interlocks
1702  * HAMMER2_INODE_DIRTYDATA by clearing it prior to the flush.  Any strategy
1703  * function creating or modifying a chain under this inode will re-set the
1704  * flag.
1705  *
1706  * inode must be locked.
1707  */
1708 int
1709 hammer2_inode_chain_flush(hammer2_inode_t *ip, int flags)
1710 {
1711         hammer2_xop_fsync_t *xop;
1712         int error;
1713
1714         atomic_clear_int(&ip->flags, HAMMER2_INODE_DIRTYDATA);
1715         xop = hammer2_xop_alloc(ip, HAMMER2_XOP_MODIFYING | flags);
1716         hammer2_xop_start(&xop->head, &hammer2_inode_flush_desc);
1717         error = hammer2_xop_collect(&xop->head, HAMMER2_XOP_COLLECT_WAITALL);
1718         hammer2_xop_retire(&xop->head, HAMMER2_XOPMASK_VOP);
1719         if (error == HAMMER2_ERROR_ENOENT)
1720                 error = 0;
1721
1722         return error;
1723 }