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